forked from kagisearch/kite-public
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kite.html
2168 lines (2016 loc) · 142 KB
/
kite.html
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
<!DOCTYPE html>
<html lang="en" x-bind:class="{ 'dark': darkMode }">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#ffffff" id="theme-color" />
<title>Kite</title>
<link rel="manifest" href="{{ static_path }}/manifest.json" />
<link rel="icon" type="image/svg+xml" href="{{ static_path }}/svg/kite.svg" />
<link rel="apple-touch-icon" href="{{ static_path }}/apple-touch-icon.png" />
<script src="https://cdn.tailwindcss.com"></script>
<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/Sortable.min.js"></script>
<link rel="stylesheet" href="{{ static_path }}/kite.css?{{ timestamp }}" />
<script>
const timestamp = Date.now();
let mediaData = null;
// Load media data immediately
fetch("{{ static_path }}/media_data.json")
.then((response) => response.json())
.then((data) => {
// Transform array into lookup object
const lookup = {};
data.forEach((item) => {
if (item.domains) {
item.domains.forEach((domain) => {
lookup[domain.toLowerCase()] = item;
});
}
});
mediaData = {
raw: data,
lookup: lookup,
};
})
.catch((error) => {
// Error handling for media data loading
});
</script>
<link
rel="alternate"
:href="currentCategory === 'OnThisDay' ? 'https://en.wikipedia.org/w/api.php?action=featuredfeed&feed=onthisday' : currentCategory.toLowerCase() + '.xml'"
type="application/rss+xml"
:title="'Kagi News - ' + currentCategory"
/>
<script>
tailwind.config = {
darkMode: "class",
theme: {
extend: {
colors: {
dark: {
bg: "#1a202c",
text: "#e2e8f0",
},
},
},
fontSize: {
xs: "0.75rem", // 12px
sm: "0.875rem", // 14px
base: "1rem", // 16px
lg: "1.125rem", // 18px
xl: "1.35rem",
"2xl": "1.5rem",
"3xl": "1.8rem",
"4xl": "2rem",
},
},
};
document.addEventListener("alpine:init", () => {
Alpine.data("sourceOverlay", () => ({
showSourceOverlay: false,
currentSource: { name: "", favicon: "" },
sourceArticles: [],
currentStory: null,
mediaInfo: null,
showSourceInfo: false,
async processSource($event) {
if (!mediaData?.lookup) {
console.log("Media data not yet loaded, fetching...");
const response = await fetch("{{ static_path }}/media_data.json");
const data = await response.json();
const lookup = {};
data.forEach((item) => {
if (item.domains) {
item.domains.forEach((domain) => {
lookup[domain.toLowerCase()] = item;
});
}
});
mediaData = {
raw: data,
lookup: lookup,
};
}
this.showSourceOverlay = true;
this.currentSource = $event.detail.domain || { name: "", favicon: "" };
this.currentStory = $event.detail.story || null;
this.sourceArticles = this.currentStory && this.currentSource?.name ? this.currentStory.articles.filter((a) => a.domain === this.currentSource.name) : [];
this.mediaInfo = null;
if (this.currentSource?.name) {
const lookupKey = this.currentSource.name.toLowerCase();
this.mediaInfo = mediaData?.lookup?.[lookupKey];
}
this.showSourceInfo = false;
},
}));
// Ensure media data is loaded
if (!mediaData) {
fetch("{{ static_path }}/media_data.json")
.then((response) => response.json())
.then((data) => {
mediaData = data;
})
.catch((error) => {
console.error("Error loading media data:", error);
});
}
Alpine.store("intro", {
shown: localStorage.getItem("introShown") === "true",
set(value) {
this.shown = value;
localStorage.setItem("introShown", value);
},
});
Alpine.store("theme", {
current: localStorage.getItem("theme") || "system",
set(theme) {
this.current = theme;
localStorage.setItem("theme", theme);
this.apply();
},
apply() {
const isDark = this.current === "dark" || (this.current === "system" && window.matchMedia("(prefers-color-scheme: dark)").matches);
document.documentElement.classList.toggle("dark", isDark);
document.getElementById("theme-color").setAttribute("content", isDark ? "#1a202c" : "#ffffff");
},
init() {
this.apply();
window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => {
if (this.current === "system") {
this.apply();
}
});
},
});
Alpine.store("fontSize", {
current: localStorage.getItem("fontSize") || "normal",
set(size) {
this.current = size;
localStorage.setItem("fontSize", size);
this.apply();
},
apply() {
document.body.classList.remove("text-sm", "text-base", "text-lg");
switch (this.current) {
case "small":
document.body.classList.add("text-sm");
break;
case "large":
document.body.classList.add("text-lg");
break;
default:
document.body.classList.add("text-base");
}
},
init() {
if (!localStorage.getItem("fontSize")) {
this.set("normal");
}
this.apply();
},
});
Alpine.store("sections", {
defaultOrder: [
"summary",
"primaryImage",
"highlights",
"quotes",
"secondaryImage",
"perspectives",
"historicalBackground",
"humanitarianImpact",
"technicalDetails",
"businessAngle",
"internationalReactions",
"otherDetails",
"timeline",
"sources",
"didYouKnow",
"actionItems"
],
settings: {
summary: localStorage.getItem("showSummary") !== "false",
primaryImage: localStorage.getItem("showPrimaryImage") !== "false",
highlights: localStorage.getItem("showHighlights") !== "false",
quotes: localStorage.getItem("showQuotes") !== "false",
secondaryImage: localStorage.getItem("showSecondaryImage") !== "false",
perspectives: localStorage.getItem("showPerspectives") !== "false",
historicalBackground: localStorage.getItem("showHistoricalBackground") !== "false",
humanitarianImpact: localStorage.getItem("showHumanitarianImpact") !== "false",
technicalDetails: localStorage.getItem("showTechnicalDetails") !== "false",
businessAngle: localStorage.getItem("showBusinessAngle") !== "false",
internationalReactions: localStorage.getItem("showInternationalReactions") !== "false",
otherDetails: localStorage.getItem("showOtherDetails") !== "false",
timeline: localStorage.getItem("showTimeline") !== "false",
sources: localStorage.getItem("showSources") !== "false",
didYouKnow: localStorage.getItem("showDidYouKnow") !== "false",
actionItems: localStorage.getItem("showActionItems") !== "false"
},
order: JSON.parse(localStorage.getItem("sectionOrder")),
toggle(section) {
this.settings[section] = !this.settings[section];
localStorage.setItem("show" + section.charAt(0).toUpperCase() + section.slice(1), this.settings[section]);
},
init() {
if (!this.order) {
this.order = this.defaultOrder;
}
// Reset if there are new items, or the keys are different
if (this.order.length !== this.defaultOrder.length || Object.keys(this.order).some((key) => this.order[key] !== this.defaultOrder[key])) {
this.order = this.defaultOrder;
localStorage.setItem("sectionOrder", JSON.stringify(this.order));
}
},
render() {
const container = document.querySelector('[x-ref="sectionsList"]');
// Clear existing content
container.innerHTML = '';
// Create the initial items
Alpine.store('sections').order.forEach(sectionName => {
const div = document.createElement('div');
div.className = 'flex items-center justify-between';
div.dataset.section = sectionName;
div.innerHTML = `
<div class='flex items-center'>
<svg class='w-6 h-6 text-gray-400 mr-3 cursor-move drag-handle' fill='none' stroke='currentColor' viewBox='0 0 24 24'>
<path stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M4 6h16M4 12h16M4 18h16'></path>
</svg>
<label class='text-sm font-medium text-gray-700 dark:text-gray-300'>
${sectionName.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase())}
</label>
</div>
<button x-data
@click="$store.sections.toggle('${sectionName}')"
class="relative inline-flex h-6 w-11 items-center rounded-full"
:class="$store.sections.settings['${sectionName}'] ? 'bg-blue-600' : 'bg-gray-200 dark:bg-gray-700'">
<span class='sr-only'>Toggle ${sectionName}</span>
<span class='inline-block h-4 w-4 transform rounded-full bg-white transition'
:class="$store.sections.settings['${sectionName}'] ? 'translate-x-6' : 'translate-x-1'"></span>
</button>
`;
container.appendChild(div);
});
// Initialize Sortable
new Sortable(container, {
animation: 150,
handle: '.drag-handle',
onEnd: function(evt) {
const newOrder = Array.from(evt.to.children)
.map(el => el.dataset.section)
.filter(Boolean);
Alpine.store('sections').order = newOrder;
localStorage.setItem("sectionOrder", JSON.stringify(newOrder));
}
});
},
reset() {
this.order = this.defaultOrder;
localStorage.setItem("sectionOrder", JSON.stringify(this.defaultOrder));
this.render();
}
});
Alpine.store("chaosIndex", {
score: 0,
summary: "",
getBucketDescription() {
const score = this.score;
if (score >= 0 && score <= 20) {
return "0-20: Peaceful and calm world. Yay!";
} else if (score >= 21 && score <= 40) {
return "21-40: Emerging challenges, manageable tensions.";
} else if (score >= 41 && score <= 60) {
return "41-60: Growing global issues, but hope persists.";
} else if (score >= 61 && score <= 80) {
return "61-80: Multiple crises, increasing instability.";
} else if (score >= 81 && score <= 100) {
return "81-100: Severe global turmoil, widespread impact.";
} else {
return "Undefined score range";
}
},
});
Alpine.store("storyCount", {
current: parseInt(localStorage.getItem("storyCount")) || 10,
set(count) {
this.current = count;
localStorage.setItem("storyCount", count);
},
init() {
if (this.current < 3) this.current = 3;
if (this.current > 12) this.current = 12;
},
});
Alpine.store("categories", {
order: [],
enabled: [],
isValidCategory(category){
return category != null && category !== undefined && category !== "";
},
init() {
const savedOrder = JSON.parse(localStorage.getItem("categoryOrder"));
const savedEnabled = JSON.parse(localStorage.getItem("enabledCategories"));
if (savedOrder) {
this.order = savedOrder.filter((cat) => this.isValidCategory(cat));
}
if (savedEnabled) {
// Reorder enabled categories to match the order in categoryOrder and filter out null values
this.enabled = this.order.filter((cat) => this.isValidCategory(cat) && savedEnabled.includes(cat));
}
// Save the cleaned up enabled categories
localStorage.setItem("enabledCategories", JSON.stringify(this.enabled));
},
saveNewOrder(newOrder) {
this.order = newOrder.filter((cat) => this.isValidCategory(cat));
// Don't modify enabled categories here - let the Sortable handler manage that
localStorage.setItem("categoryOrder", JSON.stringify(this.order));
localStorage.setItem("enabledCategories", JSON.stringify(this.enabled));
},
enableCategory(category) {
const index = this.enabled.indexOf(category);
if (index > -1) {
if (this.enabled.length > 1) {
this.enabled.splice(index, 1);
}
} else {
// When enabling a category, insert it in the correct position according to order
const orderIndex = this.order.indexOf(category);
const insertIndex = this.enabled.findIndex((cat) => this.order.indexOf(cat) > orderIndex);
if (insertIndex === -1) {
this.enabled.push(category);
} else {
this.enabled.splice(insertIndex, 0, category);
}
}
localStorage.setItem("enabledCategories", JSON.stringify(this.enabled));
},
isEnabled(category) {
return this.enabled.includes(category);
},
});
Alpine.store("imageGallery", {
swiper: null,
isOpen: false,
images: [],
open(images) {
this.images = images;
this.isOpen = true;
document.body.classList.add("overflow-hidden");
setTimeout(() => {
this.swiper = initializeSwiper(".swiper-container");
}, 0);
},
close() {
this.isOpen = false;
document.body.classList.remove("overflow-hidden");
if (this.swiper) {
this.swiper.destroy();
this.swiper = null;
}
},
});
Alpine.store("settings", {
isOpen: false,
open() {
this.isOpen = true;
document.body.classList.add("overflow-hidden");
},
close() {
this.isOpen = false;
document.body.classList.remove("overflow-hidden");
},
});
Alpine.store("audio", {
isPlaying: false,
currentTune: null,
audioElement: null,
tuneNumber: 1,
showIcon: localStorage.getItem("showMusicIcon") !== "false",
init() {
this.audioElement = new Audio();
this.audioElement.addEventListener('ended', () => {
this.isPlaying = false;
});
this.tuneNumber = Math.floor(Math.random() * 6) + 1;
if (localStorage.getItem("showMusicIcon") === null) {
localStorage.setItem("showMusicIcon", "true");
}
},
toggleIcon() {
this.showIcon = !this.showIcon;
localStorage.setItem("showMusicIcon", this.showIcon);
},
toggle() {
if (this.isPlaying) {
this.pause();
} else {
this.play();
}
},
changeTune() {
this.tuneNumber = this.tuneNumber % 6 + 1;
this.currentTune = `{{ static_path }}/tune${this.tuneNumber}.mp3`;
if (this.isPlaying) {
this.audioElement.src = this.currentTune;
this.audioElement.play();
}
},
play() {
if (!this.currentTune) {
this.currentTune = `{{ static_path }}/tune${this.tuneNumber}.mp3`;
this.audioElement.src = this.currentTune;
}
this.audioElement.play();
this.isPlaying = true;
},
pause() {
this.audioElement.pause();
this.isPlaying = false;
}
});
});
function lockScroll() {
document.body.style.overflow = "hidden";
}
function unlockScroll() {
document.body.style.overflow = "";
}
function fetchChaosIndex() {
// Disabled chaos index loading
return;
}
function generateArticleId(category, clusterNumber) {
return `${category.toLowerCase()}-${clusterNumber}`;
}
function updateUrlWithArticleId(articleId) {
const url = new URL(window.location);
if (articleId) {
url.searchParams.set("article", articleId);
} else {
url.searchParams.delete("article");
// If there are no more parameters, remove the '?' entirely
if (Array.from(url.searchParams).length === 0) {
window.history.pushState({}, "", window.location.pathname);
return;
}
}
window.history.pushState({}, "", url);
}
function getArticleIdFromUrl() {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get("article");
}
function formatTimeSince(timestamp) {
const diff = Math.floor(Date.now() / 1000 - timestamp);
if (diff < 60) {
return `Updated ${diff} sec ago`;
} else if (diff < 3600) {
const mins = Math.floor(diff / 60);
return `Updated ${mins} ${mins === 1 ? "min" : "mins"} ago`;
} else {
const hours = Math.floor(diff / 3600);
return `Updated ${hours} ${hours === 1 ? "hour" : "hours"} ago`;
}
}
function handleWikiLink(event) {
const link = event.target.closest('a[href^="https://en.wikipedia.org/wiki/"]');
if (link) {
event.preventDefault();
const title = decodeURIComponent(link.getAttribute("href").split("/").pop());
const apiUrl = `https://en.wikipedia.org/api/rest_v1/page/summary/${encodeURIComponent(title)}`;
fetch(apiUrl)
.then((response) => response.json())
.then((data) => {
showPopup(data, link);
})
.catch((error) => {
console.error("Error fetching Wikipedia summary:", error);
});
}
}
function showPopup(data, link) {
const popup = document.getElementById("wikipedia-popup");
const popupContent = document.getElementById("wikipedia-popup-content");
const popupImage = document.getElementById("wikipedia-popup-image");
const popupLayout = document.getElementById("wikipedia-popup-layout");
const closeButton = document.getElementById("wikipedia-popup-close");
popupContent.textContent = data.extract;
if (data.thumbnail) {
popupImage.src = data.thumbnail.source;
popupImage.style.display = "block";
} else {
popupImage.style.display = "none";
}
popupLayout.classList.remove("flex-row");
popupLayout.classList.add("flex-col");
popupImage.classList.add("mb-4");
popupImage.classList.remove("mr-4");
popupImage.style.width = "100%";
popupImage.style.height = "auto";
popupImage.style.objectFit = "scale-down";
const isMobile = window.innerWidth <= 768;
if (isMobile) {
popup.style.position = "fixed";
popup.style.left = "0";
popup.style.right = "0";
popup.style.top = "0";
popup.style.width = "100%";
popup.style.maxWidth = "100%";
popup.style.height = "80vh";
popup.style.maxHeight = "80vh";
popup.style.margin = "0";
popup.style.borderRadius = "0";
popup.style.overflowY = "auto";
closeButton.style.display = "block";
} else {
const rect = link.getBoundingClientRect();
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
const popupWidth = 400;
const popupHeight = 400;
let leftPosition = rect.left + window.scrollX;
let topPosition = rect.bottom + window.scrollY;
if (leftPosition + popupWidth > viewportWidth) {
leftPosition = Math.max(viewportWidth - popupWidth - 10, 0);
}
if (topPosition + popupHeight > viewportHeight + window.scrollY) {
topPosition = Math.max(rect.top + window.scrollY - popupHeight, window.scrollY);
}
popup.style.position = "absolute";
popup.style.left = `${leftPosition}px`;
popup.style.top = `${topPosition}px`;
popup.style.width = `${popupWidth}px`;
popup.style.height = `${popupHeight}px`;
popup.style.borderRadius = "0.5rem";
closeButton.style.display = "none";
}
popup.style.display = "block";
}
function openImageGallery(images) {
Alpine.store("imageGallery").open(images);
}
document.addEventListener("alpine:init", () => {
Alpine.data("kiteApp", () => ({
stories: [],
expandedStory: null,
initialLoading: true,
mediaData: [],
isScrolling: false,
readStories: JSON.parse(localStorage.getItem("readStories") || "{}"),
totalStoriesRead: parseInt(localStorage.getItem("totalStoriesRead") || "0"),
availableCategories: [],
currentCategory: "",
timestamp: 0,
readCount: 0,
dateClickCount: 0,
allStories: {},
onThisDayEvents: [],
showIntro: !Alpine.store("intro").shown && !getArticleIdFromUrl(),
chaosScore: 0,
chaosSummary: "",
viewMode: "list",
sortableInstance: null,
loadingProgress: 0,
getLastUpdated() {
return formatTimeSince(this.timestamp);
},
openMaps(location) {
const encodedLocation = encodeURIComponent(location);
const appleUrl = `maps://maps.apple.com/?q=${encodedLocation}`;
const googleUrl = `maps:?q=${encodedLocation}`;
const googleWebUrl = `https://www.google.com/maps/search/?api=1&query=${encodedLocation}`;
const isMacOSOrIOS = /Mac|iPhone|iPad|iPod/.test(navigator.platform);
if (isMacOSOrIOS) {
window.location.href = appleUrl;
setTimeout(() => {
if (document.hidden) return;
window.location.href = googleUrl;
}, 500);
} else {
window.location.href = googleUrl;
setTimeout(() => {
if (document.hidden) return;
window.location.href = googleWebUrl;
}, 500);
}
},
allStoriesRead: false,
markAllAsRead() {
// Mark all stories in current category as read
this.stories.forEach(story => {
if (!this.readStories[story.title]) {
this.readStories[story.title] = true;
this.totalStoriesRead++;
}
});
// Update localStorage
localStorage.setItem("readStories", JSON.stringify(this.readStories));
localStorage.setItem("totalStoriesRead", this.totalStoriesRead);
// Hide the button
this.allStoriesRead = true;
},
async init() {
Alpine.store("categories").init();
// Check if all stories are read
this.allStoriesRead = this.stories.every(story => this.readStories[story.title]);
// Load media data
try {
const response = await fetch("{{ static_path }}/media_data.json");
if (response.ok) {
this.mediaData = await response.json();
}
} catch (error) {
console.error("Error loading media data:", error);
this.mediaData = [];
}
this.fetchCategories()
.then(() => {
return this.fetchAllStories();
})
.then(() => {
const storedOrder = Alpine.store("categories").order || [];
const storedEnabled = Alpine.store("categories").enabled || [];
const allCategoryNames = this.availableCategories.map((cat) => cat.name);
// For new users (no stored order or enabled categories), set defaults
if (!storedOrder || storedOrder.length === 0 || !storedEnabled || storedEnabled.length === 0) {
const defaultCategories = ["World", "USA", "Business", "Technology", "Science", "Sports", "Gaming", "Bay Area"];
Alpine.store("categories").order = allCategoryNames;
Alpine.store("categories").enabled = defaultCategories.filter((name) => allCategoryNames.includes(name));
this.currentCategory = "World";
} else {
// For existing users, update order and enabled categories
const newCategories = allCategoryNames.filter((name) => !storedOrder.includes(name));
Alpine.store("categories").order = storedOrder.concat(newCategories);
// Remove categories from order that no longer exist
Alpine.store("categories").order = Alpine.store("categories").order.filter((name) => allCategoryNames.includes(name));
// Keep their enabled categories that still exist
Alpine.store("categories").enabled = storedEnabled.filter((name) => allCategoryNames.includes(name));
}
// Rebuild availableCategories according to the updated order
this.availableCategories = Alpine.store("categories")
.order.map((name) => this.availableCategories.find((cat) => cat.name === name))
.filter((cat) => cat);
// Save the updated order and enabled categories back to localStorage
localStorage.setItem("categoryOrder", JSON.stringify(Alpine.store("categories").order));
localStorage.setItem("enabledCategories", JSON.stringify(Alpine.store("categories").enabled));
// Set current category to the first enabled category
const firstEnabledCategory = Alpine.store("categories").enabled[0];
if (firstEnabledCategory) {
this.currentCategory = firstEnabledCategory;
}
this.updateCategoryDropdown();
this.renderCategories();
this.initCategorySortable();
const articleId = getArticleIdFromUrl();
if (articleId) {
this.openSharedArticle(articleId);
}
});
Alpine.store("theme").init();
Alpine.store("fontSize").init();
Alpine.store("storyCount").init();
Alpine.store("sections").init();
fetchChaosIndex();
},
fetchCategories() {
return fetch(`{{ base_path }}kite.json?${timestamp}`)
.then((response) => response.json())
.then((data) => {
this.availableCategories = data.categories;
this.timestamp = data.timestamp;
});
},
fetchAllStories() {
this.initialLoading = true;
this.allStories = {};
this.totalReadCount = 0;
const totalCategories = this.availableCategories.length;
let loadedCategories = 0;
const fetchPromises = this.availableCategories.map((category) =>
fetch(`{{ base_path }}${category.file}?${timestamp}`)
.then((response) => response.json())
.then((data) => {
if (category.name === "OnThisDay") {
this.onThisDayEvents = data.events;
} else {
this.allStories[category.name] = {
clusters: data.clusters,
readCount: data.read,
};
this.totalReadCount += data.read;
}
loadedCategories++;
this.loadingProgress = Math.round((loadedCategories / totalCategories) * 100);
})
);
return Promise.all(fetchPromises)
.then(() => {
this.changeCategory();
this.initialLoading = false;
})
.catch((error) => {
console.error("Error fetching stories:", error);
this.initialLoading = false;
});
},
initCategorySortable() {
const enabledContainer = document.querySelector('[x-ref="enabledCategories"]');
new Sortable(enabledContainer, {
animation: 150,
ghostClass: "bg-blue-600",
swapThreshold: 0.5,
onEnd: (evt) => {
const newEnabledOrder = Array.from(evt.to.children)
.map(el => el.dataset.category)
.filter(Boolean);
this.updateCategoryOrders(newEnabledOrder);
}
});
},
renderCategories() {
const enabledContainer = document.querySelector('[x-ref="enabledCategories"]');
const disabledContainer = document.querySelector('[x-ref="disabledCategories"]');
const categoriesStore = Alpine.store('categories');
const self = this;
// Clear existing content
enabledContainer.innerHTML = '';
disabledContainer.innerHTML = '';
function createCategoryElement(categoryName, isEnabled) {
const div = document.createElement('div');
div.className = `px-4 py-3 rounded-md text-sm cursor-pointer font-medium flex items-center justify-center min-h-[48px] ${
isEnabled ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-600'
}`;
div.dataset.category = categoryName;
// Use pointer workaround instead of click to avoid mobile browser issues
let startTime = 0;
div.addEventListener('pointerdown', (e) => {
startTime = Date.now();
});
div.addEventListener('pointerup', (e) => {
// Only trigger click if the pointer was down for less than 200ms (distinguishes from drag)
if (Date.now() - startTime < 200) {
self.handleCategoryClick(categoryName);
}
});
const displayName = categoryName === 'OnThisDay' ? 'Today in History' : categoryName;
div.innerHTML = `<span class='text-sm font-medium'>${displayName}</span>`;
return div;
}
// Render enabled categories
categoriesStore.enabled.forEach(categoryName => {
enabledContainer.appendChild(createCategoryElement(categoryName, true));
});
// Render disabled categories
this.availableCategories
.map((cat) => cat.name)
.filter(cat => !categoriesStore.enabled.includes(cat))
.forEach(categoryName => {
disabledContainer.appendChild(createCategoryElement(categoryName, false));
});
},
updateCategoryOrders(newEnabledOrder) {
const categoriesStore = Alpine.store("categories");
const currentOrder = categoriesStore.order;
// Update enabled categories
categoriesStore.enabled = [...newEnabledOrder];
// Create new full order maintaining positions
const newFullOrder = [
...newEnabledOrder,
...currentOrder.filter(cat => !newEnabledOrder.includes(cat))
];
categoriesStore.order = newFullOrder;
// Update localStorage
categoriesStore.saveNewOrder(newFullOrder);
// Update available categories
this.availableCategories = newFullOrder
.map(catName => this.availableCategories.find(cat => cat.name === catName))
.filter(Boolean);
},
handleCategoryClick(category) {
const categoriesStore = Alpine.store("categories");
if (!categoriesStore.enabled.includes(category)) {
categoriesStore.enableCategory(category);
}
else if(categoriesStore.enabled.length > 1 && categoriesStore.enabled.includes(category)){
categoriesStore.enabled = categoriesStore.enabled.filter(cat => cat !== category);
if (category === this.currentCategory) { // If user disables current category, set to first enabled category
this.currentCategory = categoriesStore.enabled[0];
this.changeCategory();
}
}
localStorage.setItem("enabledCategories", JSON.stringify(categoriesStore.enabled));
this.updateCategoryDropdown();
this.renderCategories();
},
updateCategoryDropdown() {
const select = document.getElementById("category-select");
if (!select) {
return;
}
const enabledCategories = Alpine.store("categories").enabled;
while (select.firstChild) {
select.removeChild(select.firstChild);
}
// Use the stored order for enabled categories
enabledCategories.forEach((catName) => {
if (catName) {
const option = document.createElement("option");
option.value = catName;
option.textContent = catName === "OnThisDay" ? "Today in History" : catName;
select.appendChild(option);
}
});
},
closeIntro() {
this.showIntro = false;
Alpine.store("intro").set(true);
},
toggleStory(story, index) {
if (this.expandedStory === story) {
// Collapse the story
story.expanded = false;
this.expandedStory = null;
updateUrlWithArticleId("");
story.showSources = false;
// Do not call scrollToStory when collapsing
} else {
if (this.expandedStory && this.expandedStory !== story) {
this.expandedStory.expanded = false;
this.expandedStory.showSources = false;
}
// Expand the story
if (!this.readStories[story.title]) {
this.readStories[story.title] = true;
localStorage.setItem("readStories", JSON.stringify(this.readStories));
this.totalStoriesRead++;
localStorage.setItem("totalStoriesRead", this.totalStoriesRead);
}
story.expanded = true;
this.expandedStory = story;
const articleId = generateArticleId(this.currentCategory, story.cluster_number);
updateUrlWithArticleId(articleId);
story.showSources = false;
// Call scrollToStory after expanding
this.$nextTick(() => {
this.scrollToStory(index);
});
}
},
closeStory(story, index) {
// Collapse the story
story.expanded = false;
this.expandedStory = null;
updateUrlWithArticleId("");
story.showSources = false;
// Scroll to the collapsed story
this.$nextTick(() => {
this.scrollToStory(index);
});
},
scrollToStory(index) {
setTimeout(() => {
const storyElement = document.getElementById("story-" + index);
if (storyElement) {
const navHeight = document.querySelector(".sticky").offsetHeight;
const yOffset = -navHeight;
const y = storyElement.getBoundingClientRect().top + window.pageYOffset + yOffset;
window.scrollTo({ top: y, behavior: "smooth" });
}
}, 100);
},
openSharedArticle(articleId) {
const [category, clusterNumber] = articleId.split("-");
// Handle multi-word categories by capitalizing each word
const targetCategory = category
.split("+")
.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join(" ");
// Wait for stories to be loaded
const checkAndOpenStory = () => {
if (this.allStories[targetCategory]) {
// Set current category first
this.currentCategory = targetCategory;
// Make sure the category is enabled
if (!Alpine.store("categories").enabled.includes(targetCategory)) {
Alpine.store("categories").enableCategory(targetCategory);
}
// Update category dropdown and UI
this.updateCategoryDropdown();
this.changeCategory();
// Find and open the story
const story = this.allStories[targetCategory].clusters.find((s) => s.cluster_number === parseInt(clusterNumber));
if (story) {
// Ensure the story is in the visible stories array
this.stories = this.allStories[targetCategory].clusters.slice(0, this.$store.storyCount.current);
// Expand the story
story.expanded = true;
this.expandedStory = story;
// Scroll to the story after a short delay to ensure DOM is updated
this.$nextTick(() => {
const storyIndex = this.stories.findIndex((s) => s.cluster_number === story.cluster_number);
if (storyIndex !== -1) {
setTimeout(() => {