This repository was archived by the owner on Jun 8, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1018 lines (897 loc) · 32.8 KB
/
Copy pathapp.js
File metadata and controls
1018 lines (897 loc) · 32.8 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
const fallbackData = {
stories: [
{
id: "water-rights-colorado",
headline: "Colorado basin talks tighten as rural districts brace for new water restrictions",
source: "highcountrynews.com",
date: "2026-04-12",
slug: "water-rights-colorado",
url: "https://www.hcn.org/issues/58-4/colorado-basin-water-restrictions",
relatedUrls: [
"https://www.hcn.org/issues/58-4/colorado-basin-water-restrictions",
"https://www.hcn.org/issues/58-4/rural-water-districts-summer-demand"
],
tags: ["water policy", "rural counties", "climate"],
topic: "Water access",
summary: "Regional talks are converging on emergency conservation targets ahead of peak summer demand.",
whyItMatters: "Food production, municipal planning, and interstate coordination are tightening at the same time.",
relevance: "high relevance",
momentum: 81,
recentMovement: [4, 5, 5, 7, 8, 10, 12],
related: ["crop-insurance-west", "reservoir-emergency-rule"]
},
{
id: "crop-insurance-west",
headline: "Farm groups press for crop insurance changes as drought losses spread westward",
source: "apnews.com",
date: "2026-04-11",
slug: "crop-insurance-west",
url: "https://apnews.com/article/western-drought-crop-insurance-farms",
relatedUrls: [
"https://apnews.com/article/western-drought-crop-insurance-farms"
],
tags: ["agriculture", "drought", "insurance"],
topic: "Water access",
summary: "State advocates want faster claims handling and revised risk models as drought widens.",
whyItMatters: "Insurance rules are becoming operating rules for farms under climate pressure.",
relevance: "high relevance",
momentum: 75,
recentMovement: [3, 4, 5, 6, 7, 8, 9],
related: ["water-rights-colorado", "reservoir-emergency-rule"]
},
{
id: "grid-data-center-south",
headline: "Power regulators weigh fast-track approvals for data center corridors across the South",
source: "reuters.com",
date: "2026-04-13",
slug: "grid-data-center-south",
url: "https://www.reuters.com/world/us/power-regulators-data-center-corridors-south-2026-04-13/",
relatedUrls: [
"https://www.reuters.com/world/us/power-regulators-data-center-corridors-south-2026-04-13/",
"https://www.utilitydive.com/news/data-center-power-corridors-fast-track/744210/"
],
tags: ["energy", "ai infrastructure", "utilities"],
topic: "Grid strain",
summary: "Utilities are debating how quickly new capacity can come online as large compute projects stack up.",
whyItMatters: "Household reliability and industrial growth are now tied to the same buildout decisions.",
relevance: "very high relevance",
momentum: 92,
recentMovement: [2, 3, 5, 7, 8, 11, 14],
related: ["utility-rate-hearings", "semiconductor-water-demand"]
},
{
id: "utility-rate-hearings",
headline: "Consumer advocates push back on utility rate hikes tied to new server campus demand",
source: "texastribune.org",
date: "2026-04-10",
slug: "utility-rate-hearings",
url: "https://www.texastribune.org/2026/04/10/utility-rate-hearings-data-centers/",
relatedUrls: [
"https://www.texastribune.org/2026/04/10/utility-rate-hearings-data-centers/"
],
tags: ["rates", "consumer impact", "electricity"],
topic: "Grid strain",
summary: "Public hearings are testing who pays when transmission upgrades follow industrial demand spikes.",
whyItMatters: "Rate design will shape whether public support for AI-era grid expansion holds.",
relevance: "medium relevance",
momentum: 63,
recentMovement: [2, 2, 3, 4, 5, 7, 8],
related: ["grid-data-center-south", "semiconductor-water-demand"]
},
{
id: "school-phone-bans",
headline: "More states move from pilot programs to statewide school phone restrictions",
source: "npr.org",
date: "2026-04-12",
slug: "school-phone-bans",
url: "https://www.npr.org/2026/04/12/school-phone-ban-states",
relatedUrls: [
"https://www.npr.org/2026/04/12/school-phone-ban-states"
],
tags: ["education", "youth policy", "mental health"],
topic: "Student attention",
summary: "Districts are moving from pilots to broader restrictions while working through enforcement details.",
whyItMatters: "Policy momentum is outrunning implementation capacity in many systems.",
relevance: "medium relevance",
momentum: 58,
recentMovement: [3, 3, 4, 4, 5, 6, 7],
related: ["student-discipline-tech", "edtech-procurement"]
},
{
id: "student-discipline-tech",
headline: "District discipline data shows uneven rollout of classroom device rules",
source: "chalkbeat.org",
date: "2026-04-09",
slug: "student-discipline-tech",
url: "https://www.chalkbeat.org/2026/04/09/device-rules-discipline-data",
relatedUrls: [
"https://www.chalkbeat.org/2026/04/09/device-rules-discipline-data"
],
tags: ["classroom policy", "district data", "implementation"],
topic: "Student attention",
summary: "Early district reporting shows rule enforcement varies sharply by school and staffing level.",
whyItMatters: "The practical story is whether attention rules widen discipline disparities.",
relevance: "moderate relevance",
momentum: 44,
recentMovement: [1, 2, 2, 3, 4, 4, 5],
related: ["school-phone-bans", "edtech-procurement"]
},
{
id: "semiconductor-water-demand",
headline: "Chip expansion plans reignite debate over industrial water use in high-growth regions",
source: "bloomberg.com",
date: "2026-04-08",
slug: "semiconductor-water-demand",
url: "https://www.bloomberg.com/news/articles/2026-04-08/chip-water-demand-growth-regions",
relatedUrls: [
"https://www.bloomberg.com/news/articles/2026-04-08/chip-water-demand-growth-regions"
],
tags: ["manufacturing", "industrial policy", "water demand"],
topic: "Resource competition",
summary: "Large manufacturing projects are colliding with local concerns over water, land, and subsidies.",
whyItMatters: "Industrial policy and local resource stress are becoming the same public argument.",
relevance: "high relevance",
momentum: 69,
recentMovement: [2, 4, 4, 5, 6, 8, 8],
related: ["grid-data-center-south", "water-rights-colorado"]
},
{
id: "reservoir-emergency-rule",
headline: "Emergency reservoir rule changes trigger legal review across western states",
source: "politico.com",
date: "2026-04-07",
slug: "reservoir-emergency-rule",
url: "https://www.politico.com/news/2026/04/07/reservoir-emergency-rule-western-states-legal-review",
relatedUrls: [
"https://www.politico.com/news/2026/04/07/reservoir-emergency-rule-western-states-legal-review"
],
tags: ["legal challenge", "reservoirs", "state response"],
topic: "Water access",
summary: "Temporary operating changes are shifting release timing and local planning assumptions.",
whyItMatters: "Emergency rules can harden into precedent if another stress season follows.",
relevance: "medium relevance",
momentum: 61,
recentMovement: [2, 2, 3, 4, 5, 6, 6],
related: ["water-rights-colorado", "crop-insurance-west"]
},
{
id: "edtech-procurement",
headline: "District buyers revisit edtech contracts as classroom attention priorities shift",
source: "edsurge.com",
date: "2026-04-06",
slug: "edtech-procurement",
url: "https://www.edsurge.com/news/2026-04-06-edtech-procurement-attention-priorities",
relatedUrls: [
"https://www.edsurge.com/news/2026-04-06-edtech-procurement-attention-priorities"
],
tags: ["procurement", "education budgets", "classroom tools"],
topic: "Student attention",
summary: "Buyers are reevaluating software categories that expanded during remote learning.",
whyItMatters: "Budget changes are a durable downstream signal for where schools are headed.",
relevance: "developing relevance",
momentum: 38,
recentMovement: [1, 1, 2, 2, 3, 4, 4],
related: ["school-phone-bans", "student-discipline-tech"]
}
],
audioBriefings: [
{
title: "Civic Engagement: From Global Service to Local Activism",
duration: "5 min",
note: "This briefing explores contrasting forms of civic engagement, from structured international volunteerism to confrontational local activism.",
link: "audio/briefing-2026-04-17.mp3"
}
]
};
const DATA_URL = "./data/stories.json";
const topicFilter = document.querySelector("#topic-filter");
const topicFeed = document.querySelector("#topic-feed");
const topicDetail = document.querySelector("#topic-detail");
const activeFilters = document.querySelector("#active-filters");
const archivePanel = document.querySelector("#archive-panel");
const archiveSummary = document.querySelector("#archive-summary");
const archiveFeed = document.querySelector("#archive-feed");
const AUDIO_BRIEFING_SOURCE_THRESHOLD = 2;
const ARCHIVE_FRESHNESS_THRESHOLD = 20;
let stories = [];
let audioBriefings = [];
const initialParams = new URLSearchParams(window.location.search);
let activeTopic = "all";
let activeTag = initialParams.get("tag") || "";
function toList(value) {
if (Array.isArray(value)) {
return value.map((item) => String(item || "").trim()).filter(Boolean);
}
return String(value || "")
.split(/[,\n|]/)
.map((item) => item.trim())
.filter(Boolean);
}
function firstSentence(value, fallback = "") {
const trimmed = String(value || "").trim();
if (!trimmed) {
return fallback;
}
const match = trimmed.match(/.+?[.!?](?:\s|$)/);
return (match ? match[0] : `${trimmed}.`).trim();
}
function trimSentenceEnd(value) {
return String(value || "").trim().replace(/[.!?]+$/, "");
}
function dedupeBy(values, getKey) {
const seen = new Set();
return values.filter((item) => {
const key = getKey(item);
if (!key || seen.has(key)) {
return false;
}
seen.add(key);
return true;
});
}
function normalizeMovementSeries(series) {
const clean = toList(series).map((item) => Number(item)).filter((item) => Number.isFinite(item));
if (!clean.length) {
return [];
}
const min = Math.min(...clean);
const max = Math.max(...clean);
if (min === max) {
return clean.map(() => 7);
}
return clean.map((value) => Math.max(1, Math.min(14, Math.round(1 + ((value - min) / (max - min)) * 13))));
}
function storyMovementSeries(story) {
const semrushSeries = normalizeMovementSeries(story.semrushTrafficSeries);
if (semrushSeries.length >= 3) {
return semrushSeries;
}
return normalizeMovementSeries(story.recentMovement);
}
function formatDate(dateString) {
return new Date(`${dateString}T12:00:00`).toLocaleDateString("en-US", {
month: "short",
day: "numeric",
year: "numeric"
});
}
function latestDateValue(storiesList) {
return storiesList.reduce((latest, story) => {
const value = new Date(`${story.date}T12:00:00`).getTime();
return Number.isFinite(value) && value > latest ? value : latest;
}, 0);
}
function currentDayTime() {
const today = new Date();
return new Date(today.getFullYear(), today.getMonth(), today.getDate(), 12, 0, 0).getTime();
}
function daysSinceDate(dateString) {
const storyTime = new Date(`${dateString}T12:00:00`).getTime();
if (!Number.isFinite(storyTime)) {
return 999;
}
return Math.max(0, Math.floor((currentDayTime() - storyTime) / 86400000));
}
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
function computeFreshnessScore(topicStories) {
if (!topicStories.length) {
return 0;
}
const latestStoryDate = new Date(latestDateValue(topicStories)).toISOString().slice(0, 10);
const daysOld = daysSinceDate(latestStoryDate);
const recentStories = topicStories.filter((story) => daysSinceDate(story.date) <= 3);
const recentOutlets = new Set(recentStories.map((story) => story.source)).size;
const recencyBase = 100 - daysOld * 12;
const recentStoryBonus = Math.min(12, Math.max(0, recentStories.length - 1) * 4);
const recentOutletBonus = Math.min(8, Math.max(0, recentOutlets - 1) * 4);
return clamp(Math.round(recencyBase + recentStoryBonus + recentOutletBonus), 0, 100);
}
function formatMovement(value) {
return value > 0 ? `+${value}` : `${value}`;
}
function formatUrlLabel(value) {
try {
const parsed = new URL(value);
const path = parsed.pathname === "/" ? "" : parsed.pathname.replace(/\/$/, "");
return `${parsed.hostname}${path}`;
} catch (_error) {
return value;
}
}
function normalizeStory(story) {
const urlCandidates = [
story.url,
story.primaryUrl,
story.storyUrl,
story.outlookLink
].filter(Boolean);
const relatedUrls = dedupeBy(
[
...urlCandidates,
...toList(story.relatedUrls),
...toList(story.urls),
...toList(story.links)
].map((item) => String(item).trim()),
(item) => item
);
return {
...story,
topic: String(story.topic || story.rawTopic || "General").trim() || "General",
tags: dedupeBy(toList(story.tags), (item) => item.toLowerCase()),
recentMovement: toList(story.recentMovement).map((item) => Number(item) || 1).slice(0, 7),
semrushTrafficSeries: toList(story.semrushTrafficSeries).map((item) => Number(item)).filter((item) => Number.isFinite(item)).slice(-7),
summary: String(story.summary || "").trim() === "Needs editorial summary."
? ""
: String(story.summary || "").trim(),
whyItMatters: String(story.whyItMatters || "Needs editorial review before publishing.").trim(),
relevance: String(story.relevance || "developing relevance").trim(),
momentum: Number(story.momentum) || 50,
url: urlCandidates[0] || relatedUrls[0] || "",
relatedUrls
};
}
function tagMatches(story) {
return !activeTag || story.tags.some((tag) => tag.toLowerCase() === activeTag.toLowerCase());
}
function storiesForCurrentTag() {
return stories.filter(tagMatches);
}
function groupedTopicEntries() {
const grouped = new Map();
storiesForCurrentTag().forEach((story) => {
const groupKey = story.clusterId || story.topic;
if (!grouped.has(groupKey)) {
grouped.set(groupKey, { topic: story.topic, stories: [] });
}
grouped.get(groupKey).stories.push(story);
});
return [...grouped.values()]
.map(({ topic, stories: topicStories }) => buildTopicEntry(topic, topicStories))
.sort((a, b) => {
if (b.freshness !== a.freshness) {
return b.freshness - a.freshness;
}
if (b.direction.delta !== a.direction.delta) {
return b.direction.delta - a.direction.delta;
}
if (b.avgMomentum !== a.avgMomentum) {
return b.avgMomentum - a.avgMomentum;
}
if (b.volume !== a.volume) {
return b.volume - a.volume;
}
return a.topic.localeCompare(b.topic);
});
}
function averageMovementSeries(topicStories) {
const storySeries = topicStories.map((story) => storyMovementSeries(story));
const longest = Math.max(...storySeries.map((series) => series.length), 1);
return Array.from({ length: longest }, (_, index) => {
const values = storySeries
.map((series) => series[index])
.filter((value) => Number.isFinite(value));
if (!values.length) {
return 1;
}
return Math.round(values.reduce((sum, value) => sum + value, 0) / values.length);
});
}
function directionFromSeries(series) {
const first = series[0] || 0;
const last = series[series.length - 1] || 0;
const delta = last - first;
if (delta >= 2) {
return { label: "Trending up", tone: "up", delta };
}
if (delta <= -2) {
return { label: "Trending down", tone: "down", delta };
}
return { label: "Holding steady", tone: "steady", delta };
}
function collectTopicUrls(topicStories) {
const urlRows = topicStories.flatMap((story) => {
const urlSet = dedupeBy(
[story.url, ...story.relatedUrls].filter(Boolean),
(item) => item
);
return urlSet.map((url, index) => ({
url,
headline: story.headline,
source: story.source,
date: story.date,
isPrimary: index === 0
}));
});
return dedupeBy(urlRows, (item) => item.url);
}
function topicTags(topicStories) {
return dedupeBy(
topicStories.flatMap((story) => story.tags),
(item) => item.toLowerCase()
);
}
function buildTopicSummary(topic, topicStories, direction, urls, avgMomentum, outlets) {
const strongestStory = [...topicStories].sort(
(a, b) => b.momentum - a.momentum || new Date(b.date) - new Date(a.date)
)[0];
const directionPhrase = direction.tone === "up" ? "moving up" : direction.tone === "down" ? "slipping back" : "holding steady";
const summarySource = strongestStory?.summary || strongestStory?.whyItMatters || "";
const leadingSummary = trimSentenceEnd(firstSentence(summarySource, `${topic} is drawing attention across multiple sources.`));
const significance = trimSentenceEnd(
firstSentence(
strongestStory?.whyItMatters,
"It matters because the cluster is affecting public attention and editorial priorities."
)
);
return `${leadingSummary}. ${significance} The cluster is ${directionPhrase} across ${urls.length || topicStories.length} tracked URLs, ${outlets} sources, and an average momentum of ${avgMomentum}.`;
}
function buildTopicEntry(topic, topicStories) {
const sortedStories = [...topicStories].sort(
(a, b) => b.momentum - a.momentum || new Date(b.date) - new Date(a.date)
);
const volume = topicStories.length;
const avgMomentum = Math.round(
topicStories.reduce((sum, story) => sum + story.momentum, 0) / Math.max(volume, 1)
);
const outlets = new Set(topicStories.map((story) => story.source)).size;
const movementSeries = averageMovementSeries(topicStories);
const direction = directionFromSeries(movementSeries);
const urls = collectTopicUrls(topicStories);
const latestStoryTime = latestDateValue(topicStories);
const latestStoryDate = latestStoryTime ? new Date(latestStoryTime).toISOString().slice(0, 10) : "";
const freshness = computeFreshnessScore(topicStories);
return {
topic,
volume,
avgMomentum,
freshness,
outlets,
movementSeries,
direction,
latestStoryDate,
isArchived: freshness < ARCHIVE_FRESHNESS_THRESHOLD,
tags: topicTags(topicStories),
stories: sortedStories,
urls,
summary: buildTopicSummary(topic, sortedStories, direction, urls, avgMomentum, outlets),
briefing: audioBriefings.find(
(briefing) =>
briefing.link &&
briefing.link !== "#" &&
String(briefing.topic || "").trim().toLowerCase() === String(topic).trim().toLowerCase()
) || null
};
}
function visibleTopicEntries() {
const entries = activeTopicEntries();
if (activeTopic === "all") {
return entries;
}
return groupedTopicEntries().filter((entry) => entry.topic === activeTopic);
}
function qualifiesForAudioSummary(entry) {
return Boolean(
entry &&
entry.briefing &&
entry.outlets >= AUDIO_BRIEFING_SOURCE_THRESHOLD &&
entry.direction?.tone === "up"
);
}
function getTopics() {
return activeTopicEntries().map((entry) => entry.topic);
}
function activeTopicEntries() {
return groupedTopicEntries().filter((entry) => !entry.isArchived);
}
function archivedTopicEntries() {
return groupedTopicEntries().filter((entry) => entry.isArchived);
}
function buildQuery(nextTopic, nextTag) {
const url = new URL(window.location.href);
url.searchParams.delete("topic");
if (!nextTag) {
url.searchParams.delete("tag");
} else {
url.searchParams.set("tag", nextTag);
}
return url;
}
function updateUrl() {
window.history.replaceState({}, "", buildQuery(activeTopic, activeTag));
}
function renderTopicFilter() {
const topics = getTopics();
topicFilter.innerHTML = '<option value="all">All Topics</option>';
topics.forEach((topic) => {
const option = document.createElement("option");
option.value = topic;
option.textContent = topic.toLowerCase();
topicFilter.append(option);
});
activeTopic = topics.includes(activeTopic) ? activeTopic : "all";
topicFilter.value = activeTopic;
}
function renderActiveFilters() {
activeFilters.innerHTML = "";
if (!activeTag && activeTopic === "all") {
return;
}
if (activeTopic !== "all") {
const topicPill = document.createElement("button");
topicPill.type = "button";
topicPill.className = "filter-pill";
topicPill.textContent = `topic: ${activeTopic}`;
topicPill.addEventListener("click", () => selectTopic("all"));
activeFilters.append(topicPill);
}
if (activeTag) {
const tagPill = document.createElement("button");
tagPill.type = "button";
tagPill.className = "filter-pill";
tagPill.textContent = `tag: ${activeTag}`;
tagPill.addEventListener("click", () => selectTag(""));
activeFilters.append(tagPill);
}
}
function tagLink(tag) {
const anchor = document.createElement("a");
anchor.className = "tag";
anchor.href = buildQuery("all", tag).toString();
anchor.textContent = tag;
return anchor;
}
function renderTopicFeed() {
const entries = visibleTopicEntries();
topicFeed.innerHTML = "";
if (!entries.length) {
topicFeed.innerHTML = '<div class="empty-state">No topics match the current filter yet.</div>';
return;
}
entries.forEach((entry) => {
const article = document.createElement("article");
article.className = `topic-card direction-${entry.direction.tone}`;
const header = document.createElement("button");
header.type = "button";
header.className = "topic-card-button";
header.innerHTML = `
<div class="topic-card-top">
<strong>${entry.topic}</strong>
</div>
<div class="topic-card-meta">
<span>Momentum ${entry.avgMomentum} / 100</span>
<span>Freshness ${entry.freshness} / 100</span>
<span class="direction-pill">${entry.direction.label}</span>
</div>
`;
header.addEventListener("click", () => selectTopic(entry.topic));
article.append(header);
const summary = document.createElement("p");
summary.className = "topic-summary-copy";
summary.textContent = entry.summary;
article.append(summary);
const tagRow = document.createElement("div");
tagRow.className = "tag-row";
entry.tags.forEach((tag) => tagRow.append(tagLink(tag)));
article.append(tagRow);
if (qualifiesForAudioSummary(entry)) {
appendBriefingControls(article, entry.briefing);
}
const details = document.createElement("details");
details.className = "url-dropdown";
details.open = activeTopic === entry.topic;
const summaryRow = document.createElement("summary");
summaryRow.textContent = `Sources (${entry.outlets})`;
details.append(summaryRow);
const urlList = document.createElement("ul");
urlList.className = "url-list";
if (!entry.urls.length) {
const empty = document.createElement("li");
empty.className = "empty-state";
empty.textContent = "No source URLs are stored for this topic yet.";
urlList.append(empty);
} else {
entry.urls.forEach((item) => {
const row = document.createElement("li");
row.className = "url-item";
row.innerHTML = `
<a href="${item.url}" target="_blank" rel="noreferrer">${formatUrlLabel(item.url)}</a>
<span>${item.source}, ${formatDate(item.date)}</span>
`;
urlList.append(row);
});
}
details.append(urlList);
article.append(details);
topicFeed.append(article);
});
}
function appendBriefingControls(container, briefing) {
if (!briefing?.link || briefing.link === "#") {
return;
}
const controls = document.createElement("div");
controls.className = "topic-audio-controls";
const label = document.createElement("strong");
label.className = "briefing-label";
label.textContent = "Audio Summary";
const playerRow = document.createElement("div");
playerRow.className = "briefing-player-row";
const audio = document.createElement("audio");
audio.preload = "none";
audio.src = briefing.link;
audio.className = "briefing-audio";
audio.controls = true;
audio.addEventListener("error", () => {
controls.classList.add("briefing-unavailable");
label.textContent = "Audio Summary Unavailable";
});
playerRow.append(audio);
controls.append(label, playerRow);
container.append(controls);
}
function renderTopicDetail() {
const entries = groupedTopicEntries();
const activeEntries = activeTopicEntries();
if (activeTag) {
const taggedStories = storiesForCurrentTag().sort(
(a, b) => new Date(b.date) - new Date(a.date) || b.momentum - a.momentum
);
topicDetail.innerHTML = `
<div class="topic-summary">
<h3>Tag: ${activeTag}</h3>
<p>${taggedStories.filter((story) => story.url || story.relatedUrls?.length).length} source links collected for this tag.</p>
</div>
`;
const list = document.createElement("div");
list.className = "topic-story-list";
taggedStories.forEach((story) => {
const item = document.createElement("a");
item.href = story.url || "#";
item.target = story.url ? "_blank" : "";
item.rel = story.url ? "noreferrer" : "";
item.textContent = `${story.topic}, ${story.headline}`;
if (!story.url) {
item.removeAttribute("target");
item.removeAttribute("rel");
}
list.append(item);
});
topicDetail.append(list);
return;
}
if (activeTopic === "all") {
const lead = activeEntries[0];
if (!lead) {
topicDetail.innerHTML = '<div class="empty-state">Choose a topic to browse deeper.</div>';
return;
}
topicDetail.innerHTML = `
<div class="topic-summary">
<p>${activeEntries.length} live topic clusters from ${storiesForCurrentTag().length} tracked sources.</p>
<ul>
<li>strongest topic: ${lead.topic}</li>
<li>current direction leader: ${lead.direction.label.toLowerCase()}</li>
<li>average momentum leader: ${lead.avgMomentum}</li>
<li>freshness leader: ${lead.freshness}</li>
</ul>
</div>
`;
const list = document.createElement("div");
list.className = "topic-story-list";
activeEntries.forEach((entry) => {
const button = document.createElement("button");
button.type = "button";
button.textContent = `${entry.topic}, ${entry.direction.label.toLowerCase()}`;
button.addEventListener("click", () => selectTopic(entry.topic));
list.append(button);
});
topicDetail.append(list);
return;
}
const entry = entries.find((item) => item.topic === activeTopic);
if (!entry) {
topicDetail.innerHTML = '<div class="empty-state">Choose a topic to browse deeper.</div>';
return;
}
topicDetail.innerHTML = `
<div class="topic-summary">
<h3>${entry.topic}</h3>
<p>${entry.summary}</p>
<ul>
<li>${entry.direction.label.toLowerCase()}</li>
<li>average momentum ${entry.avgMomentum} / 100</li>
<li>freshness ${entry.freshness} / 100</li>
</ul>
</div>
`;
const list = document.createElement("div");
list.className = "topic-story-list";
entry.stories.forEach((story) => {
const link = document.createElement("a");
link.href = story.url || "#";
link.target = story.url ? "_blank" : "";
link.rel = story.url ? "noreferrer" : "";
link.textContent = `${story.headline}, ${story.source}, ${formatDate(story.date)}`;
if (!story.url) {
link.removeAttribute("target");
link.removeAttribute("rel");
}
list.append(link);
});
topicDetail.append(list);
}
function renderArchiveFeed() {
const entries = archivedTopicEntries().sort((a, b) => {
return new Date(b.latestStoryDate) - new Date(a.latestStoryDate);
});
if (!archivePanel || !archiveSummary || !archiveFeed) {
return;
}
archiveSummary.textContent = `Archived Topics (${entries.length})`;
archiveFeed.innerHTML = "";
archivePanel.hidden = !entries.length;
if (!entries.length) {
return;
}
entries.forEach((entry) => {
const row = document.createElement("button");
row.type = "button";
row.className = "archive-item";
row.innerHTML = `
<strong>${entry.topic}</strong>
<span>Last active ${formatDate(entry.latestStoryDate)}</span>
`;
row.addEventListener("click", () => selectTopic(entry.topic));
archiveFeed.append(row);
});
}
function renderTopicVolumeChart() {
const container = document.querySelector("#topic-volume-chart");
const entries = activeTopicEntries().sort((a, b) => {
const left = b.urls.length || b.volume;
const right = a.urls.length || a.volume;
if (left !== right) {
return left - right;
}
if (b.freshness !== a.freshness) {
return b.freshness - a.freshness;
}
return b.avgMomentum - a.avgMomentum;
});
container.innerHTML = "";
entries.forEach((item) => {
const value = item.urls.length || item.volume;
const sourceLabel = value === 1 ? "source" : "sources";
const row = document.createElement("div");
row.className = "metric-row";
row.innerHTML = `
<div class="metric-top">
<span>${item.topic}</span>
<strong>${value} ${sourceLabel}</strong>
</div>
`;
container.append(row);
});
}
function renderSourceSpreadChart() {
const container = document.querySelector("#source-spread-chart");
const entries = activeTopicEntries().sort((a, b) => {
if (b.outlets !== a.outlets) {
return b.outlets - a.outlets;
}
if (b.freshness !== a.freshness) {
return b.freshness - a.freshness;
}
return b.avgMomentum - a.avgMomentum;
});
container.innerHTML = "";
entries.forEach((item) => {
const outletLabel = item.outlets === 1 ? "outlet" : "outlets";
const row = document.createElement("div");
row.className = "metric-row";
row.innerHTML = `
<div class="metric-top">
<span>${item.topic}</span>
<strong>${item.outlets} ${outletLabel}</strong>
</div>
`;
container.append(row);
});
}
function renderTrendDirectionChart() {
const container = document.querySelector("#trend-direction-chart");
const entries = activeTopicEntries();
container.innerHTML = "";
const groups = [
{
key: "up",
label: "↑ Gaining attention",
helper: "More recent source activity than the earlier cluster baseline."
},
{
key: "steady",
label: "→ Holding steady",
helper: "Coverage is still present, but not accelerating."
},
{
key: "down",
label: "↓ Cooling off",
helper: "The topic has less recent movement than it did earlier."
}
];
groups.forEach((group) => {
const matches = entries
.filter((item) => item.direction.tone === group.key)
.sort((a, b) => {
if (b.freshness !== a.freshness) {
return b.freshness - a.freshness;
}
if (b.volume !== a.volume) {
return b.volume - a.volume;
}
return b.avgMomentum - a.avgMomentum;
});
const card = document.createElement("div");
card.className = "trend-summary-card";
const leadTopics = matches.slice(0, 2).map((item) => item.topic).join(" • ");
const exampleText = leadTopics || "No topics right now";
card.innerHTML = `
<div class="chart-top">
<span>${group.label}</span>
<strong>${matches.length}</strong>
</div>
<p>${group.helper}</p>
<div class="trend-summary-example">${exampleText}</div>
`;
container.append(card);
});
}
function renderAll() {
renderTopicFilter();
renderActiveFilters();
renderTopicFeed();
renderArchiveFeed();
renderTopicDetail();
renderTopicVolumeChart();
renderSourceSpreadChart();
renderTrendDirectionChart();
}
function selectTopic(topic) {
const topics = getTopics();
activeTopic = topics.includes(topic) ? topic : "all";
topicFilter.value = activeTopic;
updateUrl();
renderTopicFeed();
renderTopicDetail();
renderActiveFilters();
}
function selectTag(tag) {
activeTag = tag;
if (activeTopic !== "all" && !groupedTopicEntries().some((entry) => entry.topic === activeTopic)) {
activeTopic = "all";
}
updateUrl();
renderAll();
}
async function loadFeedData() {
try {
const response = await fetch(DATA_URL, { cache: "no-store" });
if (!response.ok) {