-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1202 lines (1053 loc) · 73.6 KB
/
script.js
File metadata and controls
1202 lines (1053 loc) · 73.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
document.addEventListener('DOMContentLoaded', () => {
// console.log("--- DOMContentLoaded FIRED ---");
const translations = {
en: {
search: "Search news...",
filter: { press: "Press", social: "Social Media", agencies: "Agencies", think: "Think Tanks", video: "Video", image: "Image", selectAll: "Select All", clear: "Clear" },
time: { title: "Period Selector", from: "From", to: "To", hour: "Hour", day: "Day", month: "Month", year: "Year", reset: "Reset", apply: "Apply" },
view: { hour: "Hour", day: "Day", month: "Month", year: "Year" },
export: { pdf: { title: "PDF Document", desc: "Complete report with graphics" }, csv: { title: "CSV Spreadsheet", desc: "Data in tabular format" }, jpg: { title: "JPG Image", desc: "Visual snapshot" } },
history: { title: "History", empty: "No history yet. Your searches will appear here." },
verdict: { credible: "Credible", mixed: "Mixed", suspect: "Suspect" },
stats: "<span class='subject-highlight'>[{subject}]</span> | Total: {count} articles | Average score: {score}% | Verdict: {verdict}"
},
fr: {
search: "Rechercher une actualité...",
filter: { press: "Presse", social: "Réseaux Sociaux", agencies: "Agences", think: "Think Tanks", video: "Vidéo", image: "Image", selectAll: "Tout sélectionner", clear: "Effacer" },
time: { title: "Sélecteur de période", from: "De", to: "À", hour: "Heure", day: "Jour", month: "Mois", year: "Année", reset: "Réinitialiser", apply: "Appliquer" },
view: { hour: "Heure", day: "Jour", month: "Mois", year: "Année" },
export: { pdf: { title: "Document PDF", desc: "Rapport complet avec graphiques" }, csv: { title: "Feuille CSV", desc: "Données en format tabulaire" }, jpg: { title: "Image JPG", desc: "Capture visuelle" } },
history: { title: "Historique", empty: "Aucun historique pour le moment. Vos recherches apparaîtront ici." },
verdict: { credible: "Crédible", mixed: "Mitigé", suspect: "Suspect" },
stats: "<span class='subject-highlight'>[{subject}]</span> | Total: {count} articles | Score moyen: {score}% | Verdict: {verdict}"
},
ar: {
search: "البحث عن الأخبار...",
filter: { press: "الصحافة", social: "وسائل التواصل الاجتماعي", agencies: "الوكالات", think: "مراكز الأبحاث", video: "فيديو", image: "صورة", selectAll: "تحديد الكل", clear: "مسح" },
time: { title: "محدد الفترة", from: "من", to: "إلى", hour: "ساعة", day: "يوم", month: "شهر", year: "سنة", reset: "إعادة تعيين", apply: "تطبيق" },
view: { hour: "ساعة", day: "يوم", month: "شهر", year: "سنة" },
export: { pdf: { title: "مستند PDF", desc: "تقرير كامل مع رسومات" }, csv: { title: "جدول CSV", desc: "بيانات بتنسيق جدولي" }, jpg: { title: "صورة JPG", desc: "لقطة مرئية" } },
history: { title: "السجل", empty: "لا يوجد سجل حتى الآن. ستظهر عمليات البحث الخاصة بك هنا." },
verdict: { credible: "موثوق", mixed: "مختلط", suspect: "مشبوه" },
stats: "<span class='subject-highlight'>[{subject}]</span> | المجموع: {count} مقالات | متوسط النقاط: {score}% | الحكم: {verdict}"
},
es: {
search: "Buscar noticias...",
filter: { press: "Prensa", social: "Redes Sociales", agencies: "Agencias", think: "Think Tanks", video: "Video", image: "Imagen", selectAll: "Seleccionar todo", clear: "Limpiar" },
time: { title: "Selector de período", from: "Desde", to: "Hasta", hour: "Hora", day: "Día", month: "Mes", year: "Año", reset: "Restablecer", apply: "Aplicar" },
view: { hour: "Hora", day: "Día", month: "Mes", year: "Año" },
export: { pdf: { title: "Documento PDF", desc: "Informe completo con gráficos" }, csv: { title: "Hoja CSV", desc: "Datos en formato tabular" }, jpg: { title: "Imagen JPG", desc: "Captura visual" } },
history: { title: "Historial", empty: "No hay historial todavía. Tus búsquedas aparecerán aquí." },
verdict: { credible: "Creíble", mixed: "Mixto", suspect: "Sospechoso" },
stats: "<span class='subject-highlight'>[{subject}]</span> | Total: {count} artículos | Puntuación media: {score}% | Veredicto: {verdict}"
},
de: {
search: "Nachrichten suchen...",
filter: { press: "Presse", social: "Soziale Medien", agencies: "Agenturen", think: "Denkfabriken", video: "Video", image: "Bild", selectAll: "Alle auswählen", clear: "Löschen" },
time: { title: "Zeitraumauswahl", from: "Von", to: "Bis", hour: "Stunde", day: "Tag", month: "Monat", year: "Jahr", reset: "Zurücksetzen", apply: "Anwenden" },
view: { hour: "Stunde", day: "Tag", month: "Monat", year: "Jahr" },
export: { pdf: { title: "PDF-Dokument", desc: "Vollständiger Bericht mit Grafiken" }, csv: { title: "CSV-Tabelle", desc: "Daten im Tabellenformat" }, jpg: { title: "JPG-Bild", desc: "Visuelle Momentaufnahme" } },
history: { title: "Verlauf", empty: "Noch kein Verlauf. Ihre Suchen werden hier angezeigt." },
verdict: { credible: "Glaubwürdig", mixed: "Gemischt", suspect: "Verdächtig" },
stats: "<span class='subject-highlight'>[{subject}]</span> | Gesamt: {count} Artikel | Durchschnittliche Punktzahl: {score}% | Urteil: {verdict}"
},
zh: {
search: "搜索新闻...",
filter: { press: "媒体", social: "社交媒体", agencies: "机构", think: "智囊团", video: "视频", image: "图片", selectAll: "全选", clear: "清除" },
time: { title: "选择时段", from: "从", to: "到", hour: "时", day: "天", month: "月", year: "年", reset: "重置", apply: "应用" },
view: { hour: "小时", day: "天", month: "月", year: "年" },
export: { pdf: { title: "PDF 文档", desc: "带图表的完整报告" }, csv: { title: "CSV 表格", desc: "表格格式数据" }, jpg: { title: "JPG 图片", desc: "视觉快照" } },
history: { title: "历史记录", empty: "暂无历史记录。您的搜索将显示在此处。" },
verdict: { credible: "可信", mixed: "混合", suspect: "可疑" },
stats: "<span class='subject-highlight'>[{subject}]</span> | 总计: {count} 篇文章 | 平均分: {score}% | 结论: {verdict}"
},
ja: {
search: "ニュースを検索...",
filter: { press: "プレス", social: "ソーシャルメディア", agencies: "代理店", think: "シンクタンク", video: "動画", image: "画像", selectAll: "すべて選択", clear: "クリア" },
time: { title: "期間セレクター", from: "から", to: "まで", hour: "時", day: "日", month: "月", year: "年", reset: "リセット", apply: "適用" },
view: { hour: "時間", day: "日", month: "月", year: "年" },
export: { pdf: { title: "PDFドキュメント", desc: "グラフィック付きの完全なレポート" }, csv: { title: "CSVスプレッドシート", desc: "表形式のデータ" }, jpg: { title: "JPG画像", desc: "ビジュアルスナップショット" } },
history: { title: "履歴", empty: "履歴はまだありません。検索内容がここに表示されます。" },
verdict: { credible: "信頼できる", mixed: "混合", suspect: "疑わしい" },
stats: "<span class='subject-highlight'>[{subject}]</span> | 合計: {count} 記事 | 平均スコア: {score}% | 判定: {verdict}"
},
ru: {
search: "Поиск новостей...",
filter: { press: "Пресса", social: "Социальные сети", agencies: "Агентства", think: "Аналитические центры", video: "Видео", image: "Изображение", selectAll: "Выбрать все", clear: "Очистить" },
time: { title: "Выбор периода", from: "От", to: "До", hour: "Час", day: "День", month: "Месяц", year: "Год", reset: "Сброс", apply: "Применить" },
view: { hour: "Час", day: "День", month: "Месяц", year: "Год" },
export: { pdf: { title: "Документ PDF", desc: "Полный отчет с графикой" }, csv: { title: "Таблица CSV", desc: "Данные в табличном формате" }, jpg: { title: "Изображение JPG", desc: "Визуальный снимок" } },
history: { title: "История", empty: "Истории пока нет. Ваши поиски будут отображаться здесь." },
verdict: { credible: "Достоверно", mixed: "Смешанно", suspect: "Подозрительно" },
stats: "<span class='subject-highlight'>[{subject}]</span> | Всего: {count} статей | Средний балл: {score}% | Вердикт: {verdict}"
},
hi: {
search: " समाचार खोजें...",
filter: { press: "प्रेस", social: "ソーシャルメディア", agencies: "एजेंसियां", think: "थिंक टैंक", video: "वीडियो", image: "छवि", selectAll: "सभी चुनें", clear: "саफ़ करें" },
time: { title: "अवधि चुनें", from: "से", to: "तक", hour: "घंटा", day: "दिन", month: "महीना", year: "वर्ष", reset: "रीसेट", apply: "लागू करें" },
view: { hour: "घंटा", day: "दिन", month: "Mहीना", year: "वर्ष" },
export: { pdf: { title: "PDF दस्तावेज़", desc: "ग्राफिक्स के साथ पूरी रिपोर्ट" }, csv: { title: "CSV स्प्रेडशीट", desc: "ตาราง प्रारूप में डेटा" }, jpg: { title: "JPG छवि", desc: "दृश्य स्नैपショット" } },
history: { title: "इतिहास", empty: "अभी तक કોઈ इतिहास नहीं है। आपकी खोजें यहां दिखाई देंगी।" },
verdict: { credible: "विश्वसनीय", mixed: "मिश्रित", suspect: "संदिग्ध" },
stats: "<span class='subject-highlight'>[{subject}]</span> | કુલ: {count} लेख | औसत स्कोर: {score}% | निर्णय: {verdict}"
}
};
let currentLang = 'en';
let historyData = [];
let currentSubject = 'Latest News Analysis';
const CONFIG = { minZoom: 0.3, maxZoom: 2, zoomStep: 0.1 };
let currentZoom = 1;
let currentView = 'day';
let isPanning = false;
let startX, startY, scrollLeft, scrollTop;
let activeFilters = new Set(['news', 'social', 'agency', 'think', 'video', 'image']);
let currentPeriod = {
from: { year: 2025, month: 1, day: 1, hour: 8 },
to: { year: 2025, month: 12, day: 31, hour: 18 }
};
let lastRawResults = [];
let currentDisplayedData = [];
// [MODIFIED] Using 'aiSession' based on new 'LanguageModel' API
let aiSession; // LanguageModel API Session Instance
// Map language codes to full names for the prompt
const langNameMap = {
fr: 'French', ar: 'Arabic', es: 'Spanish', de: 'German',
zh: 'Chinese', ja: 'Japanese', ru: 'Russian', hi: 'Hindi'
};
// DOM References
let canvasContainer, timelineWrapper, searchInput, statsText, scoreText, verdictText, credCircle, filterBtn, filterMenu, selectAllBtn, clearAllBtn, themeToggle, calendarBtn, timeFilterPanel, periodDisplay, applyPeriodBtn, resetPeriodBtn, filterBadge, historyBtn, historyPanel, historyClose, historyContent, languageBtn, languageMenu, exportBtn, exportPanel, exportPdf, exportCsv, exportJpg;
try {
canvasContainer = document.getElementById('canvasContainer');
timelineWrapper = document.getElementById('timelineWrapper');
searchInput = document.getElementById('searchInput');
statsText = document.getElementById('statsText');
scoreText = document.getElementById('scoreText');
verdictText = document.getElementById('verdictText');
credCircle = document.getElementById('credCircle');
filterBtn = document.getElementById('filterBtn');
filterMenu = document.getElementById('filterMenu');
selectAllBtn = document.getElementById('selectAllBtn');
clearAllBtn = document.getElementById('clearAllBtn');
themeToggle = document.getElementById('themeToggle');
calendarBtn = document.getElementById('calendarBtn');
timeFilterPanel = document.getElementById('timeFilterPanel');
periodDisplay = document.getElementById('periodDisplay');
applyPeriodBtn = document.getElementById('applyPeriodBtn');
resetPeriodBtn = document.getElementById('resetPeriodBtn');
filterBadge = document.getElementById('filterBadge');
historyBtn = document.getElementById('historyBtn');
historyPanel = document.getElementById('historyPanel');
historyClose = document.getElementById('historyClose');
historyContent = document.getElementById('historyContent');
languageBtn = document.getElementById('languageBtn');
languageMenu = document.getElementById('languageMenu');
exportBtn = document.getElementById('exportBtn');
exportPanel = document.getElementById('exportPanel');
exportPdf = document.getElementById('exportPdf');
exportCsv = document.getElementById('exportCsv');
exportJpg = document.getElementById('exportJpg');
if (!searchInput || !timelineWrapper || !canvasContainer || !statsText || !scoreText || !credCircle || !filterBtn || !filterMenu || !selectAllBtn || !clearAllBtn || !themeToggle || !calendarBtn || !timeFilterPanel || !periodDisplay || !applyPeriodBtn || !resetPeriodBtn || !filterBadge || !historyBtn || !historyPanel || !historyClose || !historyContent || !languageBtn || !languageMenu || !exportBtn || !exportPanel || !exportPdf || !exportCsv || !exportJpg) {
console.warn("[Debug] One or more essential DOM elements not found! Check IDs.");
}
} catch (domError) {
console.error("[Debug] CRITICAL ERROR retrieving a DOM element:", domError);
alert("Critical Error: Cannot find an essential page element.");
return;
}
const mediaIcons = {
news: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="20px" height="20px"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M21 5H3c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm-1 12H4V7h16v10zm-9-8H7v6h5v-6zm2 4h5v2h-5v-2zm0-4h5v2h-5V9z"/></svg>`,
social: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="20px" height="20px"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z"/></svg>`,
video: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="20px" height="20px"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4z"/></svg>`,
image: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="20px" height="20px"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z"/></svg>`,
agency: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="20px" height="20px"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M12 7V3H2v18h20V7H12zM6 19H4v-2h2v2zm0-4H4v-2h2v2zm0-4H4V9h2v2zm0-4H4V5h2v2zm4 12H8v-2h2v2zm0-4H8v-2h2v2zm0-4H8V9h2v2zm0-4H8V5h2v2zm10 12h-8v-2h2v-2h-2v-2h2v-2h-2V9h8v10zm-2-8h-2v2h2v-2zm0 4h-2v2h2v-2z"/></svg>`,
think: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="20px" height="20px"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-1-13h2v2h-2zm0 4h2v6h-2z"/></svg>`
};
// ========================================================================
// AI INITIALIZATION (MODIFIED FOR 'LanguageModel')
// ========================================================================
async function initializeBuiltInAI() {
// [MODIFIED] Check for 'LanguageModel' instead of 'Prompt'
if (!('LanguageModel' in self)) {
console.error("The LanguageModel API is not supported by this browser.");
statsText.textContent = "Error: AI API not supported. Check Chrome Flags or hardware requirements (16GB+ RAM).";
aiSession = null; // Ensure aiSession is null
return;
}
try {
statsText.textContent = "Initializing AI model...";
// [MODIFIED] Use LanguageModel.availability()
const availability = await LanguageModel.availability();
if (availability === 'available') {
// [MODIFIED] Use LanguageModel.create()
aiSession = await LanguageModel.create();
console.log("AI Model (LanguageModel) initialized.");
statsText.textContent = "AI ready. Start a search.";
} else if (availability === 'downloadable') {
console.log("AI (LanguageModel) not downloaded. Starting download...");
statsText.textContent = "Downloading AI model (Gemini Nano)... 0%";
// [MODIFIED] Use LanguageModel.create()
aiSession = await LanguageModel.create({
monitor: (m) => {
m.addEventListener("downloadprogress", e => {
const percent = Math.round(e.loaded * 100);
statsText.textContent = `Downloading AI model... ${percent}%`;
});
m.addEventListener("downloadcomplete", () => {
console.log("AI Model (LanguageModel) download complete.");
statsText.textContent = "AI model ready.";
});
m.addEventListener("downloaderror", (e) => {
console.error("Error during AI model download:", e);
statsText.textContent = "AI model download error.";
});
}
});
} else {
console.error("The LanguageModel API is not available.", availability);
let reason = "Check Chrome version, Chrome Flags (if local), or hardware requirements (16GB+ RAM).";
try {
if (navigator.hardwareConcurrency && navigator.hardwareConcurrency < 4) reason += " Less than 4 CPU cores detected.";
if (navigator.deviceMemory && navigator.deviceMemory < 16) reason += ` Detected RAM: ${navigator.deviceMemory}GB (16GB+ required).`;
} catch(e) {}
statsText.textContent = `Error: AI not available (${availability}). ${reason}`;
aiSession = null;
}
} catch (error) {
console.error("Critical error during AI initialization:", error);
statsText.textContent = `AI Error: ${error.message}`;
aiSession = null;
}
}
// ========================================================================
// LOCAL HISTORY FUNCTIONS
// ========================================================================
function loadHistory() {
try {
const saved = localStorage.getItem('factbeacon_history'); // Updated app name
if (saved) {
historyData = JSON.parse(saved);
}
} catch (error) { console.error('[loadHistory] Loading error:', error); historyData = []; }
}
function saveToHistory(data) {
if (!Array.isArray(data) || data.length === 0) return;
const allScores = data.flatMap(g => g.items.map(i => i.score || 0));
const avgScore = allScores.length > 0 ? Math.round(allScores.reduce((a, b) => a + b, 0) / allScores.length) : 0;
const globalVerdict = lastRawResults.length > 0 ? (lastRawResults[0].verdict || "Mixed") : "Mixed";
const historyEntry = {
id: Date.now(), timestamp: new Date().toISOString(), subject: currentSubject,
data: data, rawResults: lastRawResults, score: avgScore,
count: allScores.length, view: currentView, filters: Array.from(activeFilters),
verdict: globalVerdict
};
historyData.unshift(historyEntry);
if (historyData.length > 50) { historyData = historyData.slice(0, 50); }
try {
localStorage.setItem('factbeacon_history', JSON.stringify(historyData)); // Updated app name
renderHistory();
} catch (error) {
console.error('[saveToHistory] Save error:', error);
if (error.name === 'QuotaExceededError') {
historyData = historyData.slice(0, 20); // Reduce size
try { localStorage.setItem('factbeacon_history', JSON.stringify(historyData)); } catch (e) { console.error('[saveToHistory] Save impossible even after cleanup'); }
}
}
}
function renderHistory() {
if (!historyContent) return;
const lang = translations[currentLang] || translations.en;
if (historyData.length === 0) {
historyContent.innerHTML = `<div class="history-empty"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/></svg><p>${lang.history.empty}</p></div>`;
return;
}
const html = historyData.map(entry => {
const date = new Date(entry.timestamp);
const formattedDate = date.toLocaleString(currentLang, { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
const verdictKey = (entry.verdict || 'mixed').toLowerCase();
const verdict = lang.verdict[verdictKey] || entry.verdict;
const scoreClass = entry.score >= 75 ? 'verdict-credible' : entry.score >= 45 ? 'verdict-mitige' : 'verdict-suspect';
return `<div class="history-item" data-id="${entry.id}"><div class="history-item-header"><div class="history-item-date">${formattedDate}</div><div class="history-item-score ${scoreClass}">${entry.score}%</div></div><div class="history-item-details"><div class="history-item-subject">${entry.subject}</div><div>${entry.count} articles • ${verdict}</div></div></div>`;
}).join('');
historyContent.innerHTML = html;
document.querySelectorAll('.history-item').forEach(item => {
item.addEventListener('click', () => { loadHistoryEntry(parseInt(item.dataset.id)); });
});
}
async function loadHistoryEntry(id) {
const entry = historyData.find(e => e.id === id);
if (!entry) return;
currentSubject = entry.subject;
lastRawResults = entry.rawResults || [];
currentView = entry.view || 'day';
if (entry.filters) {
activeFilters = new Set(entry.filters);
updateFilterBadge();
document.querySelectorAll('.filter-option input[type="checkbox"]').forEach(checkbox => {
checkbox.checked = activeFilters.has(checkbox.value);
});
}
// Appeler la fonction de mise à jour des onglets
setupTimeTabListeners();
await renderTimeline(entry.data); // 'entry.data' is already grouped
historyPanel.classList.remove('active');
}
// ========================================================================
// EXPORT FUNCTIONS
// ========================================================================
function exportToPDF() {
if (currentDisplayedData.length === 0) { alert('No data to export.'); return; }
if (typeof window.jspdf === 'undefined') { alert('PDF library (jsPDF) not loaded.'); return; }
console.log('[exportToPDF] Generating PDF...');
const { jsPDF } = window.jspdf; const doc = new jsPDF();
let yPos = 20; const pageHeight = doc.internal.pageSize.height; const margin = 20;
doc.setFontSize(18); doc.setTextColor(59, 130, 246); doc.text('FactBeacon Analysis Report', margin, yPos); yPos += 10;
doc.setFontSize(14); doc.setTextColor(0, 0, 0); doc.text(`Subject: ${currentSubject}`, margin, yPos); yPos += 10;
doc.setFontSize(10); doc.setTextColor(100, 100, 100); doc.text(`Generated: ${new Date().toLocaleString()}`, margin, yPos); yPos += 15;
const allScores = currentDisplayedData.flatMap(g => g.items.map(i => i.score || 0));
const avgScore = allScores.length > 0 ? Math.round(allScores.reduce((a, b) => a + b, 0) / allScores.length) : 0;
const verdictKey = avgScore >= 75 ? 'credible' : avgScore >= 45 ? 'mixed' : 'suspect';
const lang = translations[currentLang] || translations.en;
const verdict = lang.verdict[verdictKey];
doc.setFontSize(12); doc.setTextColor(0, 0, 0); doc.text(`Total Articles: ${allScores.length}`, margin, yPos); yPos += 7;
doc.text(`Average Score: ${avgScore}%`, margin, yPos); yPos += 7;
doc.text(`Verdict: ${verdict}`, margin, yPos); yPos += 15;
currentDisplayedData.forEach((group) => {
if (yPos > pageHeight - 40) { doc.addPage(); yPos = 20; }
doc.setFontSize(12); doc.setTextColor(59, 130, 246); doc.text(`${group.time}`, margin, yPos); yPos += 8;
group.items.forEach((item, itemIndex) => {
if (yPos > pageHeight - 30) { doc.addPage(); yPos = 20; }
doc.setFontSize(10); doc.setTextColor(0, 0, 0); const title = `${itemIndex + 1}. ${item.title || 'Untitled'}`;
const splitTitle = doc.splitTextToSize(title, 170); doc.text(splitTitle, margin + 5, yPos); yPos += splitTitle.length * 5;
doc.setFontSize(8); doc.setTextColor(100, 100, 100); doc.text(`Score: ${item.score}% | Type: ${item.type}`, margin + 5, yPos); yPos += 5;
const summaryToExport = item.translated_summary || item.summary;
if (summaryToExport) { const splitSummary = doc.splitTextToSize(summaryToExport, 170); doc.text(splitSummary, margin + 5, yPos); yPos += splitSummary.length * 4; }
yPos += 5;
}); yPos += 5;
});
doc.save(`FactBeacon_${currentSubject.replace(/\s+/g, '_')}_${Date.now()}.pdf`);
}
function exportToCSV() {
if (currentDisplayedData.length === 0) { alert('No data to export.'); return; }
const headers = ['Time Period', 'Title', 'URL', 'Type', 'Score', 'Summary', 'Date']; const rows = [];
currentDisplayedData.forEach(group => {
group.items.forEach(item => {
const summaryToExport = item.translated_summary || item.summary;
const row = [ group.time, item.title || 'N/A', item.url || 'N/A', item.type || 'N/A', item.score || 0, (summaryToExport || 'N/A').replace(/"/g, '""'), item.rawDate || 'N/A' ];
rows.push(row);
});
});
const csvContent = [ headers.map(h => `"${h}"`).join(','), ...rows.map(row => row.map(cell => `"${cell}"`).join(',')) ].join('\n');
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement('a'); link.href = URL.createObjectURL(blob);
link.download = `FactBeacon_${currentSubject.replace(/\s+/g, '_')}_${Date.now()}.csv`;
link.click();
}
function exportToJPG() {
if (!timelineWrapper || currentDisplayedData.length === 0) { alert('No data to export.'); return; }
if (typeof html2canvas === 'undefined') { alert('html2canvas library not loaded.'); return; }
const originalZoom = currentZoom; applyZoom(1);
setTimeout(() => {
html2canvas(timelineWrapper, {
backgroundColor: getComputedStyle(document.documentElement).getPropertyValue('--color-bg-dark'),
scale: 2, logging: false
}).then(canvas => {
applyZoom(originalZoom);
canvas.toBlob(blob => {
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = `FactBeacon_${currentSubject.replace(/\s+/g, '_')}_${Date.now()}.jpg`;
link.click();
}, 'image/jpeg', 0.95);
}).catch(error => { console.error('[exportToJPG] Error:', error); applyZoom(originalZoom); alert('Error generating image.'); });
}, 100);
}
// ========================================================================
// RENDER AND INTERFACE FUNCTIONS
// ========================================================================
async function translatePage() {
const langTranslations = translations[currentLang] || translations.en;
if(searchInput) searchInput.placeholder = langTranslations.search;
document.querySelectorAll('[data-i18n]').forEach(el => {
const key = el.getAttribute('data-i18n'); const keys = key.split('.'); let value = langTranslations; let found = true;
try {
for (const k of keys) { if (value && typeof value === 'object' && k in value) { value = value[k]; } else { found = false; break; } }
if (found && typeof value === 'string') { el.textContent = value; }
else {
let fallbackValue = translations.en; let fallbackFound = true;
for (const k of keys) { if (fallbackValue && typeof fallbackValue === 'object' && k in fallbackValue) { fallbackValue = fallbackValue[k]; } else { fallbackFound = false; break; } }
if(fallbackFound && typeof fallbackValue === 'string') { el.textContent = fallbackValue; } else { el.textContent = key; }
}
} catch (e) { console.error(`[translatePage] Error on key "${key}":`, e); el.textContent = key; }
});
renderHistory();
const currentData = regroupTimelineData(lastRawResults, currentView);
await renderTimeline(currentData);
calculateCredibility(currentDisplayedData);
// [CORRECTION BUG LANGUE] Ré-attache les écouteurs des onglets de temps
setupTimeTabListeners();
}
async function renderCard(item) {
let sourceName, domain; let cardHtml = '';
try {
if (typeof item.url === 'string' && item.url.trim() !== '') {
const urlObj = new URL(item.url); domain = urlObj.hostname; sourceName = domain.replace('www.', '');
} else { throw new Error('Invalid or missing URL'); }
} catch (e) { sourceName = "Unknown source"; domain = null; }
const iconSvg = mediaIcons[item.type] || mediaIcons.news;
const logoUrl = domain ? `https://www.google.com/s2/favicons?domain=${domain}&sz=32` : '';
const logoHtml = domain ? `<img src="${logoUrl}" class="source-logo" alt="Logo" width="24" height="24" onerror="this.style.display='none'">` : '<div class="source-logo-placeholder"></div>';
let dateHtml = '';
if (item.dateObject instanceof Date && !isNaN(item.dateObject)) {
try {
const options = { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' };
const formattedDate = item.dateObject.toLocaleString(currentLang, options);
dateHtml = `<div class="card-date">${formattedDate}</div>`;
} catch (e) { dateHtml = item.rawDate ? `<div class="card-date">${item.rawDate}</div>` : ''; }
} else if (item.rawDate) { dateHtml = `<div class="card-date">${item.rawDate}</div>`; }
// --- Translation Logic ---
let displaySummary = item.summary || 'No summary available.';
item.translated_summary = null;
// [MODIFIED] Check for 'aiSession' (the LanguageModel session)
if (currentLang !== 'en' && aiSession) {
try {
const translated = await handleTranslateWithPrompt(item.summary, currentLang);
displaySummary = translated;
item.translated_summary = translated;
} catch (translateError) {
console.warn(`[renderCard] Translation failure (LanguageModel) for ${item.url}:`, translateError);
displaySummary = item.summary || 'Translation error.';
}
}
try {
cardHtml = `
<div class="card" data-url="${item.url || '#'}">
${dateHtml}
<div class="card-header">
<div class="media-icon ${item.type}">${iconSvg}</div>
${logoHtml}
<div class="source-name" title="${item.url || ''}">${sourceName}</div>
<div class="external-link" data-url="${item.url || '#'}" title="Open source">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" style="width:18px;height:18px"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"/></svg>
</div>
</div>
<div class="card-content">${displaySummary}</div>
</div>`;
return cardHtml;
} catch (renderError) { console.error("[renderCard] Error building HTML:", renderError, item); return `<div class="card error-card"><div class="card-content">Internal error (renderCard HTML).</div></div>`; }
}
async function renderTimeline(data) {
if (!timelineWrapper) { console.error("[renderTimeline] Error: timelineWrapper is not defined."); return; }
if (!Array.isArray(data)) { data = []; }
const filteredData = data.map(group => ({
...group,
items: Array.isArray(group.items) ? group.items.filter(item => activeFilters.has(item.type)) : []
})).filter(g => g.items.length > 0);
currentDisplayedData = filteredData;
if (filteredData.length === 0) {
timelineWrapper.innerHTML = `<div style="padding: 40px; text-align: center; color: var(--color-text-muted);">No articles to display. Start a search or check your filters.</div>`;
calculateCredibility(data);
return;
}
const htmlPromises = filteredData.map(async (group, i) => {
let cardsHtml = '';
try {
const cardPromises = group.items.map(item => {
try { return renderCard(item); }
catch (cardError) { console.error(`[renderTimeline] Error in renderCard:`, item, cardError); return `<div class="card error-card"><div class="card-content">Error displaying article.</div></div>`; }
});
cardsHtml = (await Promise.all(cardPromises)).join('');
} catch (mapError) { console.error(`[renderTimeline] Error in .map:`, group, mapError); cardsHtml = `<div class="card error-card"><div class="card-content">Error displaying group.</div></div>`; }
const connector = i < filteredData.length - 1 ? `<div class="timeline-connector"><div class="timeline-arrow-container"><div class="timeline-line"></div><div class="timeline-arrow"><svg viewBox="0 0 24 24" fill="currentColor" stroke="none" style="width: 20px; height: 20px; fill: white;"><path d="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.41z"/></svg></div></div></div>` : '';
return `<div class="timeline-group"><div class="timeline-header">${group.time}</div>${cardsHtml}</div>${connector}`;
});
const html = (await Promise.all(htmlPromises)).join('');
timelineWrapper.innerHTML = html;
attachCardListeners();
calculateCredibility(filteredData);
}
function calculateCredibility(data) {
if (!statsText || !scoreText || !verdictText || !credCircle) {
console.warn("[calculateCredibility] A DOM element (stats, score, verdict, circle) is missing.");
return;
}
let allScores = [];
if (Array.isArray(data) && data.length > 0) { allScores = data.flatMap(g => g.items.map(i => i.score || 0)); }
else if (Array.isArray(lastRawResults) && lastRawResults.length > 0) { allScores = lastRawResults.map(i => i.score || 0); }
const lang = translations[currentLang] || translations.en;
if (allScores.length === 0) {
statsText.textContent = lang.history?.empty || 'Waiting for search...';
scoreText.textContent = '--'; verdictText.textContent = '--'; const circumference = 2 * Math.PI * 30; credCircle.style.strokeDasharray = `${circumference} ${circumference}`; credCircle.style.strokeDashoffset = circumference; credCircle.style.stroke = 'var(--color-border)'; scoreText.style.color = 'var(--color-text-muted)'; verdictText.className = `verdict-text`;
return;
}
const avg = allScores.reduce((a, b) => a + b, 0) / allScores.length;
let aiVerdictText = "Mixed"; // Default
const entry = historyData.length > 0 ? historyData.find(e => e.subject === currentSubject) : null;
if (entry && entry.verdict) {
aiVerdictText = entry.verdict;
} else if (lastRawResults.length > 0 && lastRawResults[0].verdict) {
aiVerdictText = lastRawResults[0].verdict;
}
const verdictKey = aiVerdictText.toLowerCase();
const verdict = lang.verdict[verdictKey] || aiVerdictText;
const verdictClass = avg >= 75 ? 'verdict-credible' : avg >= 45 ? 'verdict-mitige' : 'verdict-suspect';
const colorName = avg >= 75 ? '--color-success' : avg >= 45 ? '--color-warning' : '--color-danger';
const circumference = 2 * Math.PI * 30;
const offset = circumference - (avg / 100) * circumference;
const computedColor = getComputedStyle(document.documentElement).getPropertyValue(colorName);
credCircle.style.strokeDasharray = `${circumference} ${circumference}`; credCircle.style.strokeDashoffset = offset; credCircle.style.stroke = computedColor;
scoreText.textContent = `${Math.round(avg)}%`; scoreText.style.color = computedColor;
verdictText.textContent = verdict;
verdictText.className = `verdict-text ${verdictClass}`;
const statsTemplate = lang.stats;
statsText.innerHTML = statsTemplate.replace('{subject}', currentSubject).replace('{count}', allScores.length).replace('{score}', Math.round(avg)).replace('{verdict}', verdict);
}
function attachCardListeners() {
document.querySelectorAll('.external-link').forEach(link => {
link.replaceWith(link.cloneNode(true));
});
document.querySelectorAll('.external-link').forEach(link => {
link.addEventListener('click', (e) => {
e.stopPropagation();
const url = link.dataset.url;
if (url && url !== '#') {
window.open(url, '_blank');
}
});
});
}
function updateFilterBadge() {
if(filterBadge) filterBadge.textContent = activeFilters.size;
}
function applyZoom(newZoom) {
currentZoom = Math.max(CONFIG.minZoom, Math.min(CONFIG.maxZoom, newZoom));
if (timelineWrapper) {
timelineWrapper.style.transform = `scale(${currentZoom})`;
} else {
console.error("[applyZoom] ERROR: timelineWrapper is null!");
}
}
// [FIX] Added missing updatePeriodDisplay function
function updatePeriodDisplay() {
if (!periodDisplay) return;
const from = currentPeriod.from;
const to = currentPeriod.to;
periodDisplay.textContent = `Period: ${String(from.day).padStart(2, '0')}/${String(from.month).padStart(2, '0')}/${from.year} ${String(from.hour).padStart(2, '0')}:00 - ${String(to.day).padStart(2, '0')}/${String(to.month).padStart(2, '0')}/${to.year} ${String(to.hour).padStart(2, '0')}:00`;
}
function regroupTimelineData(results, view) {
const groupedData = {};
const unknownDateKey = "Unknown date";
const dayOnlySuffix = " (Full day)";
let itemCount = 0;
try {
results.forEach((item, index) => {
itemCount++;
let groupKey = unknownDateKey, displayTime = unknownDateKey, sortKey = "9999999999";
if (item.dateObject instanceof Date && !isNaN(item.dateObject)) {
try {
const year = item.dateObject.getFullYear();
const month = String(item.dateObject.getMonth() + 1).padStart(2, '0');
const day = String(item.dateObject.getDate()).padStart(2, '0');
const hour = String(item.dateObject.getHours()).padStart(2, '0');
const minute = String(item.dateObject.getMinutes()).padStart(2, '0');
const displayOptionsDay = { year: 'numeric', month: 'long', day: 'numeric' };
const displayOptionsMonth = { year: 'numeric', month: 'long' };
const displayOptionsYear = { year: 'numeric' };
const displayOptionsHour = { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute:'2-digit' };
const hasPreciseTime = (item.dateObject.getHours() !== 0 || item.dateObject.getMinutes() !== 0 || item.dateObject.getSeconds() !== 0 || (item.rawDate && (item.rawDate.includes('T') || item.rawDate.includes(':'))));
if (view === 'hour') {
if (hasPreciseTime) {
groupKey = `${year}-${month}-${day} ${hour}:${minute}`;
sortKey = `${year}${month}${day}${hour}${minute}`;
displayTime = item.dateObject.toLocaleString(currentLang, displayOptionsHour);
} else {
groupKey = `${year}-${month}-${day}${dayOnlySuffix}`;
sortKey = `${year}${month}${day}99`;
displayTime = item.dateObject.toLocaleDateString(currentLang, displayOptionsDay) + dayOnlySuffix;
}
} else if (view === 'day') {
groupKey = `${year}-${month}-${day}`;
sortKey = `${year}${month}${day}`;
displayTime = item.dateObject.toLocaleDateString(currentLang, displayOptionsDay);
} else if (view === 'month') {
groupKey = `${year}-${month}`;
sortKey = `${year}${month}`;
displayTime = item.dateObject.toLocaleDateString(currentLang, displayOptionsMonth);
} else if (view === 'year') {
groupKey = `${year}`;
sortKey = groupKey;
displayTime = item.dateObject.toLocaleDateString(currentLang, displayOptionsYear);
}
} catch (e) { console.error("[regroupTimelineData] Date formatting error:", item.dateObject, e); displayTime = item.rawDate || unknownDateKey; groupKey = unknownDateKey; sortKey = "9999999999"; }
} else { displayTime = item.rawDate || unknownDateKey; groupKey = unknownDateKey; sortKey = "9999999999"; }
if (!groupedData[groupKey]) {
groupedData[groupKey] = { displayTime: displayTime, sortKey: sortKey, items: [] };
}
groupedData[groupKey].items.push(item);
});
const sortedKeys = Object.keys(groupedData).sort((a, b) => {
const keyA = groupedData[a].sortKey;
const keyB = groupedData[b].sortKey;
if (keyA === "9999999999") return 1;
if (keyB === "9999999999") return -1;
const numA = Number(String(keyA).replace(/[- :]/g, ''));
const numB = Number(String(keyB).replace(/[- :]/g, ''));
return numA - numB; // Chronological sort (oldest first)
});
return sortedKeys.map(key => ({ time: groupedData[key].displayTime, items: groupedData[key].items }));
} catch (loopError) { console.error("[regroupTimelineData] Error IN loop/sort:", loopError); return []; }
}
// ========================================================================
// MAIN SEARCH LOGIC (CORRECTED WITH PERIOD FILTER)
// ========================================================================
// [FONCTION MISE À JOUR]
async function runRealSearch(query) {
currentSubject = query;
statsText.textContent = `Searching for "${query}"...`;
await renderTimeline([]);
timelineWrapper.innerHTML = `<div style="padding: 40px; text-align: center; color: var(--color-text-muted);">Searching Google News via proxy...</div>`;
let searchResults;
try {
// Call fetchProxyData
const [resultsPage1, resultsPage2] = await Promise.all([
fetchProxyData(query, 1),
fetchProxyData(query, 11)
]);
const combinedResults = [...resultsPage1, ...resultsPage2];
const uniqueResultsMap = new Map();
combinedResults.forEach(item => {
if(item.url && !uniqueResultsMap.has(item.url)) {
uniqueResultsMap.set(item.url, item);
}
});
searchResults = Array.from(uniqueResultsMap.values());
console.log(`[runRealSearch] ${searchResults.length} unique results received from proxy.`);
} catch (error) {
console.error("[runRealSearch] Error during proxy call:", error);
statsText.textContent = `Search error: ${error.message}`;
await renderTimeline([]); return;
}
// --- [DATE FILTER BLOCK ADDED HERE] ---
// [CORRECTION APPLIQUÉE ICI]
let usePeriodFilter = (
currentPeriod.from.year !== 2025 || currentPeriod.to.year !== 2025 ||
currentPeriod.from.month !== 1 || currentPeriod.from.day !== 1 ||
currentPeriod.to.month !== 12 || currentPeriod.to.day !== 31 ||
currentPeriod.from.hour !== 8 || currentPeriod.to.hour !== 18 // <-- LIGNE CORRIGÉE/AJOUTÉE
);
if (usePeriodFilter && searchResults.length > 0) {
console.log("[runRealSearch] Custom period filter active. Filtering results...");
let dateFrom, dateTo;
try {
dateFrom = new Date(currentPeriod.from.year, currentPeriod.from.month - 1, currentPeriod.from.day, currentPeriod.from.hour, 0, 0);
dateTo = new Date(currentPeriod.to.year, currentPeriod.to.month - 1, currentPeriod.to.day, currentPeriod.to.hour, 0, 0);
if (!isNaN(dateFrom.getTime()) && !isNaN(dateTo.getTime())) {
searchResults = searchResults.filter(item => {
if (!item.dateObject) {
return false; // Exclude articles without a date if filter is active
}
return item.dateObject >= dateFrom && item.dateObject <= dateTo;
});
console.log(`[runRealSearch] ${searchResults.length} results after date filtering.`);
} else {
console.warn("[runRealSearch] Invalid period dates, filter not applied.");
}
} catch(e) {
console.error("[runRealSearch] Error creating filter dates:", e);
}
}
// --- [END OF FILTER BLOCK] ---
if (!Array.isArray(searchResults) || searchResults.length === 0) {
statsText.textContent = `No results found for "${query}" (check date filters).`;
await renderTimeline([]);
return;
}
// The rest of the function (AI analysis, etc.) continues with the filtered searchResults...
// [MODIFIED] Check for 'aiSession'
if (!aiSession) {
console.error("AI (aiSession) is not initialized. Displaying without AI analysis.");
statsText.textContent = "AI not available. Displaying raw results.";
lastRawResults = searchResults.map(item => ({
title: item.title, url: item.url, type: guessType(item.url),
summary: item.snippet, score: 0, verdict: "N/A",
dateObject: item.dateObject, rawDate: item.rawDate,
extracted_date: null
}));
} else {
statsText.textContent = `Analyzing ${searchResults.length} articles with AI (Gemini Nano)...`;
let analysis;
try {
const snippetsToAnalyze = searchResults.map(item => ({ id: item.url, snippet: item.snippet, title: item.title }));
analysis = await getAiAnalysis(snippetsToAnalyze, query);
if (!analysis || !analysis.results || !Array.isArray(analysis.results)) {
throw new Error("AI JSON response (analysis) is invalid or empty.");
}
const analysisMap = new Map(analysis.results.map(item => [item.id, item]));
lastRawResults = searchResults.map(item => {
const aiData = analysisMap.get(item.url);
let finalDateObject = item.dateObject;
let finalRawDate = item.rawDate;
let aiExtractedDateString = null;
if (aiData?.extracted_date) {
aiExtractedDateString = aiData.extracted_date;
try {
const aiDate = new Date(aiData.extracted_date);
if (!isNaN(aiDate.getTime()) && aiDate.getFullYear() > 2000 && aiDate <= new Date()) {
finalDateObject = aiDate;
finalRawDate = aiData.extracted_date;
} else {
aiExtractedDateString = null;
}
} catch(e) { aiExtractedDateString = null; }
}
return {
title: item.title,
url: item.url,
type: guessType(item.url),
summary: aiData ? aiData.summary : item.snippet, // Base English summary from AI
score: aiData ? aiData.score : 0, // Score from AI
verdict: analysis.consensus || "Mixed", // Global verdict (Credible, Mixed, Suspect)
dateObject: finalDateObject,
rawDate: finalRawDate,
extracted_date: aiExtractedDateString
};
});
} catch (aiError) {
console.error("[runRealSearch] Error during AI analysis:", aiError);
statsText.textContent = `AI analysis error: ${aiError.message}. Displaying without AI scores.`;
lastRawResults = searchResults.map(item => ({
title: item.title, url: item.url, type: guessType(item.url),
summary: item.snippet, score: 0, verdict: "N/A",
dateObject: item.dateObject, rawDate: item.rawDate,
extracted_date: null
}));
}
}
if (lastRawResults.length === 0) {
await renderTimeline([]); statsText.textContent = `No valid results to display for "${query}".`; return;
}
const timelineData = regroupTimelineData(lastRawResults, currentView);
await renderTimeline(timelineData);
saveToHistory(timelineData);
}
function guessType(url) {
if (typeof url !== 'string') return 'news';
const lowerUrl = url.toLowerCase();
if (lowerUrl.includes('youtube.com') || lowerUrl.includes('youtu.be') || lowerUrl.includes('vimeo.com') || lowerUrl.includes('dailymotion.com')) return 'video';
if (lowerUrl.includes('facebook.com') || lowerUrl.includes('twitter.com') || lowerUrl.includes('instagram.com') || lowerUrl.includes('linkedin.com') || lowerUrl.includes('reddit.com')) return 'social';
if (lowerUrl.match(/\.(jpeg|jpg|gif|png|bmp|svg|webp)(\?|$)/i)) return 'image';
return 'news';
}
// ========================================================================
// PROXY CALL
// ========================================================================
async function fetchProxyData(query, startIndex = 1) {
// !!! REPLACE WITH YOUR RENDER WEB SERVICE URL ON DEPLOYMENT !!!
//const proxyBaseUrl = 'http://localhost:3001'; // <-- URL FOR LOCAL TEST
const proxyBaseUrl = 'https://factbeacon-api-proxy.onrender.com';
const proxyUrl = `${proxyBaseUrl}/api/search?q=${encodeURIComponent(query)}&start=${startIndex}`;
try {
console.log(`[fetchProxyData] Calling proxy: ${proxyUrl}`);
const res = await fetch(proxyUrl);
if (!res.ok) {
let errorData = {}; try { errorData = await res.json(); } catch (e) { /* ignore */ }
console.error(`[fetchProxyData] Proxy Error ${res.status}:`, errorData);
throw new Error(`Proxy error (${res.status}): ${errorData?.error || res.statusText}`);
}
const data = await res.json();
console.log(`[fetchProxyData] Response received from proxy for start=${startIndex}.`);
if (!data.items) { return []; }
return data.items.map(item => {
let rawDate = null; let dateObject = null;
if (item.pagemap?.metatags?.length > 0) {
const meta = item.pagemap.metatags[0];
rawDate = meta['article:published_time'] || meta['og:published_time'] || meta['datepublished'] || meta['dc.date.issued'] || meta['pubdate'];
}
if (rawDate) {
try { dateObject = new Date(rawDate); if (isNaN(dateObject.getTime())) { dateObject = null; } }
catch (e) { dateObject = null; }
}
return { title: item.title, url: item.link, snippet: item.snippet, rawDate: rawDate, dateObject: dateObject };
});
} catch (error) {
console.error("[fetchProxyData] Proxy call failed:", error);
throw error;
}
}
// ========================================================================
// AI FUNCTIONS (MODIFIED FOR 'LanguageModel')
// ========================================================================
async function handleTranslateWithPrompt(text, targetLang) {
// [MODIFIED] Check for 'aiSession'
if (!aiSession || !text || targetLang === 'en') {
return text;
}
const targetLanguageName = langNameMap[targetLang] || targetLang.toUpperCase();
const prompt = `Translate the following English news summary to ${targetLanguageName}. Keep the tone neutral and factual. Respond ONLY with the translated text, without any introductory phrases like "Here is the translation:" or quotes.\n\nEnglish Summary: "${text}"`;
try {
// [MODIFIED] Use aiSession.prompt()
const translatedText = await aiSession.prompt(prompt);
return translatedText.trim().replace(/^"|"$/g, '').replace(/^.*?: /,'');
} catch (error) {
console.error(`[handleTranslateWithPrompt] Translation error (LanguageModel) to ${targetLanguageName}:`, error);
return text; // Fallback: return original text
}
}
async function getAiAnalysis(snippets, topic) {
// [MODIFIED] Check for 'aiSession'
if (!aiSession) throw new Error("AI Session not initialized");
if (!snippets || snippets.length === 0) return { consensus: "N/A", results: [] };
const articlesText = snippets
.map((item, index) => `Article ${index + 1} (ID: "${item.id}"):\nTitre: ${item.title}\nSnippet: ${item.snippet}`)
.join('\n\n');
const prompt = `
Analyze the following ${snippets.length} news snippets about "${topic}". For each snippet:
1. Provide a "score" (0-100) for credibility based on neutrality and relevance to the topic.
2. Write a neutral, one-sentence "summary" IN ENGLISH.
3. Extract the most specific publication or update date/time found IN THE SNIPPET as "extracted_date". Use ISO 8601 format (YYYY-MM-DDTHH:mm:ssZ or YYYY-MM-DD) if possible, otherwise use the found string. If no date is found in the snippet, return null for "extracted_date".
After analyzing all snippets, provide a one-word overall "consensus": "Credible", "Mixed", or "Suspect".
Snippets:
${articlesText}
Respond ONLY with a valid JSON object. Do not include any text before or after the JSON.
Format:
{
"consensus": "...",
"results": [
{ "id": "...", "score": ..., "summary": "...", "extracted_date": "..." | null },
...
]
}
`;
try {
console.log(`[getAiAnalysis] Sending analysis prompt for ${snippets.length} articles.`);
// [MODIFIED] Use aiSession.prompt()
const rawResponse = await aiSession.prompt(prompt);
const cleanResponse = rawResponse.replace(/```json/g, '').replace(/```/g, '').trim();
try {
const parsedResponse = JSON.parse(cleanResponse);
if (!parsedResponse.results || !Array.isArray(parsedResponse.results)) {
throw new Error("The 'results' property is missing or is not an array in the JSON response.");
}
console.log(`[getAiAnalysis] AI analysis complete. Consensus: ${parsedResponse.consensus}`);
return parsedResponse;
} catch (jsonError) {
console.error("[getAiAnalysis] JSON parsing error:", jsonError, "Raw response:", cleanResponse);
throw new Error("Invalid AI response (not JSON).");
}
} catch (error) {
console.error("[getAiAnalysis] Prompt execution error:", error);
throw new Error(`AI analysis error: ${error.message}`);
}
}
// ========================================================================
// EVENT LISTENERS
// ========================================================================
// [NOUVELLE FONCTION POUR CORRIGER LE BUG DE LANGUE]
function setupTimeTabListeners() {
// Cette ligne clone les onglets pour effacer les anciens écouteurs (sécurité)
document.querySelectorAll('.time-tab').forEach(tab => {
tab.replaceWith(tab.cloneNode(true));
});
// Cette ligne ré-attache les écouteurs aux nouveaux onglets
document.querySelectorAll('.time-tab').forEach(tab => {
// On vérifie si l'onglet est actif (pour le style)
if (tab.dataset.view === currentView) {
tab.classList.add('active');
} else {
tab.classList.remove('active');
}
tab.addEventListener('click', async () => {
document.querySelectorAll('.time-tab').forEach(t => t.classList.remove('active'));
tab.classList.add('active');
const newView = tab.dataset.view;
if (newView !== currentView && lastRawResults.length > 0) {
currentView = newView;
const regroupedData = regroupTimelineData(lastRawResults, currentView);
await renderTimeline(regroupedData);
} else if (newView !== currentView) {
currentView = newView;
}
});
});
}
function setupEventListeners() {
try {
document.getElementById('zoomIn')?.addEventListener('click', () => applyZoom(currentZoom + CONFIG.zoomStep));
document.getElementById('zoomOut')?.addEventListener('click', () => applyZoom(currentZoom - CONFIG.zoomStep));
if(canvasContainer) {
canvasContainer.addEventListener('mousedown', (e) => {
if (e.target.closest('.external-link')) return;
isPanning = true; canvasContainer.style.cursor = 'grabbing';
startX = e.pageX; startY = e.pageY;