|
<!DOCTYPE html> |
|
<html lang="fr"> |
|
<head> |
|
<meta charset="UTF-8"> |
|
<meta name="viewport" content="width=device-width, initial-scale=1.0"> |
|
<title>Mariam AI</title> |
|
|
|
|
|
<script src="https://cdn.tailwindcss.com?plugins=forms,typography"></script> |
|
|
|
|
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"> |
|
|
|
|
|
<link rel="preconnect" href="https://fonts.googleapis.com"> |
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> |
|
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet"> |
|
|
|
|
|
<link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>✨</text></svg>"> |
|
|
|
<script> |
|
|
|
tailwind.config = { |
|
darkMode: 'class', |
|
theme: { |
|
extend: { |
|
fontFamily: { |
|
sans: ['Inter', 'system-ui', 'sans-serif'], |
|
mono: ['"JetBrains Mono"', 'monospace'], |
|
}, |
|
colors: { |
|
primary: { 50: '#f0f9ff', 100: '#e0f2fe', 200: '#bae6fd', 300: '#7dd3fc', 400: '#38bdf8', 500: '#0ea5e9', 600: '#0284c7', 700: '#0369a1', 800: '#075985', 900: '#0c4a6e' }, |
|
secondary: { 50: '#f8fafc', 100: '#f1f5f9', 200: '#e2e8f0', 300: '#cbd5e1', 400: '#94a3b8', 500: '#64748b', 600: '#475569', 700: '#334155', 800: '#1e293b', 900: '#0f172a' }, |
|
accent: { 50: '#fdf4ff', 100: '#fae8ff', 200: '#f5d0fe', 300: '#f0abfc', 400: '#e879f9', 500: '#d946ef', 600: '#c026d3', 700: '#a21caf', 800: '#86198f', 900: '#701a75' } |
|
}, |
|
animation: { |
|
'bounce-slow': 'bounce 2s infinite', |
|
'pulse-slow': 'pulse 3s infinite', |
|
'typing': 'typing 1.2s steps(3) infinite', |
|
'message-fade-in': 'message-fade-in 0.3s ease-out', |
|
'pulse-fade': 'pulse-fade 1.2s infinite' |
|
}, |
|
keyframes: { |
|
typing: { |
|
'0%': { width: '0.15em' }, |
|
'50%': { width: '0.7em' }, |
|
'100%': { width: '0.15em' }, |
|
}, |
|
|
|
'message-fade-in': { |
|
from: { opacity: 0, transform: 'translateY(10px)' }, |
|
to: { opacity: 1, transform: 'translateY(0)' }, |
|
}, |
|
'pulse-fade': { |
|
'0%, 100%': { opacity: 0.5 }, |
|
'50%': { opacity: 1 }, |
|
} |
|
} |
|
} |
|
} |
|
} |
|
</script> |
|
|
|
<style> |
|
|
|
html { scroll-behavior: smooth; } |
|
body { font-family: 'Inter', sans-serif; transition: background-color 0.3s ease, color 0.3s ease; } |
|
|
|
|
|
.chat-layout { min-height: calc(100vh - 64px); display: grid; grid-template-rows: 1fr auto; } |
|
|
|
|
|
::-webkit-scrollbar { width: 5px; height: 5px; } |
|
::-webkit-scrollbar-track { background: transparent; } |
|
::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 5px; } |
|
.dark ::-webkit-scrollbar-thumb { background: #475569; } |
|
::-webkit-scrollbar-thumb:hover { background: #94a3b8; } |
|
.dark ::-webkit-scrollbar-thumb:hover { background: #64748b; } |
|
|
|
|
|
.message-bubble { |
|
position: relative; |
|
max-width: 85%; |
|
border-radius: 1rem; |
|
padding: 0.875rem 1rem; |
|
line-height: 1.5; |
|
animation: message-fade-in 0.3s ease-out; |
|
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); |
|
transition: transform 0.2s ease, box-shadow 0.2s ease; |
|
} |
|
.message-bubble:hover { box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05), 0 1px 3px rgba(0, 0, 0, 0.1); } |
|
.dark .message-bubble { box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2); } |
|
.dark .message-bubble:hover { box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2), 0 1px 3px rgba(0, 0, 0, 0.3); } |
|
|
|
.user-message { |
|
border-bottom-right-radius: 0.125rem; |
|
align-self: flex-end; |
|
background: linear-gradient(to bottom right, theme('colors.primary.500'), theme('colors.primary.600')); |
|
color: white; |
|
} |
|
.assistant-message { |
|
border-bottom-left-radius: 0.125rem; |
|
align-self: flex-start; |
|
background-color: theme('colors.secondary.50'); |
|
color: theme('colors.secondary.900'); |
|
border: 1px solid theme('colors.secondary.200'); |
|
} |
|
.dark .assistant-message { |
|
background-color: theme('colors.secondary.800'); |
|
color: theme('colors.secondary.200'); |
|
border-color: theme('colors.secondary.700'); |
|
} |
|
|
|
|
|
|
|
.user-message::after { |
|
content: ''; position: absolute; bottom: -0.5rem; right: 0.125rem; |
|
width: 0.75rem; height: 0.75rem; background: theme('colors.primary.600'); |
|
clip-path: polygon(0 0, 100% 0, 100% 100%); |
|
} |
|
.assistant-message::after { |
|
content: ''; position: absolute; bottom: -0.5rem; left: 0.125rem; |
|
width: 0.75rem; height: 0.75rem; background: theme('colors.secondary.50'); |
|
clip-path: polygon(0 0, 100% 0, 0 100%); |
|
} |
|
.dark .assistant-message::after { background: theme('colors.secondary.800'); } |
|
|
|
|
|
.typing-indicator { display: inline-flex; align-items: center; margin-left: 0.5rem; } |
|
.typing-dot { width: 0.5rem; height: 0.5rem; border-radius: 50%; background-color: currentColor; opacity: 0.7; margin: 0 0.1rem; } |
|
.typing-dot:nth-child(1) { animation: pulse-fade 1.2s 0s infinite; } |
|
.typing-dot:nth-child(2) { animation: pulse-fade 1.2s 0.2s infinite; } |
|
.typing-dot:nth-child(3) { animation: pulse-fade 1.2s 0.4s infinite; } |
|
|
|
|
|
.dark body { background-color: theme('colors.secondary.900'); color: theme('colors.secondary.200'); } |
|
|
|
|
|
.tooltip { position: relative; } |
|
.tooltip .tooltip-text { |
|
visibility: hidden; width: max-content; max-width: 200px; |
|
background-color: theme('colors.secondary.800'); color: theme('colors.secondary.50'); |
|
text-align: center; border-radius: 6px; padding: 0.375rem 0.625rem; |
|
position: absolute; z-index: 1; bottom: 125%; left: 50%; transform: translateX(-50%); |
|
opacity: 0; transition: opacity 0.3s, visibility 0.3s; |
|
font-size: 0.75rem; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); pointer-events: none; |
|
} |
|
.dark .tooltip .tooltip-text { background-color: theme('colors.secondary.600'); color: theme('colors.secondary.100'); } |
|
.tooltip .tooltip-text::after { |
|
content: ""; position: absolute; top: 100%; left: 50%; margin-left: -5px; |
|
border-width: 5px; border-style: solid; border-color: theme('colors.secondary.800') transparent transparent transparent; |
|
} |
|
.dark .tooltip .tooltip-text::after { border-color: theme('colors.secondary.600') transparent transparent transparent; } |
|
.tooltip:hover .tooltip-text { visibility: visible; opacity: 1; } |
|
|
|
|
|
.copy-btn { |
|
position: absolute; top: 0.5rem; right: 0.5rem; opacity: 0; |
|
transition: opacity 0.2s ease, background-color 0.2s ease; z-index: 2; |
|
|
|
} |
|
.message-bubble:hover .copy-btn { opacity: 1; } |
|
|
|
|
|
.file-preview-wrapper { |
|
margin: 0.5rem auto; |
|
position: relative; |
|
overflow: hidden; |
|
border-radius: 0.5rem; |
|
transition: transform 0.2s ease; |
|
background-color: theme('colors.secondary.100'); |
|
display: inline-block; |
|
} |
|
.dark .file-preview-wrapper { background-color: theme('colors.secondary.800'); } |
|
.file-preview-wrapper:hover { transform: scale(1.02); } |
|
.file-preview-wrapper img, .file-preview-wrapper .file-icon-display { |
|
width: 100%; height: auto; display: block; object-fit: cover; |
|
} |
|
.file-icon-display { |
|
padding: 1rem; text-align: center; |
|
} |
|
|
|
|
|
.chip { } |
|
.chip .chip-icon { margin-right: 0.25rem; } |
|
.chip .chip-close { margin-left: 0.25rem; cursor: pointer; opacity: 0.7; transition: opacity 0.2s ease; } |
|
.chip .chip-close:hover { opacity: 1; } |
|
|
|
|
|
.toggle-switch { position: relative; display: inline-block; width: 2.5rem; height: 1.25rem; } |
|
.toggle-switch input { opacity: 0; width: 0; height: 0; } |
|
.toggle-slider { |
|
position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; |
|
background-color: theme('colors.secondary.300'); transition: .4s; border-radius: 1.25rem; |
|
} |
|
.toggle-slider:before { |
|
position: absolute; content: ""; height: 0.875rem; width: 0.875rem; left: 0.25rem; bottom: 0.1875rem; |
|
background-color: white; transition: .4s; border-radius: 50%; |
|
} |
|
input:checked + .toggle-slider { background-color: theme('colors.primary.500'); } |
|
input:focus + .toggle-slider { box-shadow: 0 0 1px theme('colors.primary.500'); } |
|
input:checked + .toggle-slider:before { transform: translateX(1.125rem); } |
|
.dark .toggle-slider { background-color: theme('colors.secondary.600'); } |
|
.dark input:checked + .toggle-slider { background-color: theme('colors.primary.400'); } |
|
.dark input:focus + .toggle-slider { box-shadow: 0 0 1px theme('colors.primary.400'); } |
|
|
|
|
|
.chat-input { transition: all 0.3s ease; border-color: theme('colors.secondary.200'); } |
|
.chat-input:focus { border-color: theme('colors.primary.400'); box-shadow: 0 0 0 3px theme('colors.primary.400/20'); } |
|
.dark .chat-input { background-color: theme('colors.secondary.800'); color: theme('colors.secondary.100'); border-color: theme('colors.secondary.700'); } |
|
.dark .chat-input:focus { border-color: theme('colors.primary.400'); box-shadow: 0 0 0 3px theme('colors.primary.400/20'); } |
|
|
|
|
|
pre { |
|
position: relative; background-color: theme('colors.secondary.100'); |
|
border-radius: 0.5rem; margin: 1rem 0; padding: 1rem; |
|
overflow-x: auto; |
|
} |
|
.dark pre { background-color: theme('colors.secondary.800'); color: theme('colors.secondary.200'); } |
|
code { font-family: theme('fontFamily.mono'); font-size: 0.875rem; } |
|
|
|
|
|
.code-copy-btn { |
|
position: absolute; top: 0.5rem; right: 0.5rem; opacity: 0; |
|
transition: opacity 0.2s ease; |
|
|
|
} |
|
pre:hover .code-copy-btn { opacity: 0.7; } |
|
pre:hover .code-copy-btn:hover { opacity: 1; } |
|
</style> |
|
</head> |
|
<body class="bg-secondary-50 text-secondary-900 dark:bg-secondary-900 dark:text-secondary-200 antialiased"> |
|
|
|
<header class="bg-gradient-to-r from-primary-600 to-primary-800 text-white py-3 px-4 shadow-md sticky top-0 z-20"> {/* Increased z-index */} |
|
<div class="max-w-4xl mx-auto flex justify-between items-center"> |
|
|
|
<div class="flex items-center space-x-2"> |
|
<span class="text-2xl">✨</span> |
|
<h1 class="text-xl font-bold">Mariam AI</h1> |
|
</div> |
|
|
|
|
|
<div class="flex items-center space-x-2 sm:space-x-4"> |
|
|
|
<button id="theme-toggle" class="p-2 rounded-full hover:bg-primary-700/50 transition-colors duration-200 tooltip" aria-label="Changer de thème"> |
|
<i class="fa-solid fa-moon text-lg dark:hidden"></i> {/* Slightly larger icon */} |
|
<i class="fa-solid fa-sun text-lg hidden dark:inline"></i> {/* Slightly larger icon */} |
|
<span class="tooltip-text">Mode clair/sombre</span> |
|
</button> |
|
|
|
|
|
<form action="/clear" method="POST" id="clear-form"> |
|
<button type="submit" class="flex items-center bg-red-500 hover:bg-red-600 text-white text-xs font-semibold py-1.5 px-3 rounded-full transition duration-200 focus:outline-none focus:ring-2 focus:ring-red-400 focus:ring-opacity-75 tooltip"> |
|
<i class="fa-solid fa-trash-can mr-0 sm:mr-1.5"></i> {/* Hide margin on small screens */} |
|
<span class="hidden sm:inline">Effacer</span> |
|
<span class="tooltip-text">Effacer la conversation</span> |
|
</button> |
|
</form> |
|
</div> |
|
</div> |
|
</header> |
|
|
|
|
|
<main class="max-w-4xl mx-auto chat-layout"> |
|
|
|
<section id="chat-messages" class="flex flex-col space-y-4 p-4 overflow-y-auto"> {/* Adjusted spacing slightly */} |
|
|
|
<div id="history-loading" class="text-center py-10"> |
|
<div class="inline-flex items-center px-4 py-2 bg-primary-50 text-primary-700 rounded-lg dark:bg-primary-900/30 dark:text-primary-300"> |
|
<svg class="animate-spin h-5 w-5 mr-3" viewBox="0 0 24 24"> |
|
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle> |
|
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path> |
|
</svg> |
|
<span>Chargement...</span> {/* Shortened text */} |
|
</div> |
|
</div> |
|
|
|
|
|
<div id="loading-indicator" class="flex items-start space-x-2 hidden"> |
|
<div class="w-8 h-8 rounded-full bg-primary-100 flex items-center justify-center flex-shrink-0 dark:bg-primary-900/50"> |
|
<span class="text-lg">✨</span> |
|
</div> |
|
<div class="message-bubble assistant-message flex items-center"> {/* Removed extra classes handled by CSS */} |
|
<span>Mariam réfléchit</span> |
|
<div class="typing-indicator"> |
|
<span class="typing-dot"></span> |
|
<span class="typing-dot"></span> |
|
<span class="typing-dot"></span> |
|
</div> |
|
</div> |
|
</div> |
|
</section> |
|
|
|
|
|
<div class="border-t border-secondary-200 dark:border-secondary-700 sticky bottom-0 bg-secondary-50 dark:bg-secondary-900 z-10"> {/* Made bottom sticky */} |
|
|
|
<div id="error-message" class="bg-red-100 border-l-4 border-red-500 text-red-700 p-3 mx-4 mt-2 rounded-r dark:bg-red-900/30 dark:text-red-300 dark:border-red-600 hidden" role="alert"> {/* Adjusted padding/margin */} |
|
<div class="flex items-center"> |
|
<div class="flex-shrink-0"> |
|
<i class="fa-solid fa-circle-exclamation"></i> |
|
</div> |
|
<div class="ml-2 flex-1"> {/* Adjusted margin */} |
|
<p class="text-sm font-medium" id="error-text"></p> |
|
</div> |
|
<button class="ml-auto -mx-1.5 -my-1.5 p-1.5" id="dismiss-error" aria-label="Fermer"> {/* Adjusted for easier tap */} |
|
<i class="fa-solid fa-xmark"></i> |
|
</button> |
|
</div> |
|
</div> |
|
|
|
|
|
<div id="preview-area" class="px-4 pt-2 pb-1 bg-secondary-100 dark:bg-secondary-800/50 hidden"> {/* Adjusted padding */} |
|
|
|
<div id="file-preview" class="text-center"></div> {/* Centered preview content */} |
|
</div> |
|
|
|
{/* Options Bar - Responsive stacking */} |
|
<div class="flex flex-col sm:flex-row items-start sm:items-center sm:justify-between gap-3 sm:gap-4 px-4 py-2 bg-secondary-100 dark:bg-secondary-800/80 text-sm text-secondary-600 dark:text-secondary-300"> |
|
{/* Options du chat */} |
|
<div class="flex items-center space-x-3 sm:space-x-4"> {/* Adjusted spacing */} |
|
{/* Web Search Toggle */} |
|
<label class="flex items-center cursor-pointer tooltip"> |
|
<span class="mr-1.5 text-xs sm:text-sm font-medium"> {/* Adjusted margin */} |
|
<i class="fa-solid fa-globe mr-1"></i> {/* Adjusted margin */} |
|
<span class="hidden sm:inline">Web</span> {/* Shortened */} |
|
</span> |
|
<span class="toggle-switch"> |
|
<input type="checkbox" id="web_search_toggle" name="web_search" value="true"> |
|
<span class="toggle-slider"></span> |
|
</span> |
|
<span class="tooltip-text">Recherche Web</span> |
|
</label> |
|
|
|
{/* Advanced Reasoning Toggle */} |
|
<label class="flex items-center cursor-pointer tooltip"> |
|
<span class="mr-1.5 text-xs sm:text-sm font-medium text-accent-700 dark:text-accent-300"> {/* Adjusted margin */} |
|
<i class="fa-solid fa-brain mr-1"></i> {/* Adjusted margin */} |
|
<span class="hidden sm:inline">Avancé</span> |
|
<span id="advanced-cooldown-timer" class="text-xs ml-1 hidden"></span> |
|
</span> |
|
<span class="toggle-switch"> |
|
<input type="checkbox" id="advanced_reasoning_toggle" name="advanced_reasoning" value="true"> |
|
<span class="toggle-slider"></span> |
|
</span> |
|
<span class="tooltip-text">Raisonnement avancé (1/min)</span> {/* Shortened */} |
|
</label> |
|
</div> |
|
|
|
{/* Upload Button & File Chip Area */} |
|
<div class="w-full sm:w-auto flex flex-col items-end"> |
|
<label for="file_upload" class="cursor-pointer flex items-center text-primary-600 hover:text-primary-700 dark:text-primary-400 dark:hover:text-primary-300 tooltip"> |
|
<i class="fa-solid fa-paperclip"></i> |
|
<span class="ml-1 hidden sm:inline">Fichier</span> {/* Adjusted margin */} |
|
<input type="file" id="file_upload" name="file" class="hidden" accept=".txt,.pdf,.png,.jpg,.jpeg,.webp,.md"> {/* Added common types */} |
|
<span class="tooltip-text">Joindre (txt, pdf, md, img)</span> {/* Shortened */} |
|
</label> |
|
|
|
{/* File Chip (apparaît quand un fichier est sélectionné) */} |
|
<div id="file-chip" class="chip bg-primary-100 dark:bg-primary-900/50 text-primary-700 dark:text-primary-300 mt-1 hidden"> {/* Adjusted style/margin */} |
|
<i class="fa-solid fa-file chip-icon"></i> |
|
<span id="file-name" class="truncate max-w-[100px] sm:max-w-[140px]"></span> {/* Responsive max-width */} |
|
<i id="clear-file" class="fa-solid fa-xmark chip-close"></i> |
|
</div> |
|
</div> |
|
</div> |
|
|
|
{/* Chat Input Form */} |
|
<form id="chat-form" class="p-3 sm:p-4 bg-white dark:bg-secondary-900"> |
|
<div class="relative flex items-center"> {/* Use flex to align input and button */} |
|
<input |
|
type="text" |
|
id="prompt" |
|
name="prompt" |
|
class="chat-input flex-1 w-full pl-4 pr-12 py-2.5 rounded-full border focus:outline-none text-sm sm:text-base" /* Adjusted padding */ |
|
placeholder="Votre message..." /* Shortened placeholder */ |
|
autocomplete="off" |
|
> |
|
<button |
|
type="submit" |
|
id="send-button" |
|
class="absolute right-1.5 top-1/2 transform -translate-y-1/2 bg-primary-500 hover:bg-primary-600 disabled:bg-primary-300 dark:disabled:bg-primary-700/50 text-white rounded-full w-9 h-9 flex items-center justify-center transition duration-200 focus:outline-none focus:ring-2 focus:ring-primary-400 focus:ring-opacity-50" /* Adjusted size & positioning */ |
|
title="Envoyer" |
|
> |
|
<i class="fa-solid fa-arrow-up text-sm"></i> {/* Changed icon */} |
|
</button> |
|
</div> |
|
{/* Removed helper text for cleaner mobile view, users generally know Enter/Shift+Enter */} |
|
{/* <div class="text-xs text-center mt-2 text-gray-400 dark:text-gray-500"> ... </div> */} |
|
</form> |
|
</div> |
|
</main> |
|
|
|
|
|
<script> |
|
document.addEventListener('DOMContentLoaded', () => { |
|
// Elements |
|
const chatForm = document.getElementById('chat-form'); |
|
const promptInput = document.getElementById('prompt'); |
|
const chatMessages = document.getElementById('chat-messages'); |
|
const loadingIndicator = document.getElementById('loading-indicator'); |
|
const historyLoadingIndicator = document.getElementById('history-loading'); |
|
const errorMessageDiv = document.getElementById('error-message'); |
|
const errorTextP = document.getElementById('error-text'); |
|
const dismissErrorBtn = document.getElementById('dismiss-error'); |
|
const webSearchToggle = document.getElementById('web_search_toggle'); |
|
const fileUpload = document.getElementById('file_upload'); |
|
const fileChip = document.getElementById('file-chip'); |
|
const fileNameSpan = document.getElementById('file-name'); |
|
const clearFileButton = document.getElementById('clear-file'); |
|
const filePreview = document.getElementById('file-preview'); |
|
const previewArea = document.getElementById('preview-area'); |
|
const sendButton = document.getElementById('send-button'); |
|
const clearForm = document.getElementById('clear-form'); |
|
const advancedToggle = document.getElementById('advanced_reasoning_toggle'); |
|
const advancedCooldownTimerSpan = document.getElementById('advanced-cooldown-timer'); |
|
const themeToggleBtn = document.getElementById('theme-toggle'); |
|
|
|
// API endpoints |
|
const API_CHAT_ENDPOINT = '/api/chat'; |
|
const API_HISTORY_ENDPOINT = '/api/history'; |
|
const CLEAR_ENDPOINT = '/clear'; |
|
|
|
// Constantes |
|
const COOLDOWN_DURATION = 60 * 1000; // 60 secondes |
|
|
|
// Variables |
|
let advancedToggleCooldownEndTime = 0; |
|
let isComposing = false; // Pour la composition IME |
|
|
|
// --- Thème --- |
|
function initializeTheme() { |
|
if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) { |
|
document.documentElement.classList.add('dark'); |
|
} else { |
|
document.documentElement.classList.remove('dark'); |
|
} |
|
} |
|
function toggleTheme() { |
|
document.documentElement.classList.toggle('dark'); |
|
localStorage.theme = document.documentElement.classList.contains('dark') ? 'dark' : 'light'; |
|
} |
|
themeToggleBtn.addEventListener('click', toggleTheme); |
|
initializeTheme(); |
|
|
|
// --- Utilitaires --- |
|
function scrollToBottom(smooth = true) { |
|
// Debounce scrolling slightly |
|
setTimeout(() => { |
|
chatMessages.scrollTo({ top: chatMessages.scrollHeight, behavior: smooth ? 'smooth' : 'auto' }); |
|
}, 50); |
|
} |
|
|
|
function showLoading(show) { |
|
loadingIndicator.classList.toggle('hidden', !show); |
|
if(show) { |
|
// Ensure loading indicator is appended correctly if messages were cleared |
|
if (!chatMessages.contains(loadingIndicator)) { |
|
chatMessages.appendChild(loadingIndicator); |
|
} |
|
scrollToBottom(); |
|
} |
|
sendButton.disabled = show; |
|
promptInput.disabled = show; |
|
// Keep file input enabled maybe? Or disable: |
|
// fileUpload.disabled = show; |
|
// clearFileButton.disabled = show; |
|
} |
|
|
|
function displayError(message) { |
|
errorTextP.textContent = message || "Une erreur inconnue est survenue."; |
|
errorMessageDiv.classList.remove('hidden'); |
|
// Auto-dismiss error after some time? Optional. |
|
// setTimeout(() => errorMessageDiv.classList.add('hidden'), 5000); |
|
} |
|
dismissErrorBtn.addEventListener('click', () => errorMessageDiv.classList.add('hidden')); |
|
|
|
function escapeHtml(unsafe) { |
|
// Simple escape, sufficient if backend sanitizes properly |
|
return unsafe |
|
.replace(/&/g, "&") |
|
.replace(/</g, "<") |
|
.replace(/>/g, ">") |
|
.replace(/"/g, """) |
|
.replace(/'/g, "'"); |
|
} |
|
|
|
// --- Gestion des Messages --- |
|
function addMessageToChat(role, content, isHtml = false) { |
|
errorMessageDiv.classList.add('hidden'); // Hide error on new message |
|
|
|
const messageWrapper = document.createElement('div'); |
|
messageWrapper.classList.add('flex', role === 'user' ? 'justify-end' : 'justify-start', 'w-full'); |
|
|
|
let bubbleHtml = ''; |
|
if (role === 'user') { |
|
bubbleHtml = ` |
|
<div class="message-bubble user-message"> |
|
<p class="text-sm sm:text-base whitespace-pre-wrap break-words">${escapeHtml(content)}</p> |
|
</div> |
|
`; |
|
messageWrapper.innerHTML = bubbleHtml; |
|
} else { // Assistant |
|
bubbleHtml = ` |
|
<div class="w-8 h-8 rounded-full bg-primary-100 flex items-center justify-center flex-shrink-0 dark:bg-primary-900/50"> |
|
<span class="text-lg">✨</span> |
|
</div> |
|
<div class="message-bubble assistant-message relative"> |
|
<div class="prose prose-sm sm:prose-base max-w-none dark:prose-invert prose-p:my-2 prose-ul:my-2 prose-ol:my-2 prose-pre:my-3 prose-blockquote:my-2"> {/* Tailwind prose adjustments */} |
|
${isHtml ? content : escapeHtml(content)} |
|
</div> |
|
<button class="copy-btn text-xs bg-white/80 dark:bg-secondary-700/80 backdrop-blur-sm hover:bg-secondary-100 dark:hover:bg-secondary-600 py-1 px-1.5 rounded text-secondary-600 dark:text-secondary-300 flex items-center" title="Copier"> |
|
<i class="fa-regular fa-copy text-xs"></i> |
|
</button> |
|
</div> |
|
`; |
|
messageWrapper.classList.add('items-start', 'space-x-2'); // Align avatar and bubble |
|
messageWrapper.innerHTML = bubbleHtml; |
|
} |
|
|
|
|
|
// Insert before the loading indicator if it exists, otherwise append |
|
const insertionPoint = chatMessages.querySelector('#loading-indicator'); |
|
chatMessages.insertBefore(messageWrapper, insertionPoint); |
|
|
|
// Activate copy buttons (code blocks and message) |
|
activateCopyButtons(messageWrapper); |
|
|
|
if (historyLoadingIndicator.parentNode !== chatMessages) { |
|
scrollToBottom(); |
|
} |
|
} |
|
|
|
function activateCopyButtons(container) { |
|
// Code blocks copy buttons |
|
container.querySelectorAll('pre').forEach(pre => { |
|
if (!pre.querySelector('.code-copy-btn')) { // Avoid adding multiple times |
|
const codeBtn = document.createElement('button'); |
|
codeBtn.className = 'code-copy-btn bg-white/80 dark:bg-secondary-700/80 backdrop-blur-sm hover:bg-secondary-100 dark:hover:bg-secondary-600 text-xs p-1 rounded text-secondary-600 dark:text-secondary-300'; |
|
codeBtn.innerHTML = '<i class="fa-regular fa-copy"></i>'; |
|
codeBtn.title = 'Copier le code'; |
|
codeBtn.addEventListener('click', (e) => { |
|
e.stopPropagation(); |
|
const code = pre.querySelector('code')?.innerText || pre.innerText; |
|
navigator.clipboard.writeText(code).then(() => { |
|
codeBtn.innerHTML = '<i class="fa-solid fa-check text-green-500"></i>'; |
|
setTimeout(() => { codeBtn.innerHTML = '<i class="fa-regular fa-copy"></i>'; }, 2000); |
|
}); |
|
}); |
|
pre.appendChild(codeBtn); |
|
} |
|
}); |
|
|
|
// Message copy button |
|
const copyBtn = container.querySelector('.copy-btn'); |
|
if (copyBtn) { |
|
copyBtn.addEventListener('click', (e) => { |
|
e.stopPropagation(); |
|
const textContent = container.querySelector('.prose')?.innerText || container.querySelector('p')?.innerText || ''; |
|
if (textContent) { |
|
navigator.clipboard.writeText(textContent).then(() => { |
|
copyBtn.innerHTML = '<i class="fa-solid fa-check text-green-500 text-xs"></i>'; |
|
setTimeout(() => { copyBtn.innerHTML = '<i class="fa-regular fa-copy text-xs"></i>'; }, 2000); |
|
}); |
|
} |
|
}); |
|
} |
|
} |
|
|
|
|
|
// --- Cooldown --- |
|
function startAdvancedCooldownTimer() { |
|
advancedToggle.disabled = true; |
|
advancedToggleCooldownEndTime = Date.now() + COOLDOWN_DURATION; |
|
const parentLabel = advancedToggle.closest('label'); |
|
if(parentLabel) parentLabel.classList.add('opacity-50', 'cursor-not-allowed'); |
|
|
|
const updateTimer = () => { |
|
const now = Date.now(); |
|
if (now >= advancedToggleCooldownEndTime) { |
|
clearInterval(intervalId); |
|
advancedCooldownTimerSpan.classList.add('hidden'); |
|
advancedToggle.disabled = false; |
|
if(parentLabel) parentLabel.classList.remove('opacity-50', 'cursor-not-allowed'); |
|
advancedToggleCooldownEndTime = 0; |
|
} else { |
|
const remainingSeconds = Math.ceil((advancedToggleCooldownEndTime - now) / 1000); |
|
advancedCooldownTimerSpan.textContent = `(${remainingSeconds}s)`; |
|
advancedCooldownTimerSpan.classList.remove('hidden'); |
|
} |
|
}; |
|
const intervalId = setInterval(updateTimer, 1000); |
|
updateTimer(); |
|
} |
|
|
|
// --- Chargement Historique --- |
|
async function loadChatHistory() { |
|
historyLoadingIndicator.classList.remove('hidden'); // Use classList for consistency |
|
chatMessages.innerHTML = ''; // Clear previous content before showing loader |
|
chatMessages.appendChild(historyLoadingIndicator); |
|
chatMessages.appendChild(loadingIndicator); // Keep loading indicator structure |
|
loadingIndicator.classList.add('hidden'); |
|
|
|
try { |
|
const response = await fetch(API_HISTORY_ENDPOINT); |
|
if (!response.ok) { |
|
let errorMsg = `Erreur serveur (${response.status})`; |
|
try { errorMsg = (await response.json()).error || errorMsg; } catch (e) {} |
|
throw new Error(errorMsg); |
|
} |
|
const data = await response.json(); |
|
|
|
historyLoadingIndicator.remove(); // Remove history loader first |
|
|
|
if (data.success && Array.isArray(data.history)) { |
|
if (data.history.length === 0) { |
|
addMessageToChat('assistant', "Bonjour ! Comment puis-je vous aider ?", true); // Shorter welcome |
|
} else { |
|
data.history.forEach(message => { |
|
addMessageToChat(message.role, message.text, message.role === 'assistant'); |
|
}); |
|
// Ensure all copy buttons are active after bulk load |
|
chatMessages.querySelectorAll('.message-bubble.assistant-message').forEach(bubble => activateCopyButtons(bubble.closest('.flex.justify-start'))); |
|
} |
|
scrollToBottom(false); // Scroll without smooth animation after history load |
|
} else { |
|
throw new Error(data.error || "Format historique invalide."); |
|
} |
|
} catch (error) { |
|
historyLoadingIndicator.remove(); |
|
addMessageToChat('assistant', `Impossible de charger l'historique: ${error.message}. Vous pouvez commencer une nouvelle conversation.`, true); |
|
// displayError(`Impossible de charger l'historique: ${error.message}`); // Option: show error bar instead |
|
} finally { |
|
// Ensure loading indicator is correctly placed at the end |
|
chatMessages.appendChild(loadingIndicator); |
|
loadingIndicator.classList.add('hidden'); |
|
promptInput.focus(); |
|
} |
|
} |
|
|
|
// --- Gestion Fichiers --- |
|
function clearFileInput() { |
|
fileUpload.value = ''; // Reset file input |
|
fileChip.classList.add('hidden'); |
|
previewArea.classList.add('hidden'); |
|
filePreview.innerHTML = ''; |
|
} |
|
|
|
function getFileIcon(fileType) { |
|
if (fileType.includes('pdf')) return 'fa-file-pdf'; |
|
if (fileType.includes('text') || fileType.includes('markdown')) return 'fa-file-lines'; // Added markdown |
|
if (fileType.startsWith('image/')) return 'fa-file-image'; // Specific image icon |
|
return 'fa-file'; // Default |
|
} |
|
|
|
function formatFileSize(bytes) { |
|
if (bytes < 1024) return bytes + ' o'; |
|
const i = Math.floor(Math.log(bytes) / Math.log(1024)); |
|
return parseFloat((bytes / Math.pow(1024, i)).toFixed(1)) + ' ' + ['Ko', 'Mo', 'Go'][i-1]; // More robust |
|
} |
|
|
|
fileUpload.addEventListener('change', () => { |
|
if (fileUpload.files.length > 0) { |
|
const file = fileUpload.files[0]; |
|
fileNameSpan.textContent = file.name; |
|
fileNameSpan.title = file.name; // Tooltip for long names |
|
fileChip.classList.remove('hidden'); |
|
|
|
previewArea.classList.remove('hidden'); // Show preview area container |
|
filePreview.innerHTML = ''; // Clear previous preview |
|
|
|
if (file.type.startsWith('image/')) { |
|
const reader = new FileReader(); |
|
reader.onload = (e) => { |
|
filePreview.innerHTML = ` |
|
<div class="file-preview-wrapper max-w-xs inline-block"> {/* Added wrapper and max-width */} |
|
<img src="${e.target.result}" alt="Aperçu" class="rounded"> {/* Added rounded */} |
|
</div>`; |
|
}; |
|
reader.readAsDataURL(file); |
|
} else { |
|
// Display icon and info for non-images |
|
filePreview.innerHTML = ` |
|
<div class="file-preview-wrapper max-w-xs inline-block"> {/* Added wrapper */} |
|
<div class="file-icon-display rounded"> {/* Added container div */} |
|
<i class="fa-solid ${getFileIcon(file.type)} text-4xl text-secondary-500 dark:text-secondary-400 mb-2"></i> |
|
<p class="text-xs text-secondary-500 dark:text-secondary-400">${formatFileSize(file.size)}</p> |
|
</div> |
|
</div>`; |
|
} |
|
scrollToBottom(); // Scroll down to show preview if needed |
|
} else { |
|
clearFileInput(); |
|
} |
|
}); |
|
|
|
clearFileButton.addEventListener('click', () => { |
|
clearFileInput(); |
|
}); |
|
|
|
|
|
// --- Soumission Formulaire --- |
|
chatForm.addEventListener('submit', async (e) => { |
|
e.preventDefault(); |
|
const prompt = promptInput.value.trim(); |
|
const file = fileUpload.files[0]; |
|
const useWebSearch = webSearchToggle.checked; |
|
const useAdvanced = advancedToggle.checked; |
|
|
|
if (!prompt && !file) { |
|
// Maybe flash the input border instead of error message? |
|
promptInput.classList.add('border-red-500'); |
|
setTimeout(() => promptInput.classList.remove('border-red-500'), 1000); |
|
promptInput.focus(); |
|
return; |
|
} |
|
|
|
errorMessageDiv.classList.add('hidden'); |
|
|
|
if (useAdvanced) { |
|
const now = Date.now(); |
|
if (now < advancedToggleCooldownEndTime) { |
|
const remainingSeconds = Math.ceil((advancedToggleCooldownEndTime - now) / 1000); |
|
displayError(`Mode avancé dispo dans ${remainingSeconds}s.`); |
|
return; |
|
} |
|
} |
|
|
|
// Add user message immediately |
|
// Combine prompt and file info for user message if needed |
|
let userMessageText = prompt; |
|
if (file && !prompt) { |
|
userMessageText = `[Analyse du fichier: ${file.name}]`; // Message if only file |
|
} else if (file && prompt) { |
|
userMessageText = prompt; // Just show prompt, file context is implied or handled by backend |
|
} |
|
addMessageToChat('user', userMessageText); |
|
|
|
// Prepare data |
|
const formData = new FormData(); |
|
formData.append('prompt', prompt); // Send empty prompt if only file |
|
formData.append('web_search', useWebSearch); |
|
formData.append('advanced_reasoning', useAdvanced); |
|
if (file) { formData.append('file', file); } |
|
|
|
showLoading(true); |
|
promptInput.value = ''; // Clear input AFTER getting value |
|
clearFileInput(); // Clear file AFTER getting value |
|
|
|
// Reset toggles? Maybe not web search, but advanced yes. |
|
if (useAdvanced) { |
|
advancedToggle.checked = false; // Uncheck after use |
|
startAdvancedCooldownTimer(); |
|
} |
|
// webSearchToggle.checked = false; // Decide if this should reset |
|
|
|
try { |
|
const response = await fetch(API_CHAT_ENDPOINT, { method: 'POST', body: formData }); |
|
const data = await response.json(); |
|
|
|
if (!response.ok) { throw new Error(data.error || `Erreur ${response.status}`); } |
|
if (data.success && data.message) { addMessageToChat('assistant', data.message, true); } |
|
else { throw new Error(data.error || "Réponse invalide."); } |
|
|
|
} catch (error) { |
|
addMessageToChat('assistant', `Désolé, une erreur est survenue: ${error.message}`, true); // Show error as assistant message |
|
// displayError(error.message); // Or show in error bar |
|
} finally { |
|
showLoading(false); |
|
promptInput.focus(); |
|
} |
|
}); |
|
|
|
|
|
// --- Effacement Conversation --- |
|
clearForm.addEventListener('submit', async (e) => { |
|
e.preventDefault(); |
|
const clearButton = e.target.querySelector('button'); |
|
const originalButtonContent = clearButton.innerHTML; |
|
|
|
// Simple confirmation |
|
if (!confirm("Effacer toute la conversation ?")) { |
|
return; |
|
} |
|
|
|
clearButton.innerHTML = '<i class="fa-solid fa-spinner fa-spin px-2.5"></i>'; // Spinner with padding |
|
clearButton.disabled = true; |
|
|
|
try { |
|
const response = await fetch(CLEAR_ENDPOINT, { |
|
method: 'POST', |
|
headers: { 'X-Requested-With': 'XMLHttpRequest' } // Identify as AJAX if needed by backend |
|
}); |
|
const data = await response.json(); |
|
|
|
if (response.ok && data.success) { |
|
// Clear messages visually, then add welcome message |
|
chatMessages.innerHTML = ''; |
|
// Re-add persistent elements |
|
chatMessages.appendChild(historyLoadingIndicator); // Should be removed, but add structure back |
|
chatMessages.appendChild(loadingIndicator); |
|
historyLoadingIndicator.classList.add('hidden'); // Hide them |
|
loadingIndicator.classList.add('hidden'); |
|
|
|
addMessageToChat('assistant', "Conversation effacée.", true); |
|
errorMessageDiv.classList.add('hidden'); |
|
} else { |
|
throw new Error(data.error || "Erreur serveur."); |
|
} |
|
} catch (error) { |
|
displayError(`Erreur effacement: ${error.message}`); |
|
} finally { |
|
clearButton.innerHTML = originalButtonContent; |
|
clearButton.disabled = false; |
|
promptInput.focus(); |
|
} |
|
}); |
|
|
|
// --- Raccourcis Clavier & IME --- |
|
promptInput.addEventListener('keydown', (e) => { |
|
if (isComposing) return; |
|
if (e.key === 'Enter' && !e.shiftKey && !sendButton.disabled) { |
|
e.preventDefault(); |
|
chatForm.requestSubmit(); // Use requestSubmit for proper form lifecycle |
|
} |
|
}); |
|
promptInput.addEventListener('compositionstart', () => { isComposing = true; }); |
|
promptInput.addEventListener('compositionend', () => { isComposing = false; }); |
|
|
|
// --- Initialisation --- |
|
loadChatHistory(); |
|
|
|
// Observe theme changes from other tabs/system |
|
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => { |
|
if (!('theme' in localStorage)) { // Only if user hasn't set preference |
|
initializeTheme(); |
|
} |
|
}); |
|
}); |
|
</script> |
|
</body> |
|
</html> |