Docfile commited on
Commit
254ce1e
·
verified ·
1 Parent(s): 6d14961

Update templates/index.html

Browse files
Files changed (1) hide show
  1. templates/index.html +975 -791
templates/index.html CHANGED
@@ -1,578 +1,565 @@
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
- <title>Mariam AI</title>
 
7
  <!-- Tailwind CSS via CDN -->
8
  <script src="https://cdn.tailwindcss.com?plugins=forms,typography"></script>
 
9
  <!-- Font Awesome pour les icônes -->
10
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
 
11
  <!-- Google Fonts -->
12
  <link rel="preconnect" href="https://fonts.googleapis.com">
13
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
14
  <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">
 
15
  <!-- Favicon (Emoji amélioré) -->
16
  <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>">
 
17
  <script>
 
18
  tailwind.config = {
19
  darkMode: 'class',
20
  theme: {
21
  extend: {
22
  fontFamily: {
23
- sans: ['Inter', 'system-ui', 'sans-serif'],
24
- mono: ['"JetBrains Mono"', 'monospace']
25
  },
26
  colors: {
27
- primary: { 50: '#f0f9ff', 100: '#e0f2fe', 200: '#bae6fd', 300: '#7dd3fc', 400: '#38bdf8', 500: '#0ea5e9', 600: '#0284c7', 700: '#0369a1', 800: '#075985', 900: '#0c4a6e' },
28
- secondary: { 50: '#f8fafc', 100: '#f1f5f9', 200: '#e2e8f0', 300: '#cbd5e1', 400: '#94a3b8', 500: '#64748b', 600: '#475569', 700: '#334155', 800: '#1e293b', 900: '#0f172a' },
29
- accent: { 50: '#fdf4ff', 100: '#fae8ff', 200: '#f5d0fe', 300: '#f0abfc', 400: '#e879f9', 500: '#d946ef', 600: '#c026d3', 700: '#a21caf', 800: '#86198f', 900: '#701a75' }
 
 
 
 
 
 
30
  },
31
- animation: { 'bounce-slow': 'bounce 2s infinite', 'pulse-slow': 'pulse 3s infinite', 'typing': 'typing 1.2s steps(3) infinite' },
32
- keyframes: { typing: { '0%': { width: '0.15em' }, '50%': { width: '0.7em' }, '100%': { width: '0.15em' } } }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  }
34
  }
35
  }
36
  </script>
 
37
  <style>
38
- html {
39
- scroll-behavior: smooth;
40
- overflow-x: hidden; /* Empêche le scroll horizontal global */
41
- }
42
- body {
43
- font-family: 'Inter', sans-serif;
44
- transition: background-color 0.3s ease, color 0.3s ease;
45
- overflow-x: hidden; /* Empêche le scroll horizontal du body */
46
- }
47
- .chat-layout {
48
- min-height: calc(100vh - 64px);
49
- display: grid;
50
- grid-template-rows: 1fr auto;
51
- }
52
- ::-webkit-scrollbar {
53
- width: 5px;
54
- height: 5px;
55
- }
56
- ::-webkit-scrollbar-track {
57
- background: transparent;
58
- }
59
- ::-webkit-scrollbar-thumb {
60
- background: #cbd5e1;
61
- border-radius: 5px;
62
- }
63
- .dark ::-webkit-scrollbar-thumb {
64
- background: #475569;
65
- }
66
- ::-webkit-scrollbar-thumb:hover {
67
- background: #94a3b8;
68
  }
69
- .dark ::-webkit-scrollbar-thumb:hover {
70
- background: #64748b;
 
 
 
 
 
71
  }
 
 
 
 
 
 
 
 
 
 
 
 
72
  .message-bubble {
73
  position: relative;
74
  max-width: 85%;
75
- border-radius: 1rem;
76
- padding: 0.875rem 1rem;
77
- line-height: 1.5;
78
- animation: message-fade-in 0.3s ease-out;
79
- box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
80
  transition: transform 0.2s ease, box-shadow 0.2s ease;
 
 
81
  }
82
- .message-bubble:hover {
83
- box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05), 0 1px 3px rgba(0, 0, 0, 0.1);
84
- }
85
- .dark .message-bubble {
86
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
87
- }
88
- .dark .message-bubble:hover {
89
- box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2), 0 1px 3px rgba(0, 0, 0, 0.3);
90
- }
91
  .user-message {
92
- border-bottom-right-radius: 0.125rem;
93
  align-self: flex-end;
94
- background: linear-gradient(to bottom right, #3b82f6, #2563eb);
95
- color: white;
96
  }
97
- .assistant-message {
98
- border-bottom-left-radius: 0.125rem;
99
  align-self: flex-start;
 
 
 
100
  }
101
- .dark .assistant-message {
102
- background-color: #1e293b;
103
- color: #e2e8f0;
104
- border-color: #334155;
105
- }
106
- @keyframes message-fade-in {
107
- from { opacity: 0; transform: translateY(10px); }
108
- to { opacity: 1; transform: translateY(0); }
109
- }
110
- @keyframes pulse-fade {
111
- 0%, 100% { opacity: 0.5; }
112
- 50% { opacity: 1; }
113
  }
114
- .typing-indicator {
115
- display: inline-flex;
116
- align-items: center;
117
- margin-left: 0.5rem;
 
118
  }
 
 
 
 
 
 
119
  .typing-dot {
120
- width: 0.5rem;
121
- height: 0.5rem;
122
- border-radius: 50%;
123
- background-color: currentColor;
124
- opacity: 0.7;
125
- margin: 0 0.1rem;
126
- }
127
- .typing-dot:nth-child(1) { animation: pulse-fade 1.2s 0s infinite; }
128
- .typing-dot:nth-child(2) { animation: pulse-fade 1.2s 0.2s infinite; }
129
- .typing-dot:nth-child(3) { animation: pulse-fade 1.2s 0.4s infinite; }
130
- .dark body {
131
- background-color: #0f172a;
132
- color: #e2e8f0;
133
- }
134
- .tooltip {
135
- position: relative;
136
  }
 
 
 
 
 
137
  .tooltip .tooltip-text {
138
- visibility: hidden;
139
- width: max-content;
140
- max-width: 200px;
141
- background-color: #1e293b;
142
- color: #f8fafc;
143
- text-align: center;
144
- border-radius: 6px;
145
- padding: 0.375rem 0.625rem;
146
  position: absolute;
147
- z-index: 1;
148
- bottom: 125%;
149
  left: 50%;
150
  transform: translateX(-50%);
151
- opacity: 0;
152
- transition: opacity 0.3s, visibility 0.3s;
153
- font-size: 0.75rem;
154
- box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
155
  pointer-events: none;
156
  }
157
- .dark .tooltip .tooltip-text {
158
- background-color: #475569;
159
- color: #f1f5f9;
160
- }
161
  .tooltip .tooltip-text::after {
162
- content: "";
163
- position: absolute;
164
- top: 100%;
165
- left: 50%;
166
- margin-left: -5px;
167
- border-width: 5px;
168
- border-style: solid;
169
- border-color: #1e293b transparent transparent transparent;
170
- }
171
- .dark .tooltip .tooltip-text::after {
172
- border-color: #475569 transparent transparent transparent;
173
- }
174
- .tooltip:hover .tooltip-text {
175
- visibility: visible;
176
- opacity: 1;
177
  }
 
 
 
 
178
  .copy-btn {
179
- position: absolute;
180
- top: 0.5rem;
181
- right: 0.5rem;
182
- opacity: 0;
183
- transition: opacity 0.2s ease, background-color 0.2s ease;
184
- z-index: 2;
185
  }
186
- .message-bubble:hover .copy-btn {
187
- opacity: 1;
 
 
 
 
 
 
188
  }
189
- .file-preview {
190
- max-width: 300px;
191
- margin: 0.5rem auto;
192
- position: relative;
193
- overflow: hidden;
194
- border-radius: 0.5rem;
195
  transition: transform 0.2s ease;
196
  }
197
- .file-preview:hover {
198
- transform: scale(1.02);
199
- }
200
- .file-preview img {
201
- width: 100%;
202
- height: auto;
203
- display: block;
204
- object-fit: cover;
205
  }
 
 
 
206
  .chip {
207
- display: inline-flex;
208
- align-items: center;
209
- background: #e0f2fe;
210
- border-radius: 9999px;
211
- padding: 0.25rem 0.75rem;
212
- font-size: 0.75rem;
213
- font-weight: 500;
214
- color: #0369a1;
215
  transition: all 0.2s ease;
 
216
  }
217
- .chip .chip-icon { margin-right: 0.25rem; }
 
218
  .chip .chip-close {
219
- margin-left: 0.25rem;
220
- cursor: pointer;
221
- opacity: 0.7;
222
- transition: opacity 0.2s ease;
223
- }
224
- .chip .chip-close:hover { opacity: 1; }
225
- .dark .chip {
226
- background: #0c4a6e;
227
- color: #7dd3fc;
228
- }
229
- .toggle-switch {
230
- position: relative;
231
- display: inline-block;
232
- width: 2.5rem;
233
- height: 1.25rem;
234
- }
235
- .toggle-switch input {
236
- opacity: 0;
237
- width: 0;
238
- height: 0;
239
  }
 
 
 
 
 
 
 
240
  .toggle-slider {
241
- position: absolute;
242
- cursor: pointer;
243
- top: 0;
244
- left: 0;
245
- right: 0;
246
- bottom: 0;
247
- background-color: #cbd5e1;
248
- transition: .4s;
249
- border-radius: 1.25rem;
250
  }
251
  .toggle-slider:before {
252
- position: absolute;
253
- content: "";
254
- height: 0.875rem;
255
- width: 0.875rem;
256
- left: 0.25rem;
257
- bottom: 0.1875rem;
258
- background-color: white;
259
- transition: .4s;
260
- border-radius: 50%;
261
- }
262
- input:checked + .toggle-slider {
263
- background-color: #0ea5e9;
264
- }
265
- input:focus + .toggle-slider {
266
- box-shadow: 0 0 1px #0ea5e9;
267
- }
268
- input:checked + .toggle-slider:before {
269
- transform: translateX(1.125rem);
270
- }
271
- .dark .toggle-slider {
272
- background-color: #475569;
273
- }
274
- .dark input:checked + .toggle-slider {
275
- background-color: #38bdf8;
276
- }
277
- .chat-input {
278
- transition: all 0.3s ease;
279
- border-color: #e2e8f0;
280
- }
281
- .chat-input:focus {
282
- border-color: #38bdf8;
283
- box-shadow: 0 0 0 3px rgba(56, 189, 248, 0.2);
284
- }
285
- .dark .chat-input {
286
- background-color: #1e293b;
287
- color: #f1f5f9;
288
- border-color: #334155;
289
  }
290
- .dark .chat-input:focus {
291
- border-color: #38bdf8;
292
- box-shadow: 0 0 0 3px rgba(56, 189, 248, 0.2);
293
- }
294
- pre {
295
- position: relative;
296
- background-color: #f8fafc;
297
- border-radius: 0.5rem;
298
- margin: 1rem 0;
299
- padding: 1.25rem 1rem;
300
- overflow-x: auto;
301
- }
302
- .dark pre {
303
- background-color: #1e293b;
304
- color: #e2e8f0;
305
- }
306
- code {
307
- font-family: 'JetBrains Mono', monospace;
308
- font-size: 0.875rem;
309
- }
310
- .code-copy-btn {
311
- position: absolute;
312
- top: 0.5rem;
313
- right: 0.5rem;
314
- opacity: 0;
315
- transition: opacity 0.2s ease;
316
- }
317
- pre:hover .code-copy-btn {
318
- opacity: 0.7;
319
- }
320
- /* Amélioration de l'affichage des tableaux Markdown */
321
- .table-wrapper {
322
- width: 100%;
323
- overflow-x: auto;
324
- margin: 1rem 0;
325
- border: 1px solid #e2e8f0;
326
- border-radius: 0.5rem;
327
- }
328
- .dark .table-wrapper {
329
- border-color: #334155;
330
- }
331
- .prose table {
332
- width: 100%;
333
- min-width: 100%;
334
- border-collapse: collapse;
335
- margin: 0;
336
- }
337
- .prose table th,
338
- .prose table td {
339
- border: 1px solid #e2e8f0;
340
- padding: 0.5rem 0.75rem;
341
- text-align: left;
342
- border-top: none;
343
- border-left: none;
344
- border-right: none;
345
- }
346
- .prose table th {
347
- border-bottom-width: 2px;
348
- }
349
- .dark .prose table th,
350
- .dark .prose table td {
351
- border-color: #334155;
352
- }
353
- .prose table thead {
354
- background-color: #f8fafc;
355
- font-weight: 600;
356
- }
357
- .dark .prose table thead {
358
- background-color: #1e293b;
359
- }
360
- .prose table tbody tr:nth-child(even) {
361
- background-color: #f8fafc;
362
- }
363
- .dark .prose table tbody tr:nth-child(even) {
364
- background-color: #1e293b;
365
- }
366
- /* Pour le textarea qui s'adapte au contenu */
367
  .chat-textarea {
368
- resize: none;
 
369
  min-height: 44px;
370
- max-height: 200px;
371
- overflow-y: auto;
372
  line-height: 1.5;
373
- width: 100%;
374
- border-radius: 9999px;
375
  padding-top: 0.625rem;
376
  padding-bottom: 0.625rem;
377
  padding-left: 1rem;
378
- padding-right: 3rem;
379
- box-sizing: border-box;
380
- }
381
- /* Ajustements responsive */
382
- @media (max-width: 640px) {
383
- .message-bubble {
384
- max-width: 90%;
385
- padding: 0.75rem 0.875rem;
386
- }
387
- .chat-textarea {
388
- max-height: 120px;
389
- font-size: 0.95rem;
390
- min-height: 40px;
391
- padding-top: 0.5rem;
392
- padding-bottom: 0.5rem;
393
- }
394
- .prose table {
395
- min-width: 0;
396
- font-size: 0.85rem;
397
- }
398
- .prose table th,
399
- .prose table td {
400
- padding: 0.375rem 0.5rem;
401
- }
402
- .send-button-wrapper {
403
- padding-right: 0.25rem;
404
- }
405
- .chat-textarea {
406
- padding-right: 2.75rem;
407
- }
408
- #send-button {
409
- width: 32px;
410
- height: 32px;
411
- padding: 0;
412
- display: inline-flex;
413
- align-items: center;
414
- justify-content: center;
415
- }
416
- #send-button i {
417
- font-size: 0.9rem;
418
- }
419
  }
420
- /* Container pour le textarea et le bouton */
421
- .input-wrapper {
422
- position: relative;
423
- display: flex;
424
- align-items: flex-end;
425
  }
426
- .send-button-wrapper {
427
- position: absolute;
428
- right: 0.5rem;
429
- bottom: 0.5rem;
 
 
 
 
 
 
 
 
 
 
430
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
431
  </style>
432
  </head>
433
- <body class="bg-gray-50 text-gray-900 antialiased">
434
- <!-- Header -->
435
- <header class="bg-gradient-to-r from-primary-600 to-primary-800 text-white py-3 px-4 shadow-md sticky top-0 z-10">
436
- <div class="max-w-4xl mx-auto flex justify-between items-center">
437
- <!-- Logo & Titre -->
438
- <div class="flex items-center space-x-2">
439
- <img src="https://mariam-241.vercel.app/static/image/logoboma.png" alt="Logo Mariam AI" class="h-8 sm:h-10 object-contain">
440
- <h1 class="text-xl font-bold">Mariam AI</h1>
441
- </div>
442
- <!-- Actions -->
443
- <div class="flex items-center space-x-2 sm:space-x-4">
444
- <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">
445
- <i class="fa-solid fa-moon dark:hidden"></i>
446
- <i class="fa-solid fa-sun hidden dark:inline"></i>
447
- <span class="tooltip-text">Mode clair/sombre</span>
448
- </button>
449
- <form action="/clear" method="POST" id="clear-form">
450
- <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">
451
- <i class="fa-solid fa-trash-can mr-1.5"></i>
452
- <span class="hidden sm:inline">Effacer</span>
453
- <span class="tooltip-text">Effacer la conversation</span>
454
  </button>
455
- </form>
456
- </div>
457
- </div>
458
- </header>
459
- <!-- Main Container -->
460
- <main class="max-w-4xl mx-auto chat-layout">
461
- <!-- Conteneur des messages -->
462
- <section id="chat-messages" class="flex flex-col space-y-6 p-4 overflow-y-auto">
463
- <!-- Chargement de l'historique -->
464
- <div id="history-loading" class="text-center py-10">
465
- <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">
466
- <svg class="animate-spin h-5 w-5 mr-3" viewBox="0 0 24 24">
467
- <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
468
- <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>
469
- </svg>
470
- <span>Chargement de la conversation...</span>
471
  </div>
472
  </div>
473
- <!-- Indicateur de chargement pour les réponses -->
474
- <div id="loading-indicator" class="flex items-start space-x-2 hidden">
475
- <div class="w-8 h-8 rounded-full bg-primary-100 flex items-center justify-center flex-shrink-0 dark:bg-primary-900/50">
476
- <span class="text-lg">✨</span>
 
 
 
 
 
 
 
 
 
 
 
 
477
  </div>
478
- <div class="message-bubble assistant-message bg-secondary-50 text-secondary-900 border border-secondary-200 flex items-center">
479
- <span>Mariam réfléchit</span>
480
- <div class="typing-indicator">
481
- <span class="typing-dot"></span>
482
- <span class="typing-dot"></span>
483
- <span class="typing-dot"></span>
 
 
 
 
 
484
  </div>
485
  </div>
486
- </div>
487
- </section>
488
- <!-- Conteneur du bas -->
489
- <div class="border-t border-gray-200 dark:border-gray-700">
490
- <!-- Zone d'erreur -->
491
- <div id="error-message" class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 dark:bg-red-900/30 dark:text-red-300 dark:border-red-600 hidden" role="alert">
492
- <div class="flex">
493
- <div class="flex-shrink-0"><i class="fa-solid fa-circle-exclamation"></i></div>
494
- <div class="ml-3"><p class="text-sm font-medium" id="error-text">Le message d'erreur détaillé ira ici.</p></div>
495
- <button class="ml-auto" id="dismiss-error"><i class="fa-solid fa-xmark"></i></button>
 
 
 
 
 
 
 
 
 
 
 
 
496
  </div>
497
  </div>
498
- <!-- Zone de prévisualisation -->
499
- <div id="preview-area" class="px-4 py-2 bg-gray-50 dark:bg-gray-800/50 hidden">
500
- <div id="file-preview" class="hidden"></div>
501
- </div>
502
- <!-- Barre d'options -->
503
- <div class="flex items-center justify-between flex-wrap gap-y-2 px-4 py-2 bg-gray-100 dark:bg-gray-800/80 text-sm text-gray-600 dark:text-gray-300">
504
- <div class="flex items-center space-x-4 flex-wrap gap-y-2">
505
- <label class="flex items-center cursor-pointer tooltip">
506
- <span class="mr-2 text-xs sm:text-sm font-medium"><i class="fa-solid fa-globe mr-1.5"></i><span class="hidden sm:inline">Recherche Web</span></span>
507
- <span class="toggle-switch">
508
- <input type="checkbox" id="web_search_toggle" name="web_search" value="true">
509
- <span class="toggle-slider"></span>
510
- </span>
511
- <span class="tooltip-text">Activer la recherche web</span>
512
- </label>
513
- <label class="flex items-center cursor-pointer tooltip">
514
- <span class="mr-2 text-xs sm:text-sm font-medium text-accent-700 dark:text-accent-300">
515
- <i class="fa-solid fa-brain mr-1.5"></i>
516
- <span class="hidden sm:inline">Avancé</span>
517
- <span id="advanced-cooldown-timer" class="text-xs ml-1 hidden"></span>
518
- </span>
519
- <span class="toggle-switch">
520
- <input type="checkbox" id="advanced_reasoning_toggle" name="advanced_reasoning" value="true">
521
- <span class="toggle-slider"></span>
522
- </span>
523
- <span class="tooltip-text">Raisonnement avancé (1 fois/min)</span>
524
- </label>
525
- </div>
526
- <div class="flex items-center space-x-2">
527
- <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">
528
- <i class="fa-solid fa-paperclip"></i>
529
- <span class="ml-1.5 hidden sm:inline">Fichier</span>
530
- <input type="file" id="file_upload" name="file" class="hidden" accept=".txt,.pdf,.png,.jpg,.jpeg">
531
- <span class="tooltip-text">Joindre (txt, pdf, image)</span>
532
- </label>
533
- <div id="file-chip" class="chip hidden">
534
- <i class="fa-solid fa-file chip-icon"></i>
535
- <span id="file-name" class="truncate max-w-[100px] sm:max-w-[120px]"></span>
536
- <i id="clear-file" class="fa-solid fa-xmark chip-close"></i>
537
- </div>
538
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
539
  </div>
540
- <!-- Formulaire de chat -->
541
- <form id="chat-form" class="p-3 sm:p-4 bg-white dark:bg-gray-900">
542
- <div class="input-wrapper">
 
543
  <textarea
544
  id="prompt"
545
  name="prompt"
546
- class="chat-input chat-textarea w-full border focus:outline-none text-sm sm:text-base"
547
  placeholder="Posez votre question à Mariam..."
548
  autocomplete="off"
549
- rows="1"></textarea>
 
550
  <div class="send-button-wrapper">
551
  <button
552
  type="submit"
553
  id="send-button"
554
- class="bg-primary-500 hover:bg-primary-600 disabled:bg-primary-300 text-white rounded-full p-2 transition focus:outline-none focus:ring-2 focus:ring-primary-400 flex items-center justify-center"
555
- title="Envoyer le message">
556
- <i class="fa-solid fa-paper-plane text-sm"></i>
557
  </button>
558
  </div>
559
  </div>
560
- <div class="text-xs text-center mt-2 text-gray-400 dark:text-gray-500">
561
- Appuyez sur <kbd class="px-1.5 py-0.5 bg-gray-100 dark:bg-gray-800 rounded border border-gray-300 dark:border-gray-700">Entrée</kbd>
562
- <span class="hidden sm:inline"> pour envoyer</span>
563
- <span class="sm:hidden"> pour une nouvelle ligne</span>
564
-
565
- <kbd class="px-1.5 py-0.5 bg-gray-100 dark:bg-gray-800 rounded border border-gray-300 dark:border-gray-700">Shift+Entrée</kbd>
566
- <span class="hidden sm:inline"> pour une nouvelle ligne</span>
567
- <span class="sm:hidden"> pour envoyer</span>
568
- </div>
569
  </form>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
570
  </div>
571
- </main>
 
 
 
572
  <!-- Scripts -->
573
  <script>
574
  document.addEventListener('DOMContentLoaded', () => {
575
- // Sélection des éléments
576
  const chatForm = document.getElementById('chat-form');
577
  const promptInput = document.getElementById('prompt');
578
  const chatMessages = document.getElementById('chat-messages');
@@ -586,507 +573,704 @@
586
  const fileChip = document.getElementById('file-chip');
587
  const fileNameSpan = document.getElementById('file-name');
588
  const clearFileButton = document.getElementById('clear-file');
589
- const filePreview = document.getElementById('file-preview');
590
  const previewArea = document.getElementById('preview-area');
591
  const sendButton = document.getElementById('send-button');
592
  const clearForm = document.getElementById('clear-form');
593
  const advancedToggle = document.getElementById('advanced_reasoning_toggle');
594
  const advancedCooldownTimerSpan = document.getElementById('advanced-cooldown-timer');
595
  const themeToggleBtn = document.getElementById('theme-toggle');
596
- const API_CHAT_ENDPOINT = '/api/chat';
597
- const API_HISTORY_ENDPOINT = '/api/history';
598
- const CLEAR_ENDPOINT = '/clear';
599
- const COOLDOWN_DURATION = 60 * 1000;
600
- const MOBILE_BREAKPOINT = 640;
 
 
 
 
601
  let advancedToggleCooldownEndTime = 0;
 
602
  let isComposing = false;
 
603
 
604
- // Gestion du thème
605
- function initializeTheme() {
606
- if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
607
- document.documentElement.classList.add('dark');
608
- } else {
609
- document.documentElement.classList.remove('dark');
610
- }
611
- }
612
- function toggleTheme() {
613
- if (document.documentElement.classList.contains('dark')) {
614
- document.documentElement.classList.remove('dark');
615
- localStorage.theme = 'light';
616
- } else {
617
- document.documentElement.classList.add('dark');
618
- localStorage.theme = 'dark';
619
- }
620
  }
621
- themeToggleBtn.addEventListener('click', toggleTheme);
622
- initializeTheme();
623
 
624
- // Ajuster la hauteur du textarea
625
- function adjustTextareaHeight(textarea) {
626
- textarea.style.height = 'auto';
627
- const style = window.getComputedStyle(textarea);
628
- const maxHeight = parseInt(style.maxHeight, 10);
629
- const newHeight = Math.min(maxHeight || 200, textarea.scrollHeight);
630
- textarea.style.height = newHeight + 'px';
 
 
 
631
  }
632
 
633
- // Défilement vers le bas
634
- function scrollToBottom(smooth = true) {
635
- setTimeout(() => {
636
- chatMessages.scrollTo({ top: chatMessages.scrollHeight, behavior: smooth ? 'smooth' : 'auto' });
637
- }, 50);
 
 
638
  }
639
 
640
- // Affichage de l'indicateur de chargement
641
  function showLoading(show) {
642
- if (show) {
643
- loadingIndicator.classList.remove('hidden');
644
- chatMessages.appendChild(loadingIndicator);
645
- scrollToBottom();
646
- } else {
647
- loadingIndicator.classList.add('hidden');
648
- }
649
  sendButton.disabled = show;
650
  promptInput.disabled = show;
651
  fileUpload.disabled = show;
 
 
 
 
652
  if (show) {
 
 
 
 
653
  clearFileButton.style.pointerEvents = 'none';
654
  clearFileButton.style.opacity = '0.5';
655
  } else {
 
 
656
  clearFileButton.style.pointerEvents = 'auto';
657
- clearFileButton.style.opacity = '0.7';
658
  }
659
  }
660
 
661
- // Affichage des erreurs
662
  function displayError(message) {
663
- errorTextP.textContent = message || "Une erreur inconnue est survenue.";
664
- errorMessageDiv.classList.remove('hidden');
 
 
 
665
  }
666
- dismissErrorBtn.addEventListener('click', () => { errorMessageDiv.classList.add('hidden'); });
667
 
668
- // Ajout d'un message dans le chat
669
- function addMessageToChat(role, content, isHtml = false) {
670
- errorMessageDiv.classList.add('hidden');
671
- const messageWrapper = document.createElement('div');
672
- messageWrapper.classList.add('flex', 'w-full', role === 'user' ? 'justify-end' : 'justify-start');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
673
 
674
- let messageContentHtml = '';
675
- if (isHtml) {
676
- messageContentHtml = content;
 
 
677
  } else {
678
- messageContentHtml = `<p class="text-sm sm:text-base whitespace-pre-wrap">${escapeHtml(content)}</p>`;
679
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
680
 
681
- let bubbleHtml = '';
682
  if (role === 'user') {
683
- bubbleHtml = `
684
- <div class="message-bubble user-message">
685
- ${messageContentHtml}
 
 
 
 
686
  </div>
687
  `;
688
- } else {
689
- bubbleHtml = `
690
- <div class="flex items-start space-x-2 max-w-[85%]">
691
- <div class="w-8 h-8 rounded-full bg-primary-100 flex items-center justify-center flex-shrink-0 dark:bg-primary-900/50">
692
- <span class="text-lg">✨</span>
693
- </div>
694
- <div class="message-bubble assistant-message bg-secondary-50 text-secondary-900 border border-secondary-200 relative">
695
- <div class="prose prose-sm sm:prose-base max-w-none dark:prose-invert">
696
- ${messageContentHtml}
697
- </div>
698
- <button class="copy-btn text-xs bg-white/90 dark:bg-gray-800/90 hover:bg-gray-100 dark:hover:bg-gray-700 py-1 px-2 rounded text-gray-600 dark:text-gray-300 flex items-center">
699
- <i class="fa-regular fa-copy mr-1"></i> Copier
700
- </button>
701
  </div>
 
 
 
702
  </div>
703
  `;
 
 
 
 
704
  }
705
- messageWrapper.innerHTML = bubbleHtml;
706
-
707
- // Activation du bouton de copie
708
- const copyBtns = messageWrapper.querySelectorAll('.copy-btn');
709
- copyBtns.forEach(btn => {
710
- btn.addEventListener('click', function() {
711
- const textToCopy = this.closest('.message-bubble').querySelector('.prose').innerText || this.closest('.message-bubble').innerText;
712
- navigator.clipboard.writeText(textToCopy).then(() => {
713
- const originalText = this.innerHTML;
714
- this.innerHTML = '<i class="fa-solid fa-check mr-1"></i> Copié';
715
- setTimeout(() => { this.innerHTML = originalText; }, 2000);
716
- }).catch(err => console.error('Copy failed:', err));
 
 
 
 
 
 
 
 
 
 
 
 
717
  });
718
- });
719
 
720
- // Activation de la copie pour les blocs de code
721
- const codeBlocks = messageWrapper.querySelectorAll('pre');
722
- codeBlocks.forEach(pre => {
723
  const code = pre.querySelector('code');
724
  if (!code) return;
 
 
725
  if (pre.querySelector('.code-copy-btn')) return;
726
- const copyButton = document.createElement('button');
727
- copyButton.innerHTML = '<i class="fa-regular fa-copy"></i>';
728
- copyButton.className = 'code-copy-btn p-1.5 bg-gray-200/50 dark:bg-gray-700/50 rounded text-gray-600 dark:text-gray-300 hover:bg-gray-300/70 dark:hover:bg-gray-600/70 tooltip';
729
- copyButton.setAttribute('aria-label', 'Copier le code');
 
 
730
  const tooltipText = document.createElement('span');
731
  tooltipText.className = 'tooltip-text !text-xs';
732
- tooltipText.textContent = 'Copier le code';
733
- copyButton.appendChild(tooltipText);
734
- copyButton.addEventListener('click', () => {
 
735
  navigator.clipboard.writeText(code.innerText).then(() => {
736
- tooltipText.textContent = 'Copié!';
737
- copyButton.innerHTML = '<i class="fa-solid fa-check"></i>';
 
 
738
  setTimeout(() => {
739
- copyButton.innerHTML = '<i class="fa-regular fa-copy"></i>';
740
- copyButton.appendChild(tooltipText);
741
- tooltipText.textContent = 'Copier le code';
742
  }, 2000);
743
  }).catch(err => {
744
- tooltipText.textContent = 'Erreur copie';
745
- console.error('Failed to copy code: ', err);
746
- setTimeout(() => { tooltipText.textContent = 'Copier le code'; }, 2000);
747
  });
748
  });
749
- pre.appendChild(copyButton);
750
  });
751
 
752
- chatMessages.insertBefore(messageWrapper, loadingIndicator);
753
- scrollToBottom();
754
- }
755
- function escapeHtml(unsafe) {
756
- return unsafe
757
- .replace(/&/g, "&amp;")
758
- .replace(/</g, "&lt;")
759
- .replace(/>/g, "&gt;")
760
- .replace(/"/g, "&quot;")
761
- .replace(/'/g, "&#039;");
762
- }
763
 
764
- // Gestion du cooldown pour le raisonnement avancé
765
- function startAdvancedCooldownTimer() {
766
- advancedToggle.disabled = true;
767
- advancedToggleCooldownEndTime = Date.now() + COOLDOWN_DURATION;
768
- const intervalId = setInterval(() => {
769
- const now = Date.now();
770
- if (now >= advancedToggleCooldownEndTime) {
771
- clearInterval(intervalId);
772
- advancedCooldownTimerSpan.classList.add('hidden');
773
- advancedToggle.disabled = false;
774
- advancedToggleCooldownEndTime = 0;
775
- } else {
776
- const remainingSeconds = Math.ceil((advancedToggleCooldownEndTime - now) / 1000);
777
- advancedCooldownTimerSpan.textContent = `(${remainingSeconds}s)`;
778
- advancedCooldownTimerSpan.classList.remove('hidden');
779
- }
780
- }, 1000);
781
- const remainingSeconds = Math.ceil((advancedToggleCooldownEndTime - Date.now()) / 1000);
782
- advancedCooldownTimerSpan.textContent = `(${remainingSeconds}s)`;
783
- advancedCooldownTimerSpan.classList.remove('hidden');
784
  }
785
 
786
- // Chargement de l'historique du chat
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
787
  async function loadChatHistory() {
788
- historyLoadingIndicator.style.display = 'flex';
 
 
 
 
789
  try {
790
  const response = await fetch(API_HISTORY_ENDPOINT);
791
  if (!response.ok) {
792
- let errorMsg = `Erreur serveur (${response.status})`;
793
- try {
794
- const errData = await response.json();
795
- errorMsg = errData.error || errorMsg;
796
- } catch (e) {}
797
  throw new Error(errorMsg);
798
  }
799
  const data = await response.json();
800
- const messagesToRemove = chatMessages.querySelectorAll(':scope > *:not(#loading-indicator)');
801
- messagesToRemove.forEach(el => el.remove());
802
- loadingIndicator.classList.add('hidden');
803
  if (data.success && Array.isArray(data.history)) {
804
  if (data.history.length === 0) {
805
- addMessageToChat('assistant', "Bonjour ! Je suis Mariam, votre assistant IA. Comment puis-je vous aider aujourd'hui ?", true);
806
  } else {
807
  data.history.forEach(message => {
808
- const isAssistantHtml = message.role === 'assistant';
809
- addMessageToChat(message.role, message.text, isAssistantHtml);
810
  });
811
  }
812
- scrollToBottom(false);
 
813
  } else {
814
- throw new Error(data.error || "Format de réponse invalide pour l'historique.");
815
  }
816
  } catch (error) {
817
- displayError(`Impossible de charger l'historique: ${error.message}`);
818
- if (chatMessages.querySelectorAll(':scope > *:not(#loading-indicator):not(#history-loading)').length === 0) {
819
- addMessageToChat('assistant', "Bonjour ! Je suis Mariam. Je n'ai pas pu charger notre conversation précédente. Comment puis-je vous aider ?", true);
 
 
820
  }
821
  } finally {
822
- historyLoadingIndicator.remove();
823
- promptInput.focus();
824
- adjustTextareaHeight(promptInput);
825
  }
826
  }
827
 
828
- // Gestion des fichiers
829
- function clearFileInput() {
830
  fileUpload.value = '';
831
  fileChip.classList.add('hidden');
832
  fileNameSpan.textContent = '';
833
  fileNameSpan.title = '';
834
- filePreview.innerHTML = '';
835
- filePreview.classList.add('hidden');
836
  previewArea.classList.add('hidden');
 
837
  }
 
838
  fileUpload.addEventListener('change', () => {
839
  if (fileUpload.files.length > 0) {
840
  const file = fileUpload.files[0];
841
  const name = file.name;
 
 
 
 
 
 
 
 
 
 
 
 
842
  fileNameSpan.textContent = name;
843
  fileNameSpan.title = name;
844
  fileChip.classList.remove('hidden');
845
- filePreview.innerHTML = '';
846
- if (file.type.startsWith('image/')) {
 
 
 
 
847
  const reader = new FileReader();
848
  reader.onload = (e) => {
849
- filePreview.innerHTML = `
850
- <div class="file-preview">
851
- <img src="${e.target.result}" alt="Prévisualisation: ${escapeHtml(name)}">
852
- </div>`;
853
- filePreview.classList.remove('hidden');
854
- previewArea.classList.remove('hidden');
855
- };
856
- reader.onerror = () => {
857
- filePreview.innerHTML = `<p class="text-red-500 text-xs text-center p-2">Erreur lecture image</p>`;
858
- filePreview.classList.remove('hidden');
859
  previewArea.classList.remove('hidden');
 
860
  };
 
 
 
 
861
  reader.readAsDataURL(file);
862
  } else {
863
- filePreview.innerHTML = `
864
- <div class="flex items-center justify-center p-3">
865
- <div class="bg-gray-100 dark:bg-gray-800 p-3 rounded-lg text-center">
866
- <i class="fa-solid ${getFileIcon(file.type)} text-3xl text-gray-500 dark:text-gray-400 mb-2"></i>
867
- <p class="text-xs text-gray-500 dark:text-gray-400">${formatFileSize(file.size)}</p>
 
 
 
868
  </div>
869
  </div>`;
870
- filePreview.classList.remove('hidden');
871
  previewArea.classList.remove('hidden');
 
872
  }
873
  } else {
874
  clearFileInput();
875
  }
876
  });
877
- function getFileIcon(fileType) {
878
- if (!fileType) return 'fa-file';
879
- if (fileType.includes('pdf')) return 'fa-file-pdf';
880
- if (fileType.includes('text')) return 'fa-file-lines';
881
- return 'fa-file';
882
- }
883
- function formatFileSize(bytes) {
884
- if (bytes === 0) return '0 octets';
885
- const k = 1024;
886
- const sizes = ['octets', 'Ko', 'Mo', 'Go', 'To'];
887
- const i = Math.floor(Math.log(bytes) / Math.log(k));
888
- return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
889
- }
890
- clearFileButton.addEventListener('click', clearFileInput);
891
 
892
- // Événements pour le textarea
893
- promptInput.addEventListener('input', () => {
894
- adjustTextareaHeight(promptInput);
 
895
  });
 
 
 
 
 
 
 
896
  promptInput.addEventListener('keydown', (e) => {
897
- if (isComposing) return;
898
- const isMobile = window.innerWidth < MOBILE_BREAKPOINT;
899
- if (e.key === 'Enter') {
900
- if (isMobile && !e.shiftKey) {
901
- setTimeout(() => adjustTextareaHeight(promptInput), 0);
902
- } else if (!isMobile && !e.shiftKey) {
903
- e.preventDefault();
904
- if (!sendButton.disabled && (promptInput.value.trim() || fileUpload.files.length > 0)) {
905
- chatForm.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
906
- }
907
- } else if (e.shiftKey) {
908
- setTimeout(() => adjustTextareaHeight(promptInput), 0);
909
- if (isMobile) {
910
- e.preventDefault();
911
- if (!sendButton.disabled && (promptInput.value.trim() || fileUpload.files.length > 0)) {
912
- chatForm.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
913
- }
914
- }
915
- }
916
- }
917
- });
918
- promptInput.addEventListener('compositionstart', () => { isComposing = true; });
919
- promptInput.addEventListener('compositionend', () => {
920
- isComposing = false;
921
- setTimeout(() => adjustTextareaHeight(promptInput), 0);
922
  });
923
- adjustTextareaHeight(promptInput);
924
 
925
- // Soumission du formulaire
 
 
 
 
 
 
 
926
  chatForm.addEventListener('submit', async (e) => {
927
  e.preventDefault();
928
- const prompt = promptInput.value.trim();
929
  const file = fileUpload.files[0];
930
  const useWebSearch = webSearchToggle.checked;
931
  const useAdvanced = advancedToggle.checked;
932
- if (sendButton.disabled) return;
933
- if (!prompt && !file) {
934
  promptInput.focus();
935
  return;
936
  }
937
- errorMessageDiv.classList.add('hidden');
 
 
 
938
  if (useAdvanced) {
939
  const now = Date.now();
940
  if (advancedToggleCooldownEndTime > 0 && now < advancedToggleCooldownEndTime) {
941
  const remainingSeconds = Math.ceil((advancedToggleCooldownEndTime - now) / 1000);
942
- displayError(`Le raisonnement avancé est disponible dans ${remainingSeconds} seconde(s).`);
943
  return;
944
  }
945
  }
946
- let userMessageText = prompt;
 
 
947
  if (file && file.name) {
948
- userMessageText = prompt ? `${prompt}\n[Fichier: ${file.name}]` : `[Fichier joint: ${file.name}]`;
 
949
  }
950
- addMessageToChat('user', userMessageText);
 
 
951
  const formData = new FormData();
952
- formData.append('prompt', prompt);
953
  formData.append('web_search', useWebSearch);
954
  formData.append('advanced_reasoning', useAdvanced);
955
  if (file) {
956
  formData.append('file', file);
957
  }
 
 
958
  promptInput.value = '';
959
- adjustTextareaHeight(promptInput);
 
960
  clearFileInput();
961
  if (useAdvanced) {
962
- startAdvancedCooldownTimer();
963
- advancedToggle.checked = false;
964
  }
965
- webSearchToggle.checked = false;
966
- showLoading(true);
 
 
 
967
  try {
968
  const response = await fetch(API_CHAT_ENDPOINT, { method: 'POST', body: formData });
969
- const data = await response.json();
970
  if (!response.ok) {
971
- throw new Error(data.error || `Erreur serveur: ${response.status} ${response.statusText}`);
 
 
 
 
 
 
 
972
  }
 
 
 
973
  if (data.success && data.message) {
974
- addMessageToChat('assistant', data.message, true);
 
975
  } else {
976
- throw new Error(data.error || "Réponse invalide ou vide du serveur.");
977
  }
978
  } catch (error) {
979
- console.error("Chat Error:", error);
980
- addMessageToChat('assistant', `<p class="text-red-600 dark:text-red-400">Désolé, une erreur est survenue :<br>${escapeHtml(error.message)}</p>`, true);
 
 
 
981
  } finally {
982
- showLoading(false);
983
- promptInput.focus();
984
  }
985
  });
986
 
987
- // Effacement de la conversation
988
  clearForm.addEventListener('submit', async (e) => {
989
  e.preventDefault();
 
 
990
  const confirmDialog = document.createElement('div');
991
- confirmDialog.className = 'fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4';
 
 
 
992
  confirmDialog.innerHTML = `
993
- <div class="bg-white dark:bg-gray-800 p-6 rounded-lg shadow-xl max-w-sm w-full animate-[message-fade-in_0.2s_ease-out]">
994
- <h3 class="text-lg font-semibold mb-3 text-gray-900 dark:text-gray-100">Confirmer l'effacement</h3>
995
- <p class="text-sm text-gray-600 dark:text-gray-300 mb-5">Êtes-vous sûr de vouloir effacer toute la conversation ? Cette action est irréversible.</p>
996
  <div class="flex justify-end space-x-3">
997
- <button type="button" id="cancel-clear" class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 rounded hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors focus:outline-none focus:ring-2 focus:ring-gray-400">
998
  Annuler
999
  </button>
1000
- <button type="button" id="confirm-clear" class="px-4 py-2 text-sm font-medium text-white bg-red-600 rounded hover:bg-red-700 transition-colors focus:outline-none focus:ring-2 focus:ring-red-500">
1001
  Effacer
1002
  </button>
1003
  </div>
1004
  </div>
1005
  `;
1006
- const closeModal = () => {
1007
- if (document.body.contains(confirmDialog)) {
1008
- document.body.removeChild(confirmDialog);
1009
- document.body.style.overflow = '';
1010
- }
 
 
 
 
 
 
 
 
 
 
 
 
1011
  };
1012
- confirmDialog.querySelector('#cancel-clear').addEventListener('click', closeModal);
1013
- confirmDialog.querySelector('#confirm-clear').addEventListener('click', async () => {
1014
- closeModal();
1015
- const clearButton = e.target.querySelector('button[type="submit"]');
 
 
 
1016
  const originalButtonContent = clearButton.innerHTML;
1017
  clearButton.disabled = true;
1018
- clearButton.innerHTML = '<i class="fa-solid fa-spinner fa-spin mr-1.5"></i><span class="hidden sm:inline">Effacement...</span>';
 
 
 
1019
  try {
1020
- const response = await fetch(CLEAR_ENDPOINT, {
1021
  method: 'POST',
1022
- headers: {
1023
- 'X-Requested-With': 'XMLHttpRequest'
1024
- }
1025
  });
1026
  const data = await response.json();
 
1027
  if (response.ok && data.success) {
1028
- const messagesToRemove = chatMessages.querySelectorAll(':scope > *:not(#loading-indicator)');
 
1029
  messagesToRemove.forEach(el => el.remove());
1030
- addMessageToChat('assistant', "Conversation effacée. Comment puis-je vous aider maintenant ?", true);
1031
- errorMessageDiv.classList.add('hidden');
 
 
 
 
1032
  } else {
1033
- throw new Error(data.error || "Impossible d'effacer la conversation.");
1034
  }
1035
  } catch (error) {
1036
- console.error("Clear Error:", error);
1037
- displayError(`Erreur lors de l'effacement: ${error.message}`);
1038
  } finally {
1039
- clearButton.innerHTML = originalButtonContent;
1040
  clearButton.disabled = false;
1041
- promptInput.focus();
1042
  }
1043
  });
 
 
 
 
 
 
 
 
 
 
1044
  document.body.appendChild(confirmDialog);
1045
- document.body.style.overflow = 'hidden';
1046
- confirmDialog.querySelector('#cancel-clear').focus();
 
 
 
 
 
 
 
1047
  });
1048
 
1049
- // Initialisation
1050
- loadChatHistory();
1051
-
1052
- // Observer pour les tableaux Markdown
1053
- const observeMarkdownTables = () => {
1054
- const observer = new MutationObserver(mutations => {
1055
- mutations.forEach(mutation => {
1056
- if (mutation.addedNodes.length) {
1057
- mutation.addedNodes.forEach(node => {
1058
- if (node.nodeType === 1) {
1059
- const tables = node.matches('.prose table') ? [node] : node.querySelectorAll('.prose table');
1060
- tables.forEach(table => {
1061
- if (!table.closest('.table-wrapper')) {
1062
- const wrapper = document.createElement('div');
1063
- wrapper.className = 'table-wrapper';
1064
- table.parentNode.insertBefore(wrapper, table);
1065
- wrapper.appendChild(table);
1066
- }
1067
- });
1068
- }
1069
- });
1070
- }
1071
- });
1072
- });
1073
- observer.observe(chatMessages, { childList: true, subtree: true });
1074
- };
1075
- observeMarkdownTables();
1076
-
1077
- // Gestion du changement de thème selon le système
1078
- const prefersDarkScheme = window.matchMedia('(prefers-color-scheme: dark)');
1079
- const handleSchemeChange = (e) => {
1080
- if (!localStorage.getItem('theme')) {
1081
- if (e.matches) {
1082
- document.documentElement.classList.add('dark');
1083
- } else {
1084
- document.documentElement.classList.remove('dark');
1085
  }
1086
- }
1087
- };
1088
- prefersDarkScheme.addEventListener('change', handleSchemeChange);
1089
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
1090
  </script>
1091
  </body>
1092
- </html>
 
1
  <!DOCTYPE html>
2
+ <html lang="fr" class="h-full">
3
  <head>
4
  <meta charset="UTF-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Mariam AI ✨ Assistant IA</title>
7
+
8
  <!-- Tailwind CSS via CDN -->
9
  <script src="https://cdn.tailwindcss.com?plugins=forms,typography"></script>
10
+
11
  <!-- Font Awesome pour les icônes -->
12
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha512-DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4TctnWMn13TZye+giMm8e2LwA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
13
+
14
  <!-- Google Fonts -->
15
  <link rel="preconnect" href="https://fonts.googleapis.com">
16
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
17
  <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">
18
+
19
  <!-- Favicon (Emoji amélioré) -->
20
  <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>">
21
+
22
  <script>
23
+ // Tailwind CSS Configuration
24
  tailwind.config = {
25
  darkMode: 'class',
26
  theme: {
27
  extend: {
28
  fontFamily: {
29
+ sans: ['Inter', 'system-ui', '-apple-system', 'BlinkMacSystemFont', '"Segoe UI"', 'Roboto', '"Helvetica Neue"', 'Arial', '"Noto Sans"', 'sans-serif', '"Apple Color Emoji"', '"Segoe UI Emoji"', '"Segoe UI Symbol"', '"Noto Color Emoji"'],
30
+ mono: ['"JetBrains Mono"', 'ui-monospace', 'SFMono-Regular', 'Menlo', 'Monaco', 'Consolas', '"Liberation Mono"', '"Courier New"', 'monospace']
31
  },
32
  colors: {
33
+ primary: { DEFAULT: '#0ea5e9', 50: '#f0f9ff', 100: '#e0f2fe', 200: '#bae6fd', 300: '#7dd3fc', 400: '#38bdf8', 500: '#0ea5e9', 600: '#0284c7', 700: '#0369a1', 800: '#075985', 900: '#0c4a6e', 950: '#082f49' },
34
+ secondary: { DEFAULT: '#64748b', 50: '#f8fafc', 100: '#f1f5f9', 200: '#e2e8f0', 300: '#cbd5e1', 400: '#94a3b8', 500: '#64748b', 600: '#475569', 700: '#334155', 800: '#1e293b', 900: '#0f172a', 950: '#020617' },
35
+ accent: { DEFAULT: '#d946ef', 50: '#fdf4ff', 100: '#fae8ff', 200: '#f5d0fe', 300: '#f0abfc', 400: '#e879f9', 500: '#d946ef', 600: '#c026d3', 700: '#a21caf', 800: '#86198f', 900: '#701a75', 950: '#4a044e' }
36
+ },
37
+ animation: {
38
+ 'fade-in': 'fadeIn 0.3s ease-out forwards',
39
+ 'slide-up': 'slideUp 0.3s ease-out forwards',
40
+ 'pulse-slow': 'pulse 2.5s cubic-bezier(0.4, 0, 0.6, 1) infinite',
41
+ 'typing-dot-pulse': 'typingDotPulse 1.4s infinite ease-in-out both'
42
  },
43
+ keyframes: {
44
+ fadeIn: { '0%': { opacity: '0' }, '100%': { opacity: '1' } },
45
+ slideUp: { '0%': { opacity: '0', transform: 'translateY(10px)' }, '100%': { opacity: '1', transform: 'translateY(0)' } },
46
+ typingDotPulse: {
47
+ '0%, 80%, 100%': { transform: 'scale(0)' },
48
+ '40%': { transform: 'scale(1.0)' }
49
+ }
50
+ },
51
+ typography: (theme) => ({
52
+ DEFAULT: {
53
+ css: {
54
+ '--tw-prose-body': theme('colors.secondary[700]'),
55
+ '--tw-prose-headings': theme('colors.secondary[900]'),
56
+ '--tw-prose-lead': theme('colors.secondary[600]'),
57
+ '--tw-prose-links': theme('colors.primary[600]'),
58
+ '--tw-prose-bold': theme('colors.secondary[900]'),
59
+ '--tw-prose-counters': theme('colors.secondary[500]'),
60
+ '--tw-prose-bullets': theme('colors.secondary[300]'),
61
+ '--tw-prose-hr': theme('colors.secondary[200]'),
62
+ '--tw-prose-quotes': theme('colors.secondary[900]'),
63
+ '--tw-prose-quote-borders': theme('colors.secondary[200]'),
64
+ '--tw-prose-captions': theme('colors.secondary[500]'),
65
+ '--tw-prose-code': theme('colors.secondary[900]'),
66
+ '--tw-prose-pre-code': theme('colors.secondary[700]'),
67
+ '--tw-prose-pre-bg': theme('colors.secondary[100]'),
68
+ '--tw-prose-th-borders': theme('colors.secondary[300]'),
69
+ '--tw-prose-td-borders': theme('colors.secondary[200]'),
70
+ '--tw-prose-invert-body': theme('colors.secondary[300]'),
71
+ '--tw-prose-invert-headings': theme('colors.white'),
72
+ '--tw-prose-invert-lead': theme('colors.secondary[400]'),
73
+ '--tw-prose-invert-links': theme('colors.primary[400]'),
74
+ '--tw-prose-invert-bold': theme('colors.white'),
75
+ '--tw-prose-invert-counters': theme('colors.secondary[400]'),
76
+ '--tw-prose-invert-bullets': theme('colors.secondary[600]'),
77
+ '--tw-prose-invert-hr': theme('colors.secondary[700]'),
78
+ '--tw-prose-invert-quotes': theme('colors.secondary[100]'),
79
+ '--tw-prose-invert-quote-borders': theme('colors.secondary[700]'),
80
+ '--tw-prose-invert-captions': theme('colors.secondary[400]'),
81
+ '--tw-prose-invert-code': theme('colors.white'),
82
+ '--tw-prose-invert-pre-code': theme('colors.secondary[300]'),
83
+ '--tw-prose-invert-pre-bg': theme('colors.secondary[800]'),
84
+ '--tw-prose-invert-th-borders': theme('colors.secondary[600]'),
85
+ '--tw-prose-invert-td-borders': theme('colors.secondary[700]'),
86
+ 'code::before': { content: 'none' },
87
+ 'code::after': { content: 'none' },
88
+ 'pre': {
89
+ borderRadius: theme('borderRadius.lg'),
90
+ boxShadow: theme('boxShadow.sm'),
91
+ paddingTop: theme('spacing.4'),
92
+ paddingBottom: theme('spacing.4'),
93
+ paddingLeft: theme('spacing.5'),
94
+ paddingRight: theme('spacing.5'),
95
+ },
96
+ 'table': { fontSize: theme('fontSize.sm') },
97
+ 'thead': { borderBottomWidth: '1px', borderBottomColor: 'var(--tw-prose-th-borders)' },
98
+ 'tbody tr': { borderBottomWidth: '1px', borderBottomColor: 'var(--tw-prose-td-borders)' },
99
+ 'td, th': { padding: theme('spacing.2') + ' ' + theme('spacing.3') },
100
+ },
101
+ },
102
+ }),
103
  }
104
  }
105
  }
106
  </script>
107
+
108
  <style>
109
+ /* Base Styles & Layout */
110
+ html { scroll-behavior: smooth; }
111
+ body { @apply font-sans antialiased transition-colors duration-300 ease-in-out; }
112
+
113
+ /* Full height layout using flex */
114
+ .main-layout {
115
+ display: flex;
116
+ flex-direction: column;
117
+ min-height: 100vh; /* Use min-height to be safe, but 100vh is often fine with this structure */
118
+ max-height: 100vh;
119
+ overflow: hidden; /* Prevent body scroll */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  }
121
+
122
+ #chat-messages {
123
+ flex-grow: 1; /* Take available space */
124
+ overflow-y: auto; /* Enable vertical scrolling */
125
+ -webkit-overflow-scrolling: touch; /* Smooth scrolling on iOS */
126
+ overscroll-behavior-y: contain; /* Prevent pull-to-refresh on scroll */
127
+ scrollbar-gutter: stable; /* Prevent layout shifts when scrollbar appears/disappears */
128
  }
129
+
130
+ /* Scrollbar Styling */
131
+ ::-webkit-scrollbar { width: 6px; height: 6px; }
132
+ ::-webkit-scrollbar-track { background: transparent; }
133
+ ::-webkit-scrollbar-thumb { @apply bg-secondary-300 dark:bg-secondary-700 rounded-full; }
134
+ ::-webkit-scrollbar-thumb:hover { @apply bg-secondary-400 dark:bg-secondary-600; }
135
+ /* Firefox scrollbar */
136
+ html { scrollbar-color: theme('colors.secondary.300') transparent; scrollbar-width: thin; }
137
+ .dark html { scrollbar-color: theme('colors.secondary.700') transparent; }
138
+
139
+
140
+ /* Message Bubbles */
141
  .message-bubble {
142
  position: relative;
143
  max-width: 85%;
144
+ border-radius: 1.125rem;
145
+ padding: 0.75rem 1.125rem;
146
+ line-height: 1.6;
147
+ box-shadow: 0 2px 4px rgba(0,0,0,0.05);
 
148
  transition: transform 0.2s ease, box-shadow 0.2s ease;
149
+ word-wrap: break-word;
150
+ overflow-wrap: break-word;
151
  }
152
+ .message-bubble:hover { box-shadow: 0 5px 10px rgba(0,0,0,0.07); }
153
+ .dark .message-bubble { box-shadow: 0 2px 4px rgba(0,0,0,0.15); }
154
+ .dark .message-bubble:hover { box-shadow: 0 5px 12px rgba(0,0,0,0.2); }
155
+
 
 
 
 
 
156
  .user-message {
157
+ border-bottom-right-radius: 0.25rem;
158
  align-self: flex-end;
159
+ @apply bg-gradient-to-br from-primary-500 to-primary-600 text-white;
 
160
  }
161
+ .assistant-message-wrapper {
 
162
  align-self: flex-start;
163
+ display: flex;
164
+ gap: 0.625rem;
165
+ max-width: 85%;
166
  }
167
+ .assistant-avatar {
168
+ @apply w-8 h-8 rounded-full bg-gradient-to-br from-primary-100 to-primary-200 dark:from-primary-800 dark:to-primary-900 flex items-center justify-center flex-shrink-0 shadow-sm text-primary-700;
169
+ font-size: 1.1rem;
 
 
 
 
 
 
 
 
 
170
  }
171
+ .dark .assistant-avatar { @apply text-primary-200; }
172
+
173
+ .assistant-message {
174
+ border-bottom-left-radius: 0.25rem;
175
+ @apply bg-white dark:bg-secondary-800 text-secondary-800 dark:text-secondary-100 border border-secondary-200 dark:border-secondary-700;
176
  }
177
+
178
+ /* Message animation */
179
+ .message-animate { animation: slideUp 0.3s ease-out forwards; }
180
+
181
+ /* Typing Indicator */
182
+ .typing-indicator { display: flex; align-items: center; gap: 0.2rem; }
183
  .typing-dot {
184
+ @apply w-2 h-2 rounded-full bg-current opacity-70;
185
+ animation: typingDotPulse 1.4s infinite ease-in-out both;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  }
187
+ .typing-dot:nth-child(1) { animation-delay: -0.32s; }
188
+ .typing-dot:nth-child(2) { animation-delay: -0.16s; }
189
+
190
+ /* Tooltip Styling */
191
+ .tooltip { position: relative; display: inline-block; } /* Ensure tooltip works on various elements */
192
  .tooltip .tooltip-text {
193
+ @apply invisible opacity-0 transition-opacity duration-200 ease-in-out;
194
+ @apply bg-secondary-800 dark:bg-secondary-600 text-white dark:text-secondary-100 text-xs font-medium;
195
+ @apply rounded-md px-2 py-1 shadow-lg whitespace-nowrap;
 
 
 
 
 
196
  position: absolute;
197
+ z-index: 20;
198
+ bottom: 130%;
199
  left: 50%;
200
  transform: translateX(-50%);
 
 
 
 
201
  pointer-events: none;
202
  }
 
 
 
 
203
  .tooltip .tooltip-text::after {
204
+ content: ""; position: absolute; top: 100%; left: 50%; margin-left: -4px;
205
+ border-width: 4px; border-style: solid;
206
+ @apply border-transparent border-t-secondary-800 dark:border-t-secondary-600;
 
 
 
 
 
 
 
 
 
 
 
 
207
  }
208
+ .tooltip:hover .tooltip-text,
209
+ .tooltip:focus-within .tooltip-text { @apply visible opacity-100; }
210
+
211
+ /* Copy Button (Message & Code) */
212
  .copy-btn {
213
+ @apply absolute top-2 right-2 p-1.5 rounded-md text-secondary-500 dark:text-secondary-400;
214
+ @apply bg-white/70 dark:bg-secondary-700/70 backdrop-blur-sm;
215
+ @apply opacity-0 group-hover:opacity-100 focus:opacity-100 transition-opacity duration-200;
216
+ @apply hover:bg-secondary-100 dark:hover:bg-secondary-600 hover:text-primary-600 dark:hover:text-primary-300;
217
+ z-index: 5;
 
218
  }
219
+ .copy-btn i { font-size: 0.8rem; }
220
+
221
+ .code-copy-btn {
222
+ @apply absolute top-2 right-2 p-1.5 rounded-md text-secondary-500 dark:text-secondary-400;
223
+ @apply bg-secondary-200/50 dark:bg-secondary-900/50 backdrop-blur-sm;
224
+ @apply opacity-0 group-hover:opacity-100 focus:opacity-100 transition-opacity duration-200;
225
+ @apply hover:bg-secondary-300/70 dark:hover:bg-secondary-800/70 hover:text-primary-600 dark:hover:text-primary-300;
226
+ z-index: 5;
227
  }
228
+ .code-copy-btn i { font-size: 0.8rem; }
229
+
230
+
231
+ /* File Preview */
232
+ .file-preview-wrapper {
233
+ @apply relative max-w-[250px] mx-auto my-2 rounded-lg overflow-hidden shadow-md border border-secondary-200 dark:border-secondary-700;
234
  transition: transform 0.2s ease;
235
  }
236
+ .file-preview-wrapper:hover { transform: scale(1.03); }
237
+ .file-preview-wrapper img { @apply block w-full h-auto object-cover; }
238
+ .file-info-overlay {
239
+ @apply absolute bottom-0 left-0 right-0 p-2 bg-gradient-to-t from-black/60 to-transparent text-white text-xs;
240
+ pointer-events: none;
 
 
 
241
  }
242
+ .file-info-overlay span { @apply block truncate; }
243
+
244
+ /* File Chip */
245
  .chip {
246
+ @apply inline-flex items-center bg-primary-100 dark:bg-primary-900/60 rounded-full py-1 pl-2.5 pr-1 text-xs font-medium text-primary-700 dark:text-primary-200;
 
 
 
 
 
 
 
247
  transition: all 0.2s ease;
248
+ max-width: 150px;
249
  }
250
+ .chip .chip-icon { @apply mr-1.5 text-primary-500 dark:text-primary-400; font-size: 0.8em;}
251
+ .chip .chip-text { @apply truncate flex-1 mr-1; }
252
  .chip .chip-close {
253
+ @apply ml-auto w-4 h-4 flex items-center justify-center rounded-full bg-primary-200 dark:bg-primary-700/80 text-primary-600 dark:text-primary-100 cursor-pointer transition-colors;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
  }
255
+ .chip .chip-close:hover { @apply bg-primary-300 dark:bg-primary-600; }
256
+ .chip .chip-close i { font-size: 0.6rem; }
257
+
258
+
259
+ /* Toggle Switch */
260
+ .toggle-switch { position: relative; display: inline-block; width: 36px; height: 20px; }
261
+ .toggle-switch input { opacity: 0; width: 0; height: 0; }
262
  .toggle-slider {
263
+ position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0;
264
+ @apply bg-secondary-300 dark:bg-secondary-600 transition-colors duration-300 ease-in-out rounded-full;
 
 
 
 
 
 
 
265
  }
266
  .toggle-slider:before {
267
+ position: absolute; content: ""; height: 14px; width: 14px; left: 3px; bottom: 3px;
268
+ @apply bg-white transition-transform duration-300 ease-in-out rounded-full shadow;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
269
  }
270
+ input:checked + .toggle-slider { @apply bg-primary-500 dark:bg-primary-600; }
271
+ input:focus-visible + .toggle-slider { @apply ring-2 ring-primary-400 ring-offset-1 ring-offset-secondary-50 dark:ring-offset-secondary-950; }
272
+ input:checked + .toggle-slider:before { transform: translateX(16px); }
273
+ input:disabled + .toggle-slider { @apply opacity-50 cursor-not-allowed; }
274
+
275
+ /* Chat Input Area */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
276
  .chat-textarea {
277
+ @apply block w-full resize-none overflow-y-auto bg-transparent dark:text-secondary-100 placeholder-secondary-400 dark:placeholder-secondary-500;
278
+ @apply transition-all duration-200 ease-in-out;
279
  min-height: 44px;
280
+ max-height: 180px;
 
281
  line-height: 1.5;
 
 
282
  padding-top: 0.625rem;
283
  padding-bottom: 0.625rem;
284
  padding-left: 1rem;
285
+ padding-right: 3.5rem;
286
+ border: none;
287
+ outline: none;
288
+ box-shadow: none;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289
  }
290
+
291
+ .chat-input-container {
292
+ @apply relative flex items-end bg-white dark:bg-secondary-900 rounded-full border border-secondary-300 dark:border-secondary-700 shadow-sm transition-all duration-200 ease-in-out;
 
 
293
  }
294
+ .chat-input-container:focus-within { @apply ring-2 ring-primary-400; }
295
+
296
+ .send-button-wrapper { @apply absolute right-1.5 bottom-[5px]; }
297
+ #send-button {
298
+ @apply w-9 h-9 rounded-full flex items-center justify-center transition-all duration-200 ease-in-out;
299
+ @apply bg-primary-500 text-white hover:bg-primary-600 dark:bg-primary-600 dark:hover:bg-primary-500;
300
+ @apply focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-400 focus-visible:ring-offset-1 focus-visible:ring-offset-white dark:focus-visible:ring-offset-secondary-900;
301
+ @apply disabled:opacity-50 disabled:cursor-not-allowed disabled:bg-secondary-300 dark:disabled:bg-secondary-700;
302
+ }
303
+ #send-button i { font-size: 0.95rem; }
304
+
305
+ /* Markdown Table Wrapper */
306
+ .table-wrapper {
307
+ @apply w-full overflow-x-auto my-4 rounded-lg border border-secondary-200 dark:border-secondary-700 shadow-sm;
308
  }
309
+ .dark .table-wrapper { border-color: var(--tw-prose-invert-td-borders); }
310
+
311
+ /* Error Banner */
312
+ #error-message {
313
+ @apply bg-red-50 dark:bg-red-900/30 border-l-4 border-red-500 dark:border-red-600 text-red-800 dark:text-red-200 p-4 rounded-r-md shadow-md transition-all duration-300 ease-in-out;
314
+ max-height: 500px; /* For transition */
315
+ overflow: hidden;
316
+ }
317
+ #error-message.hidden {
318
+ @apply max-h-0 p-0 border-0 opacity-0;
319
+ }
320
+ #error-message .icon { @apply text-red-500 dark:text-red-400; }
321
+ #error-message button {
322
+ @apply text-red-600 dark:text-red-300 hover:text-red-800 dark:hover:text-red-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-400 rounded-sm p-0.5;
323
+ }
324
+
325
+ /* History Loader */
326
+ #history-loading .loader-icon { animation: spin 1s linear infinite; }
327
+ @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
328
+
329
+ /* Focus Visible for Accessibility */
330
+ *:focus-visible {
331
+ outline: 2px solid theme('colors.primary.400');
332
+ outline-offset: 2px;
333
+ border-radius: 2px;
334
+ }
335
+ .chat-input-container:focus-within,
336
+ #send-button:focus-visible,
337
+ .toggle-switch input:focus-visible + .toggle-slider,
338
+ #error-message button:focus-visible {
339
+ outline: none;
340
+ }
341
+
342
+ /* Responsive Adjustments */
343
+ @media (max-width: 640px) {
344
+ body { font-size: 0.95rem; }
345
+ .message-bubble { max-width: 92%; padding: 0.6rem 1rem; }
346
+ .assistant-avatar { width: 28px; height: 28px; font-size: 1rem; }
347
+ .assistant-message-wrapper { gap: 0.5rem; max-width: 92%;}
348
+ .chat-textarea { min-height: 40px; max-height: 120px; padding-left: 0.875rem; padding-right: 3rem; }
349
+ .send-button-wrapper { right: 0.375rem; bottom: 4px; }
350
+ #send-button { width: 32px; height: 32px; }
351
+ #send-button i { font-size: 0.85rem; }
352
+ .options-bar { flex-direction: column; align-items: flex-start; gap: 0.5rem; padding: 0.5rem 0.75rem; }
353
+ .options-group { justify-content: space-between; width: 100%; }
354
+ .chip { max-width: 120px; }
355
+ .prose { font-size: 0.9rem; }
356
+ .prose table { font-size: 0.8rem; }
357
+ .prose td, .prose th { padding: 0.3rem 0.5rem; }
358
+ .tooltip .tooltip-text { font-size: 0.7rem; }
359
+ .header-action-text { display: none; }
360
+ .header-clear-button { padding-left: 0.5rem; padding-right: 0.5rem; }
361
+ .header-clear-button i { margin-right: 0; }
362
+ }
363
  </style>
364
  </head>
365
+
366
+ <body class="h-full bg-secondary-50 text-secondary-900 dark:bg-secondary-950 dark:text-secondary-100">
367
+ <div class="main-layout">
368
+
369
+ <!-- Header -->
370
+ <header class="bg-white dark:bg-secondary-900 border-b border-secondary-200 dark:border-secondary-800 shadow-sm py-2 px-4 sm:px-6 sticky top-0 z-20 transition-colors duration-300">
371
+ <div class="max-w-5xl mx-auto flex justify-between items-center h-12">
372
+ <!-- Logo & Title -->
373
+ <div class="flex items-center space-x-3">
374
+ <img src="https://mariam-241.vercel.app/static/image/logoboma.png" alt="Logo Mariam AI" class="h-8 sm:h-9 object-contain flex-shrink-0">
375
+ <h1 class="text-lg sm:text-xl font-semibold text-secondary-800 dark:text-secondary-100 truncate">Mariam AI</h1>
376
+ </div>
377
+
378
+ <!-- Actions -->
379
+ <div class="flex items-center space-x-2 sm:space-x-3">
380
+ <!-- Theme Toggle Button -->
381
+ <button id="theme-toggle" class="tooltip p-2 rounded-full text-secondary-600 dark:text-secondary-400 hover:bg-secondary-100 dark:hover:bg-secondary-800 hover:text-primary-600 dark:hover:text-primary-300 transition-colors duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-400" aria-label="Changer de thème">
382
+ <i class="fa-solid fa-moon text-lg hidden dark:inline"></i>
383
+ <i class="fa-solid fa-sun text-lg dark:hidden"></i>
384
+ <span class="tooltip-text">Mode Sombre / Clair</span>
 
385
  </button>
386
+
387
+ <!-- Clear Chat Button -->
388
+ <form action="/clear" method="POST" id="clear-form">
389
+ <button type="submit" class="tooltip header-clear-button flex items-center bg-red-100 hover:bg-red-200 dark:bg-red-900/50 dark:hover:bg-red-800/70 text-red-600 dark:text-red-300 dark:hover:text-red-200 text-xs font-semibold py-1.5 px-2 sm:px-3 rounded-full transition duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-400" aria-label="Effacer la conversation">
390
+ <i class="fa-solid fa-eraser mr-0 sm:mr-1.5 text-sm"></i>
391
+ <span class="header-action-text">Effacer</span>
392
+ <span class="tooltip-text">Effacer la conversation</span>
393
+ </button>
394
+ </form>
 
 
 
 
 
 
 
395
  </div>
396
  </div>
397
+ </header>
398
+
399
+ <!-- Main Content Area -->
400
+ <main class="flex-grow overflow-hidden flex flex-col">
401
+
402
+ <!-- Chat Messages Container -->
403
+ <section id="chat-messages" class="flex-grow p-4 sm:p-6 space-y-5 overflow-y-auto">
404
+
405
+ <!-- History Loading Indicator -->
406
+ <div id="history-loading" class="text-center py-10 animate-fade-in">
407
+ <div class="inline-flex items-center px-4 py-2 bg-secondary-100 text-secondary-600 dark:bg-secondary-800 dark:text-secondary-300 rounded-lg shadow-sm text-sm">
408
+ <svg class="loader-icon h-4 w-4 mr-2 text-primary-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
409
+ <path stroke-linecap="round" stroke-linejoin="round" d="M16.023 9.348h4.992v-.001m0 0l-3.181 3.183a8.25 8.25 0 01-13.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99"></path>
410
+ </svg>
411
+ <span>Chargement de la conversation...</span>
412
+ </div>
413
  </div>
414
+
415
+ <!-- AI Response Loading Indicator (kept in HTML for initial structure) -->
416
+ <div id="loading-indicator" class="assistant-message-wrapper hidden message-animate">
417
+ <div class="assistant-avatar">✨</div>
418
+ <div class="message-bubble assistant-message flex items-center space-x-2">
419
+ <span class="text-sm italic">Mariam réfléchit</span>
420
+ <div class="typing-indicator">
421
+ <span class="typing-dot"></span>
422
+ <span class="typing-dot"></span>
423
+ <span class="typing-dot"></span>
424
+ </div>
425
  </div>
426
  </div>
427
+
428
+ </section>
429
+
430
+ </main>
431
+
432
+ <!-- Footer: Input Area and Options -->
433
+ <footer class="border-t border-secondary-200 dark:border-secondary-800 bg-secondary-100 dark:bg-secondary-900/80 backdrop-blur-sm sticky bottom-0 z-10 transition-colors duration-300">
434
+
435
+ <!-- Error Banner -->
436
+ <div id="error-message" class="hidden" role="alert" aria-hidden="true">
437
+ <div class="flex items-start">
438
+ <div class="flex-shrink-0 mt-0.5">
439
+ <i class="fa-solid fa-circle-exclamation icon text-lg"></i>
440
+ </div>
441
+ <div class="ml-3 flex-grow">
442
+ <p class="text-sm font-medium" id="error-text">Message d'erreur.</p>
443
+ </div>
444
+ <div class="ml-auto pl-3">
445
+ <button type="button" class="-mx-1.5 -my-1.5 p-1.5" id="dismiss-error" aria-label="Fermer l'alerte">
446
+ <i class="fa-solid fa-xmark"></i>
447
+ </button>
448
+ </div>
449
  </div>
450
  </div>
451
+
452
+ <!-- Preview Area + Options -->
453
+ <div class="px-4 py-2 space-y-2">
454
+ <!-- File Preview (if present) -->
455
+ <div id="preview-area" class="hidden">
456
+ <!-- File preview content will be injected here by JS -->
457
+ </div>
458
+
459
+ <!-- Options Bar -->
460
+ <div class="options-bar flex items-center justify-between flex-wrap gap-x-4 gap-y-2 text-xs sm:text-sm text-secondary-700 dark:text-secondary-300">
461
+ <!-- Left Options Group -->
462
+ <div class="options-group flex items-center space-x-3 sm:space-x-4 flex-wrap gap-y-2">
463
+ <!-- Web Search Toggle -->
464
+ <label class="flex items-center cursor-pointer tooltip group">
465
+ <span class="toggle-switch">
466
+ <input type="checkbox" id="web_search_toggle" name="web_search" value="true" class="sr-only">
467
+ <span class="toggle-slider"></span>
468
+ </span>
469
+ <span class="ml-2 font-medium group-hover:text-primary-600 dark:group-hover:text-primary-300 transition-colors">
470
+ <i class="fa-solid fa-globe mr-1 opacity-70"></i>
471
+ <span class="hidden sm:inline">Recherche Web</span>
472
+ </span>
473
+ <span class="tooltip-text">Activer la recherche web</span>
474
+ </label>
475
+
476
+ <!-- Advanced Reasoning Toggle -->
477
+ <label class="flex items-center cursor-pointer tooltip group">
478
+ <span class="toggle-switch">
479
+ <input type="checkbox" id="advanced_reasoning_toggle" name="advanced_reasoning" value="true" class="sr-only">
480
+ <span class="toggle-slider"></span>
481
+ </span>
482
+ <span class="ml-2 font-medium text-accent-700 dark:text-accent-400 group-hover:text-accent-600 dark:group-hover:text-accent-300 transition-colors">
483
+ <i class="fa-solid fa-brain mr-1 opacity-70"></i>
484
+ <span class="hidden sm:inline">Avancé</span>
485
+ <span id="advanced-cooldown-timer" class="text-xs ml-1 hidden opacity-80"></span>
486
+ </span>
487
+ <span class="tooltip-text">Raisonnement avancé (1 fois/min)</span>
488
+ </label>
489
+ </div>
490
+
491
+ <!-- Right Options Group (File) -->
492
+ <div class="options-group flex items-center space-x-2">
493
+ <!-- File Chip (if attached) -->
494
+ <div id="file-chip" class="chip hidden animate-fade-in">
495
+ <i class="fa-solid fa-paperclip chip-icon"></i>
496
+ <span id="file-name" class="chip-text"></span>
497
+ <button id="clear-file" class="chip-close tooltip" aria-label="Retirer le fichier">
498
+ <i class="fa-solid fa-xmark"></i>
499
+ <span class="tooltip-text !bottom-full !mb-1">Retirer</span>
500
+ </button>
501
+ </div>
502
+
503
+ <!-- File Upload Button -->
504
+ <label for="file_upload" class="tooltip cursor-pointer p-2 rounded-full text-secondary-600 dark:text-secondary-400 hover:bg-secondary-200 dark:hover:bg-secondary-700 hover:text-primary-600 dark:hover:text-primary-300 transition-colors duration-200 focus-within:ring-2 focus-within:ring-primary-400">
505
+ <i class="fa-solid fa-paperclip"></i>
506
+ <input type="file" id="file_upload" name="file" class="hidden" accept=".txt,.pdf,.png,.jpg,.jpeg,.md,.csv,.json,.xml,.docx,.pptx,.xlsx">
507
+ <span class="tooltip-text">Joindre fichier (texte, pdf, image, doc...)</span>
508
+ </label>
509
+ </div>
510
+ </div>
511
  </div>
512
+
513
+ <!-- Chat Form -->
514
+ <form id="chat-form" class="p-3 sm:p-4 pt-0">
515
+ <div class="chat-input-container">
516
  <textarea
517
  id="prompt"
518
  name="prompt"
519
+ class="chat-textarea"
520
  placeholder="Posez votre question à Mariam..."
521
  autocomplete="off"
522
+ rows="1"
523
+ aria-label="Votre message"></textarea>
524
  <div class="send-button-wrapper">
525
  <button
526
  type="submit"
527
  id="send-button"
528
+ title="Envoyer (Entrée)"
529
+ aria-label="Envoyer le message">
530
+ <i class="fa-solid fa-arrow-up"></i>
531
  </button>
532
  </div>
533
  </div>
534
+ <div class="text-xs text-center mt-2 text-secondary-500 dark:text-secondary-400">
535
+ <kbd class="px-1.5 py-0.5 bg-secondary-200 dark:bg-secondary-700 rounded border border-secondary-300 dark:border-secondary-600 font-sans font-semibold">Entrée</kbd> envoyer
536
+ <span class="mx-1">•</span>
537
+ <kbd class="px-1.5 py-0.5 bg-secondary-200 dark:bg-secondary-700 rounded border border-secondary-300 dark:border-secondary-600 font-sans font-semibold">Shift+Entrée</kbd> nouvelle ligne
538
+ </div>
 
 
 
 
539
  </form>
540
+ </footer>
541
+
542
+ <!-- Confirmation Modal for Clear Chat -->
543
+ <!-- This modal is dynamically added/removed by JS -->
544
+ <!-- Example Structure:
545
+ <div class="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4 animate-fade-in" role="dialog" aria-modal="true" aria-labelledby="confirm-dialog-title">
546
+ <div class="bg-white dark:bg-secondary-800 p-6 rounded-lg shadow-xl max-w-sm w-full transform transition-transform duration-300 scale-95 opacity-0" data-dialog-content>
547
+ <h3 id="confirm-dialog-title" class="text-lg font-semibold mb-3 text-secondary-900 dark:text-secondary-100">Vider la conversation ?</h3>
548
+ <p class="text-sm text-secondary-600 dark:text-secondary-300 mb-6">Toute l'historique de cette session sera définitivement effacé.</p>
549
+ <div class="flex justify-end space-x-3">
550
+ <button type="button" data-cancel class="..."> Annuler </button>
551
+ <button type="button" data-confirm class="..."> Effacer </button>
552
+ </div>
553
+ </div>
554
  </div>
555
+ -->
556
+
557
+ </div>
558
+
559
  <!-- Scripts -->
560
  <script>
561
  document.addEventListener('DOMContentLoaded', () => {
562
+ // --- DOM Elements Selection ---
563
  const chatForm = document.getElementById('chat-form');
564
  const promptInput = document.getElementById('prompt');
565
  const chatMessages = document.getElementById('chat-messages');
 
573
  const fileChip = document.getElementById('file-chip');
574
  const fileNameSpan = document.getElementById('file-name');
575
  const clearFileButton = document.getElementById('clear-file');
 
576
  const previewArea = document.getElementById('preview-area');
577
  const sendButton = document.getElementById('send-button');
578
  const clearForm = document.getElementById('clear-form');
579
  const advancedToggle = document.getElementById('advanced_reasoning_toggle');
580
  const advancedCooldownTimerSpan = document.getElementById('advanced-cooldown-timer');
581
  const themeToggleBtn = document.getElementById('theme-toggle');
582
+ const htmlElement = document.documentElement;
583
+
584
+ // --- Constants and Variables ---
585
+ const API_CHAT_ENDPOINT = '/api/chat'; // Replace with your actual chat endpoint
586
+ const API_HISTORY_ENDPOINT = '/api/history'; // Replace with your actual history endpoint
587
+ const CLEAR_ENDPOINT = '/clear'; // Replace with your actual clear endpoint
588
+ const COOLDOWN_DURATION = 60 * 1000; // 60 seconds for advanced reasoning
589
+ const MOBILE_BREAKPOINT = 640; // Tailwind's sm breakpoint
590
+
591
  let advancedToggleCooldownEndTime = 0;
592
+ let advancedCooldownIntervalId = null;
593
  let isComposing = false;
594
+ let currentAssistantMessageDiv = null; // For potential streaming
595
 
596
+ // --- Utility Functions ---
597
+
598
+ // Basic HTML escaping
599
+ function escapeHtml(unsafe) {
600
+ if (!unsafe) return '';
601
+ return unsafe
602
+ .replace(/&/g, "&")
603
+ .replace(/</g, "<")
604
+ .replace(/>/g, ">")
605
+ .replace(/"/g, """)
606
+ .replace(/'/g, "'");
 
 
 
 
 
607
  }
 
 
608
 
609
+ // Adjust textarea height based on content
610
+ function adjustTextareaHeight() {
611
+ promptInput.style.height = 'auto';
612
+ const scrollHeight = promptInput.scrollHeight;
613
+ const maxHeight = parseInt(window.getComputedStyle(promptInput).maxHeight, 10);
614
+ promptInput.style.height = `${Math.min(scrollHeight, maxHeight)}px`;
615
+
616
+ // Optional: Adjust padding-bottom of messages area if input grows large
617
+ // const footerHeight = document.querySelector('footer').offsetHeight;
618
+ // chatMessages.style.paddingBottom = `${footerHeight + 16}px`;
619
  }
620
 
621
+ // Scroll to the bottom of the chat messages area
622
+ function scrollToBottom(behavior = 'smooth') {
623
+ requestAnimationFrame(() => {
624
+ setTimeout(() => {
625
+ chatMessages.scrollTo({ top: chatMessages.scrollHeight, behavior });
626
+ }, behavior === 'smooth' ? 50 : 10); // Small delay to ensure rendering
627
+ });
628
  }
629
 
630
+ // Show/hide the AI loading indicator
631
  function showLoading(show) {
 
 
 
 
 
 
 
632
  sendButton.disabled = show;
633
  promptInput.disabled = show;
634
  fileUpload.disabled = show;
635
+ webSearchToggle.disabled = show; // Disable web search toggle
636
+ // Disable advanced toggle, considering its own cooldown
637
+ advancedToggle.disabled = show || (advancedToggleCooldownEndTime > Date.now());
638
+
639
  if (show) {
640
+ loadingIndicator.classList.remove('hidden');
641
+ chatMessages.appendChild(loadingIndicator); // Ensure loader is at the end
642
+ scrollToBottom();
643
+ // Visually indicate disabled state for file clear
644
  clearFileButton.style.pointerEvents = 'none';
645
  clearFileButton.style.opacity = '0.5';
646
  } else {
647
+ loadingIndicator.classList.add('hidden');
648
+ // Reset state for file clear
649
  clearFileButton.style.pointerEvents = 'auto';
650
+ clearFileButton.style.opacity = '1';
651
  }
652
  }
653
 
654
+ // Display an error message in the banner
655
  function displayError(message) {
656
+ errorTextP.textContent = message || "An unknown error occurred.";
657
+ errorMessageDiv.classList.remove('hidden', 'opacity-0', 'max-h-0', 'p-0', 'border-0');
658
+ errorMessageDiv.setAttribute('aria-hidden', 'false');
659
+ // Optional: scroll error into view if needed
660
+ // errorMessageDiv.scrollIntoView({ behavior: 'smooth', block: 'center' });
661
  }
 
662
 
663
+ // Hide the error banner
664
+ function hideError() {
665
+ if (errorMessageDiv.classList.contains('hidden')) return; // Avoid multiple calls
666
+ errorMessageDiv.classList.add('opacity-0', 'max-h-0', 'p-0', 'border-0');
667
+ // Wait for transition to complete before hiding
668
+ setTimeout(() => {
669
+ errorMessageDiv.classList.add('hidden');
670
+ errorMessageDiv.setAttribute('aria-hidden', 'true');
671
+ }, 300);
672
+ }
673
+
674
+ // Format file size for display
675
+ function formatFileSize(bytes) {
676
+ if (bytes === 0) return '0 Bytes';
677
+ const k = 1024;
678
+ const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
679
+ const i = Math.max(0, Math.floor(Math.log(bytes) / Math.log(k)));
680
+ if (i >= sizes.length) return `${(bytes / Math.pow(k, sizes.length - 1)).toFixed(1)} ${sizes[sizes.length - 1]}`;
681
+ return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`;
682
+ }
683
+
684
+ // Get FontAwesome icon class for file type
685
+ function getFileIcon(fileType) {
686
+ if (!fileType) return 'fa-file';
687
+ if (fileType.includes('pdf')) return 'fa-file-pdf';
688
+ if (fileType.includes('image')) return 'fa-file-image';
689
+ if (fileType.includes('video')) return 'fa-file-video';
690
+ if (fileType.includes('audio')) return 'fa-file-audio';
691
+ if (fileType.includes('zip') || fileType.includes('archive')) return 'fa-file-zipper';
692
+ if (fileType.includes('word')) return 'fa-file-word';
693
+ if (fileType.includes('spreadsheet') || fileType.includes('excel')) return 'fa-file-excel';
694
+ if (fileType.includes('presentation') || fileType.includes('powerpoint')) return 'fa-file-powerpoint';
695
+ if (fileType.includes('text')) return 'fa-file-lines';
696
+ if (fileType.includes('csv')) return 'fa-file-csv';
697
+ if (fileType.includes('code') || fileType.includes('script') || fileType.includes('json') || fileType.includes('xml')) return 'fa-file-code';
698
+ return 'fa-file';
699
+ }
700
+
701
+
702
+ // --- Theme Management ---
703
+ function applyTheme(theme) {
704
+ if (theme === 'dark') {
705
+ htmlElement.classList.add('dark');
706
+ } else {
707
+ htmlElement.classList.remove('dark');
708
+ }
709
+ // Update scrollbar color if needed (Firefox)
710
+ // This is handled by CSS variable in the style block now
711
+ }
712
 
713
+ function initializeTheme() {
714
+ const savedTheme = localStorage.theme;
715
+ const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
716
+ if (savedTheme) {
717
+ applyTheme(savedTheme);
718
  } else {
719
+ applyTheme(prefersDark ? 'dark' : 'light');
720
  }
721
+ }
722
+
723
+ function toggleTheme() {
724
+ const isDark = htmlElement.classList.contains('dark');
725
+ const newTheme = isDark ? 'light' : 'dark';
726
+ applyTheme(newTheme);
727
+ localStorage.theme = newTheme;
728
+ }
729
+
730
+
731
+ // --- Add Message to Chat ---
732
+ function addMessageToChat(role, content, isHtml = false, animate = true) {
733
+ hideError(); // Hide error banner on new message
734
+
735
+ const messageWrapper = document.createElement('div');
736
+ messageWrapper.classList.add('message-animate');
737
+
738
+ let messageHtml = '';
739
+ let textContentForCopy = content;
740
+
741
+ // Basic sanitization for HTML content
742
+ const cleanContent = isHtml ? content : escapeHtml(content);
743
 
 
744
  if (role === 'user') {
745
+ messageWrapper.classList.add('flex', 'justify-end', 'w-full');
746
+ messageHtml = `
747
+ <div class="message-bubble user-message group relative">
748
+ <div class="prose prose-sm sm:prose-base max-w-none text-white dark:prose-invert">${cleanContent}</div>
749
+ <button class="copy-btn" aria-label="Copy message">
750
+ <i class="fa-regular fa-copy"></i>
751
+ </button>
752
  </div>
753
  `;
754
+ textContentForCopy = content; // Use original text for copy
755
+ } else { // Assistant
756
+ messageWrapper.classList.add('assistant-message-wrapper');
757
+ messageHtml = `
758
+ <div class="assistant-avatar">✨</div>
759
+ <div class="message-bubble assistant-message group relative">
760
+ <div class="prose prose-sm sm:prose-base max-w-none dark:prose-invert">
761
+ ${cleanContent}
 
 
 
 
 
762
  </div>
763
+ <button class="copy-btn" aria-label="Copy response">
764
+ <i class="fa-regular fa-copy"></i>
765
+ </button>
766
  </div>
767
  `;
768
+ // Extract plain text from HTML for copy
769
+ const tempDiv = document.createElement('div');
770
+ tempDiv.innerHTML = content; // Use original content before escape
771
+ textContentForCopy = tempDiv.textContent || tempDiv.innerText || content;
772
  }
773
+
774
+ messageWrapper.innerHTML = messageHtml;
775
+
776
+ // Insert message before the loading indicator
777
+ chatMessages.insertBefore(messageWrapper, loadingIndicator);
778
+
779
+ // Activate message copy button
780
+ const copyBtn = messageWrapper.querySelector('.copy-btn');
781
+ if (copyBtn) {
782
+ copyBtn.addEventListener('click', () => {
783
+ navigator.clipboard.writeText(textContentForCopy).then(() => {
784
+ const icon = copyBtn.querySelector('i');
785
+ icon.classList.remove('fa-regular', 'fa-copy');
786
+ icon.classList.add('fa-solid', 'fa-check');
787
+ copyBtn.setAttribute('aria-label', 'Copied!');
788
+ setTimeout(() => {
789
+ icon.classList.remove('fa-solid', 'fa-check');
790
+ icon.classList.add('fa-regular', 'fa-copy');
791
+ copyBtn.setAttribute('aria-label', 'Copy response');
792
+ }, 2000);
793
+ }).catch(err => {
794
+ console.error('Copy failed:', err);
795
+ // Optionally display a copy error
796
+ });
797
  });
798
+ }
799
 
800
+ // Activate code block copy buttons within this new message
801
+ messageWrapper.querySelectorAll('pre').forEach(pre => {
802
+ pre.classList.add('group', 'relative');
803
  const code = pre.querySelector('code');
804
  if (!code) return;
805
+
806
+ // Prevent adding button if already exists (e.g. during history load)
807
  if (pre.querySelector('.code-copy-btn')) return;
808
+
809
+ const copyCodeButton = document.createElement('button');
810
+ copyCodeButton.innerHTML = '<i class="fa-regular fa-copy"></i>';
811
+ copyCodeButton.className = 'code-copy-btn tooltip';
812
+ copyCodeButton.setAttribute('aria-label', 'Copy code');
813
+
814
  const tooltipText = document.createElement('span');
815
  tooltipText.className = 'tooltip-text !text-xs';
816
+ tooltipText.textContent = 'Copy';
817
+ copyCodeButton.appendChild(tooltipText);
818
+
819
+ copyCodeButton.addEventListener('click', () => {
820
  navigator.clipboard.writeText(code.innerText).then(() => {
821
+ const icon = copyCodeButton.querySelector('i');
822
+ icon.classList.remove('fa-regular', 'fa-copy');
823
+ icon.classList.add('fa-solid', 'fa-check');
824
+ tooltipText.textContent = 'Copied!';
825
  setTimeout(() => {
826
+ icon.classList.remove('fa-solid', 'fa-check');
827
+ icon.classList.add('fa-regular', 'fa-copy');
828
+ tooltipText.textContent = 'Copy';
829
  }, 2000);
830
  }).catch(err => {
831
+ console.error('Failed to copy code:', err);
832
+ tooltipText.textContent = 'Error';
833
+ setTimeout(() => { tooltipText.textContent = 'Copy'; }, 2000);
834
  });
835
  });
836
+ pre.appendChild(copyCodeButton);
837
  });
838
 
839
+ // Wrap tables in a container for horizontal scrolling
840
+ messageWrapper.querySelectorAll('.prose table').forEach(table => {
841
+ if (!table.closest('.table-wrapper')) {
842
+ const wrapper = document.createElement('div');
843
+ wrapper.className = 'table-wrapper';
844
+ table.parentNode.insertBefore(wrapper, table);
845
+ wrapper.appendChild(table);
846
+ }
847
+ });
 
 
848
 
849
+
850
+ if (animate) {
851
+ scrollToBottom(); // Smooth scroll for new messages
852
+ }
853
+
854
+ // Keep reference to assistant message div for potential streaming
855
+ if(role === 'assistant') {
856
+ currentAssistantMessageDiv = messageWrapper.querySelector('.prose');
857
+ } else {
858
+ currentAssistantMessageDiv = null;
859
+ }
 
 
 
 
 
 
 
 
 
860
  }
861
 
862
+ // --- Advanced Cooldown Management ---
863
+ function updateAdvancedCooldownTimer() {
864
+ const now = Date.now();
865
+ if (advancedToggleCooldownEndTime <= now) {
866
+ clearInterval(advancedCooldownIntervalId);
867
+ advancedCooldownIntervalId = null;
868
+ advancedCooldownTimerSpan.classList.add('hidden');
869
+ advancedToggle.disabled = false;
870
+ // Re-enable the label cursor style
871
+ advancedToggle.closest('label').classList.remove('opacity-50', 'cursor-not-allowed');
872
+ } else {
873
+ const remainingSeconds = Math.ceil((advancedToggleCooldownEndTime - now) / 1000);
874
+ advancedCooldownTimerSpan.textContent = `(${remainingSeconds}s)`;
875
+ advancedCooldownTimerSpan.classList.remove('hidden');
876
+ advancedToggle.disabled = true; // Keep disabled during cooldown
877
+ advancedToggle.closest('label').classList.add('opacity-50', 'cursor-not-allowed');
878
+ }
879
+ }
880
+
881
+ function startAdvancedCooldownTimer() {
882
+ advancedToggle.disabled = true;
883
+ advancedToggle.checked = false; // Uncheck after use
884
+ advancedToggle.closest('label').classList.add('opacity-50', 'cursor-not-allowed');
885
+ advancedToggleCooldownEndTime = Date.now() + COOLDOWN_DURATION;
886
+ updateAdvancedCooldownTimer(); // Update immediately
887
+ if (!advancedCooldownIntervalId) {
888
+ advancedCooldownIntervalId = setInterval(updateAdvancedCooldownTimer, 1000);
889
+ }
890
+ }
891
+
892
+
893
+ // --- Load Chat History ---
894
  async function loadChatHistory() {
895
+ historyLoadingIndicator.classList.remove('hidden');
896
+ chatMessages.innerHTML = ''; // Clear existing messages (if any)
897
+ chatMessages.appendChild(historyLoadingIndicator); // Add loader to empty container
898
+ chatMessages.appendChild(loadingIndicator); // Keep AI loader ready
899
+
900
  try {
901
  const response = await fetch(API_HISTORY_ENDPOINT);
902
  if (!response.ok) {
903
+ let errorMsg = `Server Error (${response.status})`;
904
+ try { const errData = await response.json(); errorMsg = errData.error || errorMsg; } catch (e) {}
 
 
 
905
  throw new Error(errorMsg);
906
  }
907
  const data = await response.json();
908
+
 
 
909
  if (data.success && Array.isArray(data.history)) {
910
  if (data.history.length === 0) {
911
+ addMessageToChat('assistant', "Bonjour ! Je suis Mariam Comment puis-je vous aider aujourd'hui ?", true, false);
912
  } else {
913
  data.history.forEach(message => {
914
+ // Assuming assistant content is already formatted HTML from backend
915
+ addMessageToChat(message.role, message.text, message.role === 'assistant', false);
916
  });
917
  }
918
+ // Scroll without animation after initial load
919
+ scrollToBottom('auto');
920
  } else {
921
+ throw new Error(data.error || "Invalid history response format.");
922
  }
923
  } catch (error) {
924
+ console.error("Error loading history:", error);
925
+ displayError(`Impossible de charger l'historique : ${error.message}`);
926
+ // Add fallback message if chat is empty after load attempt
927
+ if (chatMessages.querySelectorAll('.message-animate').length === 0) {
928
+ addMessageToChat('assistant', "Bonjour ! Je n'ai pas pu charger notre conversation précédente. Comment puis-je vous aider ?", true, false);
929
  }
930
  } finally {
931
+ historyLoadingIndicator.classList.add('hidden'); // Hide history loader
932
+ promptInput.focus(); // Focus the input
933
+ adjustTextareaHeight(); // Adjust height in case of saved text
934
  }
935
  }
936
 
937
+ // --- File Management ---
938
+ function clearFileInput(triggerAdjust = true) {
939
  fileUpload.value = '';
940
  fileChip.classList.add('hidden');
941
  fileNameSpan.textContent = '';
942
  fileNameSpan.title = '';
943
+ previewArea.innerHTML = '';
 
944
  previewArea.classList.add('hidden');
945
+ if (triggerAdjust) adjustTextareaHeight();
946
  }
947
+
948
  fileUpload.addEventListener('change', () => {
949
  if (fileUpload.files.length > 0) {
950
  const file = fileUpload.files[0];
951
  const name = file.name;
952
+ const type = file.type;
953
+ const size = file.size;
954
+
955
+ // Client-side validation (size) - Must be validated server-side too!
956
+ const maxSize = 10 * 1024 * 1024; // 10 MB
957
+ if (size > maxSize) {
958
+ displayError(`Le fichier "${escapeHtml(name)}" est trop volumineux (${formatFileSize(size)}). Maximum : ${formatFileSize(maxSize)}.`);
959
+ clearFileInput(false);
960
+ return;
961
+ }
962
+ // Optional: more rigorous type validation
963
+
964
  fileNameSpan.textContent = name;
965
  fileNameSpan.title = name;
966
  fileChip.classList.remove('hidden');
967
+ previewArea.innerHTML = '';
968
+
969
+ const previewWrapper = document.createElement('div');
970
+ previewWrapper.className = 'file-preview-wrapper animate-fade-in';
971
+
972
+ if (type.startsWith('image/')) {
973
  const reader = new FileReader();
974
  reader.onload = (e) => {
975
+ previewWrapper.innerHTML = `
976
+ <img src="${e.target.result}" alt="Preview: ${escapeHtml(name)}">
977
+ <div class="file-info-overlay">
978
+ <span>${escapeHtml(name)}</span>
979
+ <span>${formatFileSize(size)}</span>
980
+ </div>`;
981
+ previewArea.appendChild(previewWrapper);
 
 
 
982
  previewArea.classList.remove('hidden');
983
+ adjustTextareaHeight();
984
  };
985
+ reader.onerror = () => {
986
+ displayError(`Error reading image file "${escapeHtml(name)}".`);
987
+ clearFileInput();
988
+ };
989
  reader.readAsDataURL(file);
990
  } else {
991
+ // Generic preview for other file types
992
+ previewWrapper.innerHTML = `
993
+ <div class="flex items-center p-3 bg-secondary-50 dark:bg-secondary-800">
994
+ <i class="fa-solid ${getFileIcon(type)} text-4xl text-secondary-400 dark:text-secondary-500 mr-3"></i>
995
+ <div class="text-xs text-secondary-700 dark:text-secondary-300 overflow-hidden">
996
+ <p class="font-medium truncate">${escapeHtml(name)}</p>
997
+ <p class="opacity-80">${formatFileSize(size)}</p>
998
+ <p class="opacity-60 truncate">${type || 'Unknown Type'}</p>
999
  </div>
1000
  </div>`;
1001
+ previewArea.appendChild(previewWrapper);
1002
  previewArea.classList.remove('hidden');
1003
+ adjustTextareaHeight();
1004
  }
1005
  } else {
1006
  clearFileInput();
1007
  }
1008
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1009
 
1010
+ clearFileButton.addEventListener('click', (e) => {
1011
+ e.preventDefault();
1012
+ clearFileInput();
1013
+ promptInput.focus();
1014
  });
1015
+
1016
+
1017
+ // --- Input & Form Submission ---
1018
+ promptInput.addEventListener('input', adjustTextareaHeight);
1019
+ promptInput.addEventListener('paste', () => setTimeout(adjustTextareaHeight, 0)); // Adjust after paste content is in
1020
+
1021
+ // Handle Enter / Shift+Enter keydown
1022
  promptInput.addEventListener('keydown', (e) => {
1023
+ if (isComposing) return;
1024
+
1025
+ if (e.key === 'Enter') {
1026
+ if (!e.shiftKey) {
1027
+ e.preventDefault(); // Prevent default newline
1028
+ // Submit if there's text or a file, and button is not disabled
1029
+ if (!sendButton.disabled && (promptInput.value.trim() || fileUpload.files.length > 0)) {
1030
+ chatForm.dispatchEvent(new Event('submit', { cancelable: true }));
1031
+ }
1032
+ }
1033
+ // If Shift+Enter, allow default newline and adjust height
1034
+ else {
1035
+ setTimeout(adjustTextareaHeight, 0);
1036
+ }
1037
+ }
 
 
 
 
 
 
 
 
 
 
1038
  });
 
1039
 
1040
+ // Handle IME composition (for languages like Chinese, Japanese, Korean)
1041
+ promptInput.addEventListener('compositionstart', () => { isComposing = true; });
1042
+ promptInput.addEventListener('compositionend', () => {
1043
+ isComposing = false;
1044
+ setTimeout(adjustTextareaHeight, 0); // Adjust after composition is finalized
1045
+ });
1046
+
1047
+ // Main Form Submission
1048
  chatForm.addEventListener('submit', async (e) => {
1049
  e.preventDefault();
1050
+ const promptText = promptInput.value.trim();
1051
  const file = fileUpload.files[0];
1052
  const useWebSearch = webSearchToggle.checked;
1053
  const useAdvanced = advancedToggle.checked;
1054
+
1055
+ if (sendButton.disabled || (!promptText && !file)) {
1056
  promptInput.focus();
1057
  return;
1058
  }
1059
+
1060
+ hideError(); // Hide previous errors
1061
+
1062
+ // Check Advanced cooldown
1063
  if (useAdvanced) {
1064
  const now = Date.now();
1065
  if (advancedToggleCooldownEndTime > 0 && now < advancedToggleCooldownEndTime) {
1066
  const remainingSeconds = Math.ceil((advancedToggleCooldownEndTime - now) / 1000);
1067
+ displayError(`Le mode avancé est en récupération. Disponible dans ${remainingSeconds} seconde(s).`);
1068
  return;
1069
  }
1070
  }
1071
+
1072
+ // Display user message
1073
+ let userMessageDisplayed = promptText;
1074
  if (file && file.name) {
1075
+ const fileTag = `[Fichier: ${escapeHtml(file.name)}]`;
1076
+ userMessageDisplayed = promptText ? `${promptText}\n${fileTag}` : fileTag;
1077
  }
1078
+ addMessageToChat('user', userMessageDisplayed, false);
1079
+
1080
+ // Prepare form data
1081
  const formData = new FormData();
1082
+ formData.append('prompt', promptText);
1083
  formData.append('web_search', useWebSearch);
1084
  formData.append('advanced_reasoning', useAdvanced);
1085
  if (file) {
1086
  formData.append('file', file);
1087
  }
1088
+
1089
+ // Reset UI
1090
  promptInput.value = '';
1091
+ promptInput.style.height = 'auto';
1092
+ adjustTextareaHeight();
1093
  clearFileInput();
1094
  if (useAdvanced) {
1095
+ startAdvancedCooldownTimer(); // Start cooldown
 
1096
  }
1097
+ // Optionally uncheck web search
1098
+ // webSearchToggle.checked = false;
1099
+
1100
+ showLoading(true); // Show loading indicator
1101
+
1102
  try {
1103
  const response = await fetch(API_CHAT_ENDPOINT, { method: 'POST', body: formData });
1104
+
1105
  if (!response.ok) {
1106
+ // Attempt to read error from response body
1107
+ let errorData = { error: `Server Error: ${response.status} ${response.statusText}`};
1108
+ try {
1109
+ errorData = await response.json();
1110
+ } catch (jsonError) {
1111
+ console.error("Failed to parse JSON error:", jsonError);
1112
+ }
1113
+ throw new Error(errorData.error || `Server Error: ${response.status}`);
1114
  }
1115
+
1116
+ const data = await response.json();
1117
+
1118
  if (data.success && data.message) {
1119
+ // Assuming data.message is HTML formatted from backend
1120
+ addMessageToChat('assistant', data.message, true);
1121
  } else {
1122
+ throw new Error(data.error || "Invalid or empty response received from server.");
1123
  }
1124
  } catch (error) {
1125
+ console.error("Chat API Error:", error);
1126
+ // Display error within an assistant message bubble
1127
+ addMessageToChat('assistant', `<p class="text-red-600 dark:text-red-400 font-medium">Désolé, une erreur est survenue :</p><p class="text-sm mt-1">${escapeHtml(error.message)}</p>`, true);
1128
+ // Optionally display the banner for critical errors
1129
+ // displayError(`Communication error: ${error.message}`);
1130
  } finally {
1131
+ showLoading(false); // Hide loading indicator
1132
+ promptInput.focus(); // Return focus to input
1133
  }
1134
  });
1135
 
1136
+ // --- Clear Conversation ---
1137
  clearForm.addEventListener('submit', async (e) => {
1138
  e.preventDefault();
1139
+
1140
+ // Show confirmation modal
1141
  const confirmDialog = document.createElement('div');
1142
+ confirmDialog.className = 'fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4 animate-fade-in';
1143
+ confirmDialog.setAttribute('role', 'dialog');
1144
+ confirmDialog.setAttribute('aria-modal', 'true');
1145
+ confirmDialog.setAttribute('aria-labelledby', 'confirm-dialog-title');
1146
  confirmDialog.innerHTML = `
1147
+ <div class="bg-white dark:bg-secondary-800 p-6 rounded-lg shadow-xl max-w-sm w-full transform transition-transform duration-300 scale-95 opacity-0" data-dialog-content>
1148
+ <h3 id="confirm-dialog-title" class="text-lg font-semibold mb-3 text-secondary-900 dark:text-secondary-100">Vider la conversation ?</h3>
1149
+ <p class="text-sm text-secondary-600 dark:text-secondary-300 mb-6">Toute l'historique de cette session sera définitivement effacé.</p>
1150
  <div class="flex justify-end space-x-3">
1151
+ <button type="button" data-cancel class="px-4 py-2 text-sm font-medium text-secondary-700 dark:text-secondary-300 bg-secondary-100 dark:bg-secondary-700 rounded-md hover:bg-secondary-200 dark:hover:bg-secondary-600 transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-secondary-400">
1152
  Annuler
1153
  </button>
1154
+ <button type="button" data-confirm class="px-4 py-2 text-sm font-medium text-white bg-red-600 rounded-md hover:bg-red-700 transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-red-500">
1155
  Effacer
1156
  </button>
1157
  </div>
1158
  </div>
1159
  `;
1160
+
1161
+ let isClosing = false;
1162
+ const dialogContent = confirmDialog.querySelector('[data-dialog-content]');
1163
+
1164
+ const closeModal = (focusReturnElement = null) => {
1165
+ if (isClosing) return;
1166
+ isClosing = true;
1167
+ dialogContent.classList.remove('scale-100', 'opacity-100');
1168
+ dialogContent.classList.add('scale-95', 'opacity-0');
1169
+ confirmDialog.classList.add('opacity-0');
1170
+ setTimeout(() => {
1171
+ if (document.body.contains(confirmDialog)) {
1172
+ document.body.removeChild(confirmDialog);
1173
+ document.body.style.overflow = ''; // Restore body scroll
1174
+ if (focusReturnElement) focusReturnElement.focus(); // Return focus
1175
+ }
1176
+ }, 300);
1177
  };
1178
+
1179
+ const clearButton = e.target.querySelector('button[type="submit"]'); // Get the button to update its state
1180
+ confirmDialog.querySelector('[data-cancel]').addEventListener('click', () => closeModal(clearButton));
1181
+ confirmDialog.querySelector('[data-confirm]').addEventListener('click', async () => {
1182
+
1183
+ closeModal(); // Close modal immediately
1184
+
1185
  const originalButtonContent = clearButton.innerHTML;
1186
  clearButton.disabled = true;
1187
+ clearButton.innerHTML = `
1188
+ <i class="fa-solid fa-spinner fa-spin mr-0 sm:mr-1.5 text-sm"></i>
1189
+ <span class="header-action-text">Effacement...</span>`;
1190
+
1191
  try {
1192
+ const response = await fetch(CLEAR_ENDPOINT, {
1193
  method: 'POST',
1194
+ headers: { 'X-Requested-With': 'XMLHttpRequest' }
 
 
1195
  });
1196
  const data = await response.json();
1197
+
1198
  if (response.ok && data.success) {
1199
+ // Clear chat UI
1200
+ const messagesToRemove = chatMessages.querySelectorAll('.message-animate, .assistant-message-wrapper');
1201
  messagesToRemove.forEach(el => el.remove());
1202
+ // Add initial welcome message
1203
+ addMessageToChat('assistant', "Conversation effacée. Prêt pour une nouvelle discussion !", true);
1204
+ hideError();
1205
+ // Reset cooldown if needed (depends on backend logic)
1206
+ // advancedToggleCooldownEndTime = 0;
1207
+ // updateAdvancedCooldownTimer();
1208
  } else {
1209
+ throw new Error(data.error || "Unable to clear conversation.");
1210
  }
1211
  } catch (error) {
1212
+ console.error("Clear Chat Error:", error);
1213
+ displayError(`Erreur lors de l'effacement : ${error.message}`);
1214
  } finally {
1215
+ clearButton.innerHTML = originalButtonContent; // Restore button text
1216
  clearButton.disabled = false;
1217
+ promptInput.focus(); // Focus input
1218
  }
1219
  });
1220
+
1221
+ // Handle Escape key to close modal
1222
+ confirmDialog.addEventListener('keydown', (event) => {
1223
+ if (event.key === 'Escape') closeModal(clearButton);
1224
+ });
1225
+ // Handle click outside modal content to close
1226
+ confirmDialog.addEventListener('click', (event) => {
1227
+ if (event.target === confirmDialog) closeModal(clearButton);
1228
+ });
1229
+
1230
  document.body.appendChild(confirmDialog);
1231
+ document.body.style.overflow = 'hidden'; // Prevent body scroll
1232
+ // Animate modal appearance
1233
+ requestAnimationFrame(() => {
1234
+ confirmDialog.classList.remove('opacity-0');
1235
+ dialogContent.classList.add('scale-100', 'opacity-100');
1236
+ dialogContent.classList.remove('scale-95', 'opacity-0');
1237
+ });
1238
+ confirmDialog.querySelector('[data-cancel]').focus(); // Focus the cancel button first
1239
+
1240
  });
1241
 
1242
+
1243
+ // --- Initialization ---
1244
+ initializeTheme();
1245
+ themeToggleBtn.addEventListener('click', toggleTheme);
1246
+ dismissErrorBtn.addEventListener('click', hideError);
1247
+ loadChatHistory(); // Load history on startup
1248
+ adjustTextareaHeight(); // Adjust initial input height
1249
+ updateAdvancedCooldownTimer(); // Check advanced cooldown state on load
1250
+
1251
+ // Listen for system color scheme changes
1252
+ window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
1253
+ // Only apply system preference if user hasn't manually set a theme
1254
+ if (!localStorage.getItem('theme')) {
1255
+ applyTheme(e.matches ? 'dark' : 'light');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1256
  }
1257
+ });
1258
+
1259
+ // Adjust textarea height and maybe scroll on window resize
1260
+ let resizeTimeout;
1261
+ window.addEventListener('resize', () => {
1262
+ clearTimeout(resizeTimeout);
1263
+ resizeTimeout = setTimeout(() => {
1264
+ adjustTextareaHeight();
1265
+ // Optional: re-scroll to bottom if user was already there
1266
+ // const isAtBottom = chatMessages.scrollTop + chatMessages.clientHeight >= chatMessages.scrollHeight - 50;
1267
+ // if (isAtBottom) {
1268
+ // scrollToBottom('auto');
1269
+ // }
1270
+ }, 100); // Debounce resize events
1271
+ });
1272
+
1273
+ }); // End DOMContentLoaded
1274
  </script>
1275
  </body>
1276
+ </html>