Docfile's picture
Create index.html
fe4735c verified
raw
history blame
19.5 kB
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Solution mathématique intelligente pour résoudre vos problèmes">
<title>Mariam M-0 | Solution Mathématique</title>
<!-- Preload des ressources critiques -->
<link rel="preload" href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;700&display=swap" as="style">
<link rel="preload" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css" as="style">
<link rel="preload" href="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.0/gsap.min.js" as="script">
<!-- Chargement asynchrone des styles -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;700&display=swap" rel="stylesheet">
<!-- Scripts différés -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.0/gsap.min.js" defer></script>
<script src="https://cdn.jsdelivr.net/npm/marked/lib/marked.umd.min.js" defer></script>
<!-- MathJax config et chargement optimisé -->
<script>
window.MathJax = {
tex: {
inlineMath: [['$', '$']],
displayMath: [['$$', '$$']],
processEscapes: true,
packages: {'[+]': ['autoload','ams']}
},
options: {
enableMenu: false,
messageStyle: 'none'
},
startup: {
pageReady: () => {
window.mathJaxReady = true;
window.dispatchEvent(new CustomEvent('mathJaxReady'));
}
}
};
</script>
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js" id="MathJax-script" async></script>
<style>
/* Styles critiques chargés en premier */
:root {
--primary: #3b82f6;
--primary-dark: #2563eb;
--animation-timing: 0.3s;
}
/* Optimisation des performances d'animation */
.optimize-animation {
will-change: transform, opacity;
transform: translateZ(0);
backface-visibility: hidden;
}
/* Styles de base */
body {
font-family: 'Space Grotesk', -apple-system, BlinkMacSystemFont, sans-serif;
background: linear-gradient(135deg, #f0f4ff 0%, #ffffff 100%);
min-height: 100vh;
overflow-x: hidden;
}
/* Media queries pour le responsive */
@media (max-width: 640px) {
.container {
padding: 1rem;
}
.title {
font-size: 1.75rem;
}
.upload-container {
padding: 1rem;
}
}
@media (min-width: 641px) and (max-width: 1024px) {
.container {
padding: 1.5rem;
}
.upload-container {
padding: 1.5rem;
}
}
/* Animations optimisées */
@keyframes fadeInUp {
from {
opacity: 0;
transform: translate3d(0, 20px, 0);
}
to {
opacity: 1;
transform: translate3d(0, 0, 0);
}
}
.fade-in-up {
animation: fadeInUp var(--animation-timing) cubic-bezier(0.4, 0, 0.2, 1) forwards;
}
/* Styles pour le loader et les composants UI */
.loader {
width: 48px;
height: 48px;
border: 3px solid var(--primary);
border-bottom-color: transparent;
border-radius: 50%;
display: inline-block;
animation: rotation 1s linear infinite;
}
@keyframes rotation {
to {
transform: rotate(360deg);
}
}
.upload-area {
border: 2px dashed #d1d5db;
transition: all var(--animation-timing) cubic-bezier(0.4, 0, 0.2, 1);
background: rgba(255, 255, 255, 0.8);
backdrop-filter: blur(8px);
}
.upload-area:hover {
border-color: var(--primary);
transform: scale(1.01);
}
/* Style pour le contenu mathématique */
.math-content {
overflow-x: auto;
-webkit-overflow-scrolling: touch;
max-width: 100%;
}
/* Optimisations pour le scroll */
.smooth-scroll {
scroll-behavior: smooth;
-webkit-overflow-scrolling: touch;
}
</style>
</head>
<body>
<div class="container max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
<header class="py-6 sm:py-8 md:py-10 text-center optimize-animation fade-in-up">
<h1 class="title text-3xl sm:text-4xl md:text-5xl font-bold text-blue-600">Mariam M-0</h1>
<p class="mt-2 text-gray-600">Solution Mathématique/Physique/Chimie Intelligente</p>
</header>
<main class="space-y-6 sm:space-y-8">
<form id="problemForm" class="space-y-4 sm:space-y-6" novalidate>
<div class="upload-area p-4 sm:p-6 md:p-8 text-center relative rounded-lg optimize-animation">
<input
type="file"
id="imageInput"
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-12 sm:w-16 h-12 sm:h-16 mx-auto border-2 border-blue-400 rounded-full flex items-center justify-center">
<svg class="w-6 sm:w-8 h-6 sm:h-8 text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<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>
<div id="imagePreview" class="hidden text-center">
<img id="previewImage" class="max-w-xs sm:max-w-sm md:max-w-md mx-auto rounded-lg shadow-lg optimize-animation" alt="Prévisualisation">
</div>
<button type="submit" class="w-full py-3 px-4 bg-blue-600 text-white font-medium rounded-lg transition-all duration-300 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
Résoudre le problème
</button>
</form>
<div id="loader" class="hidden mt-8 text-center optimize-animation">
<span class="loader"></span>
<p class="mt-4 text-gray-600">Analyse en cours...</p>
</div>
<section id="solution" class="hidden mt-8 space-y-6">
<div class="border-t pt-4">
<button id="thoughtsToggle" class="w-full flex justify-between items-center p-2 hover:bg-gray-50 rounded-lg transition-colors">
<span class="font-medium text-gray-700">Processus de Réflexion</span>
<span id="timestamp" class="text-blue-600 text-sm"></span>
</button>
<div id="thoughtsBox" class="thought-box">
<div id="thoughtsContent" class="p-4 text-gray-600 math-content"></div>
</div>
</div>
<div class="border-t pt-6">
<h3 class="text-xl font-bold text-gray-800 mb-4">Solution</h3>
<div id="answerContent" class="text-gray-700 math-content smooth-scroll"></div>
</div>
</section>
</main>
</div>
<script>
// Gestionnaire d'événements principal avec gestion améliorée des erreurs et de la performance
class MathSolver {
constructor() {
this.form = document.getElementById('problemForm');
this.imageInput = document.getElementById('imageInput');
this.imagePreview = document.getElementById('imagePreview');
this.previewImage = document.getElementById('previewImage');
this.loader = document.getElementById('loader');
this.solution = document.getElementById('solution');
this.thoughtsContent = document.getElementById('thoughtsContent');
this.answerContent = document.getElementById('answerContent');
this.thoughtsToggle = document.getElementById('thoughtsToggle');
this.thoughtsBox = document.getElementById('thoughtsBox');
this.timestamp = document.getElementById('timestamp');
this.startTime = null;
this.timerInterval = null;
this.thoughtsBuffer = '';
this.answerBuffer = '';
this.currentMode = null;
this.updateTimeout = null;
this.uploadArea = document.querySelector('.upload-area');
this.init();
}
init() {
this.setupEventListeners();
this.setupMarkedOptions();
this.setupIntersectionObserver();
}
setupEventListeners() {
// Utilisation des event listeners passifs pour améliorer les performances
this.form.addEventListener('submit', this.handleSubmit.bind(this));
this.imageInput.addEventListener('change', (e) => this.handleFileSelect(e.target.files[0]), { passive: true });
this.thoughtsToggle.addEventListener('click', this.toggleThoughts.bind(this), { passive: true });
// Gestion optimisée du drag & drop
this.setupDragAndDrop();
// Gestionnaire de redimensionnement optimisé
let resizeTimeout;
window.addEventListener('resize', () => {
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(() => this.handleResize(), 150);
}, { passive: true });
}
setupMarkedOptions() {
marked.setOptions({
gfm: true,
breaks: true,
sanitize: true,
smartLists: true,
smartypants: true
});
}
setupIntersectionObserver() {
const observer = new IntersectionObserver(
(entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('fade-in-up');
observer.unobserve(entry.target);
}
});
},
{ threshold: 0.1 }
);
document.querySelectorAll('.optimize-animation').forEach(el => observer.observe(el));
}
setupDragAndDrop() {
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
this.uploadArea.addEventListener(eventName, (e) => {
e.preventDefault();
e.stopPropagation();
}, { passive: false });
});
['dragenter', 'dragover'].forEach(eventName => {
this.uploadArea.addEventListener(eventName, () => {
this.uploadArea.classList.add('border-blue-400');
}, { passive: true });
});
['dragleave', 'drop'].forEach(eventName => {
this.uploadArea.addEventListener(eventName, () => {
this.uploadArea.classList.remove('border-blue-400');
}, { passive: true });
});
this.uploadArea.addEventListener('drop', (e) => {
const file = e.dataTransfer.files[0];
if (file) this.handleFileSelect(file);
}, { passive: false });
}
handleFileSelect(file) {
if (!file) return;
// Validation du type de fichier
if (!file.type.startsWith('image/')) {
this.showError('Veuillez sélectionner une image valide.');
return;
}
// Utilisation de createObjectURL pour une meilleure performance
const objectUrl = URL.createObjectURL(file);
this.previewImage.onload = () => {
URL.revokeObjectURL(objectUrl);
this.imagePreview.classList.remove('hidden');
requestAnimationFrame(() => {
this.previewImage.classList.add('fade-in-up');
});
};
this.previewImage.src = objectUrl;
}
async handleSubmit(e) {
e.preventDefault();
const file = this.imageInput.files[0];
if (!file) {
this.showError('Veuillez sélectionner une image.');
return;
}
this.startProcessing();
try {
const formData = new FormData();
formData.append('image', file);
const response = await this.sendRequest(formData);
await this.processResponse(response);
} catch (error) {
console.error('Erreur:', error);
this.showError('Une erreur est survenue lors du traitement.');
} finally {
this.stopProcessing();
}
}
async sendRequest(formData) {
const response = await fetch('/solve', {
method: 'POST',
body: formData
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response;
}
async processResponse(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() || '';
for (const line of lines) {
if (!line.startsWith('data:')) continue;
try {
const data = JSON.parse(line.slice(5));
await this.handleStreamData(data);
} catch (error) {
console.error('Erreur parsing JSON:', error);
continue;
}
}
};
try {
while (true) {
const { done, value } = await reader.read();
if (done) {
if (buffer) {
const data = JSON.parse(buffer.slice(5));
await this.handleStreamData(data);
}
break;
}
await processChunk(value);
}
} catch (error) {
throw new Error('Erreur lors du traitement du flux: ' + error.message);
}
}
async handleStreamData(data) {
if (data.mode) {
this.currentMode = data.mode;
this.loader.classList.add('hidden');
this.solution.classList.remove('hidden');
await this.animateSolutionAppearance();
}
if (data.content) {
if (this.currentMode === 'thinking') {
this.thoughtsBuffer += data.content;
} else if (this.currentMode === 'answering') {
this.answerBuffer += data.content;
}
await this.scheduleUpdate();
}
}
async scheduleUpdate() {
if (this.updateTimeout) return;
this.updateTimeout = setTimeout(async () => {
await this.updateDisplay();
this.updateTimeout = null;
}, 100);
}
async updateDisplay() {
// Utilisation de requestAnimationFrame pour les mises à jour visuelles
return new Promise(resolve => {
requestAnimationFrame(async () => {
try {
// Mise à jour du contenu avec sanitization
this.thoughtsContent.innerHTML = DOMPurify.sanitize(marked.parse(this.thoughtsBuffer));
this.answerContent.innerHTML = DOMPurify.sanitize(marked.parse(this.answerBuffer));
// Rendu MathJax optimisé
if (window.mathJaxReady) {
await this.renderMathJax();
}
// Scroll automatique optimisé
this.smoothScroll();
resolve();
} catch (error) {
console.error('Erreur mise à jour affichage:', error);
resolve();
}
});
});
}
async renderMathJax() {
try {
MathJax.startup.document.state(0);
await MathJax.typesetPromise([this.answerContent]);
} catch (error) {
console.error('Erreur rendu MathJax:', error);
}
}
smoothScroll() {
const scrollOptions = {
behavior: 'smooth',
block: 'end'
};
if ('scrollBehavior' in document.documentElement.style) {
this.answerContent.scrollIntoView(scrollOptions);
} else {
// Fallback pour les navigateurs ne supportant pas scroll-behavior
this.answerContent.scrollIntoView(false);
}
}
startProcessing() {
this.resetState();
this.startTimer();
this.loader.classList.remove('hidden');
this.solution.classList.add('hidden');
this.thoughtsBox.classList.add('open');
}
stopProcessing() {
this.stopTimer();
this.loader.classList.add('hidden');
}
resetState() {
this.thoughtsBuffer = '';
this.answerBuffer = '';
this.currentMode = null;
this.thoughtsContent.innerHTML = '';
this.answerContent.innerHTML = '';
}
startTimer() {
this.startTime = Date.now();
this.updateTimestamp();
this.timerInterval = setInterval(() => this.updateTimestamp(), 1000);
}
stopTimer() {
clearInterval(this.timerInterval);
this.startTime = null;
this.timestamp.textContent = '';
}
updateTimestamp() {
if (!this.startTime) return;
const seconds = Math.floor((Date.now() - this.startTime) / 1000);
this.timestamp.textContent = `${seconds}s`;
this.timestamp.classList.add('visible');
}
toggleThoughts() {
this.thoughtsBox.classList.toggle('open');
}
async animateSolutionAppearance() {
return new Promise(resolve => {
requestAnimationFrame(() => {
this.solution.style.opacity = '0';
this.solution.classList.remove('hidden');
requestAnimationFrame(() => {
this.solution.style.transition = 'opacity 0.3s ease';
this.solution.style.opacity = '1';
setTimeout(resolve, 300);
});
});
});
}
handleResize() {
// Ajustements responsifs lors du redimensionnement
const isMobile = window.innerWidth < 640;
const containerPadding = isMobile ? '1rem' : '2rem';
document.querySelector('.container').style.padding = containerPadding;
}
showError(message) {
// Système de notification d'erreur optimisé
const notification = document.createElement('div');
notification.className = 'fixed top-4 right-4 bg-red-500 text-white px-6 py-3 rounded-lg shadow-lg transform translate-y-[-100%] opacity-0 transition-all duration-300';
notification.textContent = message;
document.body.appendChild(notification);
requestAnimationFrame(() => {
notification.style.transform = 'translate(0)';
notification.style.opacity = '1';
setTimeout(() => {
notification.style.transform = 'translate-y-[-100%]';
notification.style.opacity = '0';
setTimeout(() => notification.remove(), 300);
}, 3000);
});
}
}
// Initialisation de l'application avec gestion des erreurs
window.addEventListener('DOMContentLoaded', () => {
try {
window.mathSolver = new MathSolver();
} catch (error) {
console.error('Erreur initialisation:', error);
}
});
</script>
<!-- Script de sanitization -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/2.4.1/purify.min.js" defer></script>
</body>
</html>