-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
1385 lines (1313 loc) · 60.3 KB
/
index.js
File metadata and controls
1385 lines (1313 loc) · 60.3 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
/* index.js
* Extracted from index.html on 2026-05-01. Loaded with `defer` so it runs after
* data.js / app.js (matches original execution order).
*
* IMPORTANT: blocks are concatenated at top-level (no IIFE wrap) because inline
* onclick="..." attributes in index.html depend on these functions being globals.
*/
/* ===== Block 1 (from line 1571, 7 lines) ===== */
/* Toggle .on state when a category is clicked */
function rsActivateCat(el){
var nav = el.closest('.rs-cat');
if (!nav) return;
nav.querySelectorAll('a').forEach(function(a){ a.classList.remove('on'); });
el.classList.add('on');
}
/* ----- Articles category dropdown (compact toolbar version) -----
The .rs-cat panel inside .rs-cat-dd-panel is the option list. The
button is a summary that mirrors the active option. */
function rsCatDdToggle(e){
if (e && e.stopPropagation) e.stopPropagation();
var dd = document.getElementById('rs-cat-dd');
if (!dd) return;
var btn = dd.querySelector('.rs-cat-dd-btn');
var panel = dd.querySelector('.rs-cat-dd-panel');
if (!btn || !panel) return;
var open = !panel.hasAttribute('hidden');
if (open) {
panel.setAttribute('hidden','');
btn.setAttribute('aria-expanded','false');
} else {
panel.removeAttribute('hidden');
btn.setAttribute('aria-expanded','true');
}
}
function rsCatDdClose(){
var dd = document.getElementById('rs-cat-dd');
if (!dd) return;
var btn = dd.querySelector('.rs-cat-dd-btn');
var panel = dd.querySelector('.rs-cat-dd-panel');
if (panel) panel.setAttribute('hidden','');
if (btn) btn.setAttribute('aria-expanded','false');
}
/* Mirror the active option's label + count + tint onto the button. */
function rsCatDdSync(){
var dd = document.getElementById('rs-cat-dd');
if (!dd) return;
var active = dd.querySelector('.rs-cat-dd-panel a.on') ||
dd.querySelector('.rs-cat-dd-panel a[data-cat="all"]');
if (!active) return;
var labelEl = document.getElementById('rs-cat-dd-label');
var countEl = document.getElementById('rs-cat-dd-count');
if (labelEl) {
var lbl = active.querySelector('.lbl');
labelEl.textContent = lbl ? lbl.textContent : 'All';
labelEl.setAttribute('data-cat', active.getAttribute('data-cat') || 'all');
}
if (countEl) {
var n = active.querySelector('.n');
countEl.textContent = n ? n.textContent : '0';
}
}
/* Close on outside click */
document.addEventListener('click', function(e){
var dd = document.getElementById('rs-cat-dd');
if (!dd) return;
var panel = dd.querySelector('.rs-cat-dd-panel');
if (!panel || panel.hasAttribute('hidden')) return;
if (!dd.contains(e.target)) rsCatDdClose();
});
/* Close on Esc */
document.addEventListener('keydown', function(e){
if (e.key === 'Escape') rsCatDdClose();
});
/* Initial sync once the count-population code has run.
The data-cat-count attributes are filled by the loop further
down in this file; we wait two animation frames to let that
finish before mirroring numbers onto the button. */
if (typeof window !== 'undefined') {
window.addEventListener('DOMContentLoaded', function(){
requestAnimationFrame(function(){
requestAnimationFrame(rsCatDdSync);
});
});
}
/* ===== Block 2 (from line 16567, 323 lines) ===== */
function _renderArticleInline(n) {
document.getElementById('research-list-view').style.display = 'none';
var target = document.getElementById('article-' + n);
if (!target) return;
var isReader = document.body.classList.contains('reader-mode');
/* Hide (or remove, in reader mode) all other articles */
var all = document.querySelectorAll('.article-full');
for (var i = 0; i < all.length; i++) {
var el = all[i];
if (el === target) continue;
if (isReader) {
if (el.parentNode) el.parentNode.removeChild(el);
} else {
el.style.display = 'none';
}
}
target.style.display = 'block';
/* Clear prior v2-injected content (sections, trust, bl, toc, aend, sens-pop). */
var prior = target.querySelectorAll('.bl, .toc, .trust, .aend, .sec');
for (var p = 0; p < prior.length; p++) {
if (prior[p].parentNode) prior[p].parentNode.removeChild(prior[p]);
}
/* Clear legacy renderer outputs too, in case we rerender after a previous
non-v2 pass left them behind. */
var legacy = target.querySelectorAll('.art-supps-section, .art-kp-card, .art-related-section');
for (var q = 0; q < legacy.length; q++) {
if (legacy[q].parentNode) legacy[q].parentNode.removeChild(legacy[q]);
}
var inner = target.querySelector('[style*="padding"]') || target;
if (inner) {
/* v2 scope: add .article-v2 to the inner wrapper. */
inner.classList.add('article-v2');
target.classList.add('article-v2');
/* Pick accent. */
var accentKey = 'stack';
try {
if (typeof _buildAllArts === 'function') {
var am = _buildAllArts();
if (am[n] && am[n].c && typeof _v2AccentKeyFromCode === 'function') accentKey = _v2AccentKeyFromCode(am[n].c);
}
if (!accentKey || accentKey === 'stack') {
var catEl0 = inner.querySelector('.article-cat');
if (catEl0 && typeof _v2AccentKeyFromCatText === 'function') accentKey = _v2AccentKeyFromCatText(catEl0.textContent);
}
} catch (_) {}
inner.setAttribute('data-accent', accentKey);
/* Cat eyebrow + h1 typography. */
var catEl = inner.querySelector('.article-cat');
if (catEl) { catEl.classList.add('cat'); catEl.removeAttribute('style'); }
var h2El = inner.querySelector('h2');
if (h2El) { h2El.classList.add('v2-h1'); h2El.removeAttribute('style'); }
/* Sensitive-pop conversion. */
if (typeof articleConvertSensitivePops === 'function') articleConvertSensitivePops(inner);
/* Trust strip. */
if (typeof articleTrustHtml === 'function' && h2El) {
var trustHtml = articleTrustHtml(target, accentKey);
if (trustHtml) h2El.insertAdjacentHTML('afterend', trustHtml);
}
/* Bottom Line. */
if (typeof articleBottomLineHtml === 'function') {
var blHtml = articleBottomLineHtml(inner, null);
if (blHtml) {
var trustEl = inner.querySelector('.trust');
if (trustEl) trustEl.insertAdjacentHTML('afterend', blHtml);
else if (h2El) h2El.insertAdjacentHTML('afterend', blHtml);
}
}
/* TOC. */
if (typeof articleTocHtml === 'function') {
var tocHtml = articleTocHtml(inner);
if (tocHtml) {
var blEl = inner.querySelector('.bl');
if (blEl) blEl.insertAdjacentHTML('afterend', tocHtml);
}
}
/* Section wrap. */
if (typeof articleSectionWrapHtml === 'function') articleSectionWrapHtml(inner);
/* Process sources first so it returns the sources wrapper for insertion. */
var sourcesDiv = null;
if (typeof processArticleSources === 'function') {
sourcesDiv = processArticleSources(inner);
}
/* Supplements .aend. */
if (typeof articleSuppsHtml === 'function') {
var suppHtml = articleSuppsHtml(n);
if (suppHtml) {
if (sourcesDiv) sourcesDiv.insertAdjacentHTML('beforebegin', suppHtml);
else inner.insertAdjacentHTML('beforeend', suppHtml);
}
}
/* Related .aend. */
if (typeof articleRelatedHtml === 'function') {
var relHtml = articleRelatedHtml(n);
if (relHtml) {
if (sourcesDiv) sourcesDiv.insertAdjacentHTML('beforebegin', relHtml);
else inner.insertAdjacentHTML('beforeend', relHtml);
}
}
}
target.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
function showArticle(n) {
goArticle(n);
}
function readerClose() {
/* Always navigate to the main page in-tab for a reliable, clean transition.
If the tab was opened via window.open(), it will just land on the main view; the user can close the tab themselves. */
window.location.href = window.location.pathname;
}
function toggleSrcCat(btn) {
var cat = btn.closest('.abt-src-cat');
if (cat) cat.classList.toggle('collapsed');
}
function showArticleList() {
for (var i = 1; i <= 141; i++) {
var el = document.getElementById('article-' + i);
if (el) el.style.display = 'none';
}
document.getElementById('research-list-view').style.display = 'block';
document.getElementById('research-view').scrollIntoView({ behavior: 'smooth', block: 'start' });
}
window._articleCategoryFilter = 'all';
window._articleSearchQuery = '';
const ARTICLE_CAT_LABELS={all:'All Research',quickread:'Quick Reads',guide:'Guides',breakthrough:'Breakthroughs',myth:'Reality Check',safety:'Safety Alerts',kids:'Kids',population:'Population',condition:'Condition',stack:'Stack'};
/* Curated "top 20" article ordering — explicitly mixes categories at the
top of the Articles list so the page doesn't front-load Quick Reads (or
any single category). The 20 picks below are the highest-click-potential
pieces across all 6 categories: featured guides, popular reality-checks,
safety alerts, breakthroughs, and the new Quick Reads digests. Anything
not in this list keeps its source-DOM position after position 20.
Identifier format:
• Numeric (e.g. 1, 3, 92) → showArticle(N) inline-modal card
• '/a/slug.html' → direct-link /a/ Quick Read card
We match a card to an identifier by parsing either its onclick attribute
(showArticle\((\d+)\)) or its href attribute. */
(function curateTopArticles(){
/* Rebalanced 2026-05-20: previous order was 10 Quick Reads + 10 others
interleaved 1:1, which still made every second card a Quick Read and
visually dominated the Research feed. New mix targets ~6 Quick Reads
across the top 20 (~30%) with the remaining 14 slots split across
Reality Checks, Guides, Safety Alerts, and Breakthroughs so no single
category dominates the first viewport. Featured Guide (id 1) sits
above this list and is unaffected. */
var TOP_20 = [
3, /* Reality Check — Detox Supplements $3 Billion Scam */
4, /* Safety Alert — CDC Warning: Kava Poisoning */
'a/the-10-most-dangerous-supplements-still-legally-sold.html', /* Quick Read */
10, /* Guide — Magnesium Forms Explained */
5, /* Breakthrough — Creatine for Brain Health */
'a/the-10-most-overhyped-supplements-of-2026.html', /* Quick Read */
11, /* Reality Check — Ashwagandha: Most Overhyped */
2, /* Guide — Evidence-Based Sleep Stack */
'a/12-supplement-mistakes-you-should-literally-never-make.html', /* Quick Read */
9, /* Safety Alert — 5 Supplements That Dangerously Interact */
6, /* Breakthrough — NMN and NAD */
'a/the-cheapest-effective-supplements-vs-the-priciest-hyped-ones.html', /* Quick Read */
15, /* Reality Check — Are Multivitamins a Waste of Money? */
7, /* Guide */
'a/the-10-safest-supplements-on-earth.html', /* Quick Read */
17, /* Safety Alert */
8, /* Breakthrough — Collagen */
'a/the-10-most-studied-supplements-on-earth.html', /* Quick Read */
16, /* Reality Check */
12 /* Guide */
];
function cardKey(card){
var onclick = card.getAttribute('onclick') || '';
var m = onclick.match(/showArticle\((\d+)\)/);
if (m) return parseInt(m[1], 10);
var href = card.getAttribute('href') || '';
if (href.indexOf('a/') !== -1){
/* Strip any leading slash so 'a/foo.html' === '/a/foo.html'. */
return href.replace(/^\/+/, '');
}
return null;
}
function curate(){
var list = document.querySelector('.article-list');
if (!list) return;
if (list.dataset.curated === '1') return;
var cards = Array.prototype.slice.call(list.children).filter(function(el){
return el.classList && el.classList.contains('article-card');
});
if (cards.length < 2) return;
/* Build an index from key → card node. */
var index = {};
cards.forEach(function(c){
var k = cardKey(c);
if (k !== null) index[k] = c;
});
/* Resolve TOP_20 in order; skip any that don't exist on the page. */
var picked = [];
var pickedSet = new Set();
TOP_20.forEach(function(id){
var card = index[id];
if (card && !pickedSet.has(card)){
picked.push(card);
pickedSet.add(card);
}
});
/* Append the picked cards in curated order, then the remainder in their
original source-DOM order. appendChild moves nodes (no clone). */
picked.forEach(function(c){ list.appendChild(c); });
cards.forEach(function(c){ if (!pickedSet.has(c)) list.appendChild(c); });
list.dataset.curated = '1';
}
if (document.readyState === 'loading'){
document.addEventListener('DOMContentLoaded', curate);
} else {
curate();
}
})();
function filterArticles(cat, shouldScroll) {
if(shouldScroll === undefined) shouldScroll = true;
window._articleCategoryFilter = cat || 'all';
// Sync the compact toolbar dropdown — mark active option, mirror to button
document.querySelectorAll('.rs-cat-dd-panel a').forEach(function(a){
a.classList.toggle('on', a.getAttribute('data-cat') === window._articleCategoryFilter);
});
if (typeof rsCatDdSync === 'function') rsCatDdSync();
if (typeof rsCatDdClose === 'function') rsCatDdClose();
applyArticleFilter();
// Scroll to the toolbar so it sits at the top of the viewport and the first article appears fully below it
if(shouldScroll){
const toolbar = document.querySelector('.rs-toolbar');
if(toolbar){
const y = toolbar.getBoundingClientRect().top + window.pageYOffset - 72;
window.scrollTo({top: Math.max(0, y), behavior: 'smooth'});
}
}
}
function applyArticleFilter() {
const cat = window._articleCategoryFilter || 'all';
const q = window._articleSearchQuery || '';
const cards = document.querySelectorAll('.article-card,.article-featured');
let visibleCount = 0;
cards.forEach(c => {
const catMatch = (cat === 'all') || (c.dataset.category === cat);
let textMatch = true;
if (q) {
const title = (c.querySelector('.article-title')?.textContent || '').toLowerCase();
const desc = (c.querySelector('.article-desc')?.textContent || '').toLowerCase();
const catText = (c.querySelector('.article-cat')?.textContent || '').toLowerCase();
textMatch = title.includes(q) || desc.includes(q) || catText.includes(q);
}
const show = catMatch && textMatch;
c.style.display = show ? '' : 'none';
if (show) visibleCount++;
});
// Also show/hide kids section based on filter
const kidsSection = document.querySelector('[data-kids-section]');
if (kidsSection) kidsSection.style.display = (cat === 'kids' && !q) ? '' : 'none';
// Handle load-more button + article-hidden class
const lmBtn = document.getElementById('article-load-more');
if (lmBtn) {
if (cat === 'all' && !q) {
document.querySelectorAll('.article-card').forEach((c, i) => {
if (i >= 20) c.classList.add('article-hidden');
else c.classList.remove('article-hidden');
});
const rem = document.querySelectorAll('.article-card.article-hidden').length;
if (rem) { lmBtn.style.display = ''; lmBtn.textContent = 'Load more (' + rem + ' remaining)'; }
else lmBtn.style.display = 'none';
} else {
// When filtering, reveal all matching cards (ignore article-hidden)
document.querySelectorAll('.article-card').forEach(c => c.classList.remove('article-hidden'));
lmBtn.style.display = 'none';
}
}
// No-results state
const noRes = document.getElementById('articles-no-results');
if (noRes) noRes.style.display = (visibleCount === 0) ? '' : 'none';
}
function initArticleLoadMore() {
const cards = document.querySelectorAll('.article-card');
cards.forEach((c, i) => { if (i >= 20) c.classList.add('article-hidden'); c.dataset.articleIndex = i; });
if (cards.length > 20) {
const btn = document.createElement('button');
btn.id = 'article-load-more';
btn.textContent = 'Load more (' + (cards.length - 20) + ' remaining)';
btn.style.cssText = 'width:100%;padding:10px;border:1px solid var(--color-border-tertiary);border-radius:10px;background:none;font-size:12px;color:var(--color-text-secondary);cursor:pointer;margin-top:8px;font-family:inherit';
btn.onclick = function() {
const hidden = document.querySelectorAll('.article-card.article-hidden');
let shown = 0;
hidden.forEach(c => { if (shown < 20) { c.classList.remove('article-hidden'); shown++; } });
const rem = document.querySelectorAll('.article-card.article-hidden').length;
if (!rem) btn.remove();
else btn.textContent = 'Load more (' + rem + ' remaining)';
};
document.querySelector('.article-list')?.appendChild(btn);
}
}
/* Reorder article cards by engagement potential — shock/trending first, then practical/useful, then niche */
const ARTICLE_PRIORITY=[55,18,5,3,9,11,2,47,8,67,45,91,84,88,104,65,15,4,127,6,100,7,16,54,85,107,52,121,124,31,10,17,12,13,59,96,82,56,115,92,14,21,34,69,78,23,75,87,102,20,26,22,72,36,24,66,37,64,81,35,73,111,119,99,27,30,62,49,80,110,98,113,118,130,131,132,133,134,135,136,137,138,139,140,141,90,32,33,105,112,53,71,125,93,40,28,39,42,44,50,51,60,63,70,74,76,79,94,106,108,114,116,123,129,29,41,46,58,86,95,101,120,126,19,25,38,43,48,57,61,68,77,83,89,97,103,109,117,122,128];
/* Top of the "All" list — curated mix of Quick Reads (/a/ pages) and inline
articles (showArticle(N) modal). Used to interleave types at the top so
the page doesn't front-load any one category. After this top block, the
numeric ARTICLE_PRIORITY order takes over. */
const ARTICLE_TOP_MIX=[
'a/the-10-most-dangerous-supplements-still-legally-sold.html',
3, /* Why "Detox" Supplements Are a $3 Billion Scam (Reality Check) */
'a/the-10-most-overhyped-supplements-of-2026.html',
4, /* CDC Warning: Kava Poisoning (Safety Alert) */
'a/12-supplement-mistakes-you-should-literally-never-make.html',
10, /* Magnesium Forms Explained (Guide) */
'a/the-cheapest-effective-supplements-vs-the-priciest-hyped-ones.html',
11, /* Ashwagandha: The Most Overhyped Supplement (Reality Check) */
'a/the-10-safest-supplements-on-earth.html',
5, /* Creatine for Brain Health (Breakthrough) */
'a/10-supplements-that-interact-with-the-most-prescription-drugs.html',
15, /* Are Multivitamins a Waste of Money? (Reality Check) */
'a/10-wild-fun-facts-about-the-supplement-industry.html',
2, /* The Evidence-Based Sleep Stack (Guide) */
'a/the-10-most-studied-supplements-on-earth.html',
9, /* 5 Supplements That Dangerously Interact (Safety Alert) */
'a/10-hidden-gem-supplements-no-one-markets.html',
8, /* The Truth About Collagen Supplements (Reality Check) */
'a/the-10-supplements-people-are-actually-deficient-in.html',
6 /* NMN and NAD (Reality Check) */
];
function _articleCardKey(c){
const onclick=c.getAttribute('onclick')||'';
const m=onclick.match(/showArticle\((\d+)\)/);
if(m)return parseInt(m[1],10);
const href=c.getAttribute('href')||'';
if(href.indexOf('a/')!==-1)return href.replace(/^\/+/,'');
return null;
}
function reorderArticles(){
const list=document.querySelector('.article-list');if(!list)return;
const cards=[...list.querySelectorAll('.article-card')];
/* Build index keyed by either showArticle numeric id or /a/ href. */
const idx={};cards.forEach(c=>{const k=_articleCardKey(c);if(k!==null&&!(k in idx))idx[k]=c;});
/* Compose final order: TOP_MIX → numeric PRIORITY → any leftover cards
(Quick Reads not in TOP_MIX) in source order. Use a Set to skip
duplicates so each card lands in exactly one slot. */
const seen=new Set();
const order=[];
ARTICLE_TOP_MIX.forEach(id=>{const c=idx[id];if(c&&!seen.has(c)){order.push(c);seen.add(c);}});
ARTICLE_PRIORITY.forEach(id=>{const c=idx[id];if(c&&!seen.has(c)){order.push(c);seen.add(c);}});
cards.forEach(c=>{if(!seen.has(c)){order.push(c);seen.add(c);}});
/* appendChild moves each node to the end in turn — final DOM order matches `order`. */
order.forEach(c=>list.appendChild(c));
}
function catCardClick(cat){
filterArticles(cat);
}
/* Hero carousel */
(function(){
const SLIDES=document.querySelectorAll('.hero-slide');
const TOTAL=SLIDES.length;
if(!TOTAL) return;
let current=0, timer;
const dotsEl=document.getElementById('hero-dots');
const counterEl=document.getElementById('hero-current');
const PATTERNS=document.querySelectorAll('.hero-pattern-bg');
const PCOUNT=PATTERNS.length;
let lastPattern=-1;
function rotatePattern(){
if(!PCOUNT) return;
let idx;
if(PCOUNT===1){idx=0;}
else{do{idx=Math.floor(Math.random()*PCOUNT);}while(idx===lastPattern);}
PATTERNS.forEach((p,i)=>p.classList.toggle('active',i===idx));
lastPattern=idx;
}
function renderDots(){
if(!dotsEl) return;
dotsEl.innerHTML='';
for(let i=0;i<TOTAL;i++){
const d=document.createElement('button');
d.className='hero-dot'+(i===current?' active':'');
d.onclick=(e)=>{e.stopPropagation();window.heroGoto(i);};
dotsEl.appendChild(d);
}
}
const progressEl=document.getElementById('hero-progress-fill');
function restartProgress(){
if(!progressEl) return;
progressEl.classList.remove('run');
/* force reflow so the animation restarts */
void progressEl.offsetWidth;
progressEl.classList.add('run');
}
window.heroGoto=function(i){
SLIDES.forEach((s,idx)=>s.classList.toggle('active',idx===i));
current=i;
if(counterEl) counterEl.textContent=(i+1)+' / '+TOTAL;
renderDots();
rotatePattern();
restartProgress();
resetTimer();
};
window.heroNext=function(){window.heroGoto((current+1)%TOTAL);};
window.heroPrev=function(){window.heroGoto((current-1+TOTAL)%TOTAL);};
/* Click the CTA → open the currently-active slide's article */
window.heroReadActive=function(){
const active=SLIDES[current];
if(!active) return;
/* Each slide has onclick="showArticle(<id>)" — extract the id and call directly */
const oc=active.getAttribute('onclick')||'';
const m=oc.match(/showArticle\s*\(\s*(\d+)\s*\)/);
if(m && typeof window.showArticle==='function'){window.showArticle(parseInt(m[1],10));return;}
/* Fallback: synthesize a click */
active.click();
};
function resetTimer(){
clearInterval(timer);
timer=setInterval(()=>window.heroGoto((current+1)%TOTAL),12000);
}
rotatePattern();
renderDots();
if(counterEl) counterEl.textContent='1 / '+TOTAL;
restartProgress();
resetTimer();
const hero=document.getElementById('hero');
if(hero){
hero.addEventListener('mouseenter',()=>{clearInterval(timer);if(progressEl)progressEl.style.animationPlayState='paused';});
hero.addEventListener('mouseleave',()=>{if(progressEl)progressEl.style.animationPlayState='';resetTimer();});
}
})();
function initCatCardCounts(){
const counts={};
document.querySelectorAll('.article-card[data-category],.article-featured[data-category]').forEach(c=>{
const cat=c.dataset.category;counts[cat]=(counts[cat]||0)+1;
});
document.querySelectorAll('[data-cat-count]').forEach(el=>{
el.textContent=counts[el.dataset.catCount]||0;
});
// Total — populates [data-total-count] in the toolbar dropdown's "All" option,
// which the dropdown sync function then mirrors onto the trigger button.
const total=Object.values(counts).reduce((a,b)=>a+b,0);
document.querySelectorAll('[data-total-count]').forEach(el=>{el.textContent=total;});
if (typeof rsCatDdSync === 'function') rsCatDdSync();
}
if (document.querySelector('.article-list')) { reorderArticles(); initArticleLoadMore(); initCatCardCounts(); }
/* Category-hero rotating carousel removed — markup #cat-hero no longer exists. */
/* ===== Block 3 (from line 17014, 3 lines) ===== */
/* Dark mode disabled site-wide — theme is forced to light at the top of <head>.
The theme toggle button is kept hidden in markup; this stub is a no-op kept
only so any older cached link to it doesn't error. */
/* Live-counter ticker moved to nav-search.js so every page that loads it
gets the same animation behavior. (Nav search submit is also handled there.) */
/* Tab routing on load.
- With no hash (or an unrecognized one) → force the Index tab.
- With #research / #about / #profile / #supplements → open that tab.
This guarantees Index is the landing tab no matter what state we
arrived from. */
(function(){
var allowed = {research:1, about:1, profile:1, supplements:1};
function applyHash(){
if (typeof switchTab !== 'function') return false;
var h = (location.hash || '').replace(/^#/, '').toLowerCase();
switchTab(allowed[h] ? h : 'supplements');
// Drop the anti-flash override now that switchTab has set inline display
// rules on the views. Leaving it in place would block in-page tab clicks
// (e.g. Index → Articles → Index) since the !important rule beats the
// empty inline style switchTab uses for the active tab.
document.documentElement.removeAttribute('data-pre-tab');
return true;
}
if(!applyHash()){
var tries = 0;
var iv = setInterval(function(){
if(applyHash() || ++tries > 40) clearInterval(iv);
}, 50);
}
window.addEventListener('hashchange', applyHash);
})();
/* ===== Block 5 (from line 17072, 61 lines) ===== */
// ── Sort-by dropdown ────────────────────────────────────────────────────────
window._sortMode = 'score';
function _applySort() {
const mode = window._sortMode;
const content = document.getElementById('s-content');
if (!content) return;
// Collect ALL cards from every tier section (includes tier-hidden ones)
const allCards = [];
content.querySelectorAll('.scards').forEach(function(container) {
Array.from(container.querySelectorAll(':scope > .sc')).forEach(function(c) {
allCards.push(c);
});
});
if (!allCards.length) return;
allCards.sort(function(a, b) {
if (mode === 'az') {
const na = (a.querySelector('.lc-name') || {}).textContent || '';
const nb = (b.querySelector('.lc-name') || {}).textContent || '';
return na.localeCompare(nb);
}
if (mode === 'recent') {
const na = (a.querySelector('.lc-name') || {}).textContent || '';
const nb = (b.querySelector('.lc-name') || {}).textContent || '';
const da = (typeof lastReviewedFor === 'function') ? lastReviewedFor(na) : '';
const db = (typeof lastReviewedFor === 'function') ? lastReviewedFor(nb) : '';
const cmp = (db || '').localeCompare(da || '');
return cmp !== 0 ? cmp : na.localeCompare(nb);
}
// score high → low (default)
const sa = parseInt((a.querySelector('.lc-score-num') || {}).textContent || '0', 10);
const sb = parseInt((b.querySelector('.lc-score-num') || {}).textContent || '0', 10);
return sb - sa;
});
// Replace entire content with one flat sorted list — removes tier banners & load-more bars
content.innerHTML = '<div class="scards"></div>';
const flat = content.querySelector('.scards');
allCards.forEach(function(c) {
c.classList.remove('tier-hidden');
flat.appendChild(c);
});
}
window.setSortMode = function(val) {
window._sortMode = val;
// Just re-sort whatever is currently displayed — never re-render,
// because renderAll() doesn't know about category/population filters.
_applySort();
};
// Patch renderAll so every render respects the current sort
if (typeof renderAll === 'function') {
const _origRenderAll = renderAll;
window.renderAll = function() {
_origRenderAll.apply(this, arguments);
_applySort();
};
}
/* ===== Block 6 (autocomplete) =====
2026-05-22 — bind autocomplete to BOTH search inputs.
Earlier this listener was wired only to #ix-hero-search + #ix-ac.
On mobile, once the user scrolls past the hero the page swaps in the
sticky-panel search (#ix-sticky-search + #ix-sticky-ac), and that input
had no autocomplete handler — typing into it produced nothing.
Fix: extract a `bind(input, ac)` factory and call it for each
(input, ac) pair that exists in the DOM. The suggestion-builder,
keyboard-nav, and pick handlers are shared; the visible AC element
used at any moment is the one belonging to the input the user is
typing into, so it renders below the correct field. */
(function(){
const inputs = [
{ inp: document.getElementById('ix-hero-search'), ac: document.getElementById('ix-ac') },
{ inp: document.getElementById('ix-sticky-search'), ac: document.getElementById('ix-sticky-ac') },
].filter(p => p.inp && p.ac);
if (!inputs.length) return;
// ── Shared helpers ──────────────────────────────────────────────────────
function escH(s){const d=document.createElement('div');d.textContent=s;return d.innerHTML;}
function escA(s){return String(s).replace(/"/g,'"').replace(/'/g,''');}
function scrollToList(){
const el=document.getElementById('s-content')||document.getElementById('main-ui');
if(!el)return;
const sticky=document.querySelector('.sticky-bar');
const offset=sticky?sticky.getBoundingClientRect().bottom+8:80;
window.scrollTo({top:el.getBoundingClientRect().top+window.pageYOffset-offset,behavior:'smooth'});
}
/* Build an article search-index lazily from every .article-card on the
page. Captures: title, href (for <a> cards) or articleId (for showArticle
numbered cards), category, and read-time minutes. Cached after first
build; cleared if the page injects more cards dynamically. */
let _artIndex = null;
function buildArtIndex(){
if (_artIndex) return _artIndex;
_artIndex = [];
/* 2026-05-25 — dedupe by (title|href|articleId) key. The same article
can legitimately appear on the page twice (e.g. a "Featured" spot
above the grid + the same card in the main grid), but we don't want
it twice in the search dropdown — that's how "Atrial Fibrillation"
was showing twice in a row. */
const seen = new Set();
document.querySelectorAll('.article-card,.article-featured').forEach(card => {
const titleEl = card.querySelector('.article-title');
if (!titleEl) return;
const title = (titleEl.textContent || '').trim();
if (!title) return;
const catEl = card.querySelector('.article-cat');
const cat = (catEl ? catEl.textContent.trim() : '') || (card.getAttribute('data-category') || '');
const minEl = card.querySelector('.article-side-stat');
const min = minEl ? (minEl.textContent || '').trim() : '';
const href = card.tagName === 'A' ? card.getAttribute('href') : '';
const onclickAttr = card.getAttribute('onclick') || '';
const showMatch = onclickAttr.match(/showArticle\((\d+)\)/);
const articleId = showMatch ? parseInt(showMatch[1], 10) : 0;
if (!href && !articleId) return;
const key = (href || ('id:' + articleId) || title).toLowerCase();
if (seen.has(key)) return;
seen.add(key);
_artIndex.push({ title, cat, min, href, articleId });
});
return _artIndex;
}
/* Category eyebrow colour map for the Research section rows.
Safety/Reality Check use red; everything else uses brand-green. */
function artCatClass(cat){
const c = (cat || '').toLowerCase();
if (/safety|alert/.test(c)) return 'gs-ac-art-cat gs-ac-art-cat-safety';
if (/reality|myth/.test(c)) return 'gs-ac-art-cat gs-ac-art-cat-reality';
return 'gs-ac-art-cat';
}
/* ============================================================================
SEARCH MATCHER v2 (2026-05-25)
Five tiers, in order of relevance:
4 — prefix on the primary name/title
3 — prefix on any word inside the name/title (split on space/hyphen/paren/slash/comma)
2 — prefix on a tag/category field (e.g. "Heart" matches Omega-3 via s.tag)
1 — fuzzy match (Levenshtein) on any word, queries ≥4 chars only
0 — no match
Within the same tier:
• Supplements sort by composite score (calcScore) DESC, then idx ASC.
• Articles sort by idx ASC (page order) as a stable tie-breaker.
Previously the matcher was startsWith + includes(), which surfaced
mid-word noise like "atri" → "Matricaria" / "psychiatric" / "matrixyl".
The fix moves substring matching out of the relevance signal entirely. */
const WORD_SPLIT = /[\s\-(),\/]+/;
/* Levenshtein with early-exit when the length delta exceeds tolerance. */
function levDist(a, b, maxTol){
const la = a.length, lb = b.length;
if (Math.abs(la - lb) > maxTol) return maxTol + 1;
if (la === 0) return lb;
if (lb === 0) return la;
let prev = new Array(lb + 1);
let cur = new Array(lb + 1);
for (let j = 0; j <= lb; j++) prev[j] = j;
for (let i = 1; i <= la; i++){
cur[0] = i;
let rowMin = cur[0];
for (let j = 1; j <= lb; j++){
cur[j] = (a.charCodeAt(i-1) === b.charCodeAt(j-1))
? prev[j-1]
: Math.min(prev[j-1], prev[j], cur[j-1]) + 1;
if (cur[j] < rowMin) rowMin = cur[j];
}
if (rowMin > maxTol) return maxTol + 1; // can only grow from here
const swap = prev; prev = cur; cur = swap;
}
return prev[lb];
}
function fuzzyHit(ql, words){
if (ql.length < 4) return false;
const tol = ql.length >= 7 ? 2 : 1;
for (let i = 0; i < words.length; i++){
const w = words[i];
if (w.length < ql.length - tol) continue;
/* Compare the query against the WORD'S PREFIX of the same length.
This intentionally rejects matches like "atri" vs "matricaria"
(which would be valid under a more permissive "any substring within
edit distance" scheme — but that's how the "atri" noise got into
the dropdown in the first place). Allow the prefix to be slightly
longer than the query if the word is at least query-length+tol. */
const probe = w.slice(0, ql.length);
if (levDist(probe, ql, tol) <= tol) return true;
}
return false;
}
function suppRank(s, ql){
const name = (s.n || '').toLowerCase();
if (!name) return 0;
if (name.startsWith(ql)) return 4;
const nameWords = name.split(WORD_SPLIT).filter(Boolean);
if (nameWords.some(w => w.startsWith(ql))) return 3;
const tag = (s.tag || '').toLowerCase();
if (tag){
const tagWords = tag.split(WORD_SPLIT).filter(Boolean);
if (tag.startsWith(ql) || tagWords.some(w => w.startsWith(ql))) return 2;
}
if (fuzzyHit(ql, nameWords)) return 1;
return 0;
}
function artRank(a, ql){
const title = (a.title || '').toLowerCase();
if (!title) return 0;
if (title.startsWith(ql)) return 4;
const titleWords = title.split(WORD_SPLIT).filter(Boolean);
if (titleWords.some(w => w.startsWith(ql))) return 3;
const cat = (a.cat || '').toLowerCase();
if (cat){
const catWords = cat.split(WORD_SPLIT).filter(Boolean);
if (cat.startsWith(ql) || catWords.some(w => w.startsWith(ql))) return 2;
}
if (fuzzyHit(ql, titleWords)) return 1;
return 0;
}
/* Bold the matched substring inside the result row. Falls back to plain
escaped text when no exact substring exists (e.g. fuzzy/tag matches). */
function boldMatch(text, ql){
if (!text) return '';
if (!ql) return escH(text);
const lower = text.toLowerCase();
const idx = lower.indexOf(ql);
if (idx < 0) return escH(text);
return escH(text.slice(0, idx))
+ '<b>' + escH(text.slice(idx, idx + ql.length)) + '</b>'
+ escH(text.slice(idx + ql.length));
}
/* Score helper: prefer the global app.js calcScore() when present so the
two surfaces always agree. Falls back to a simple sum if not loaded. */
function _supScore(s){
if (typeof calcScore === 'function') return calcScore(s);
return (s.e||0)*7 + (s.s||0)*4 + (s.r||1)*3 + (s.o||1)*2 + (s.c||1)*2 + (s.d||1)*2;
}
function buildHtml(q){
q = String(q || '').trim();
if (!q) return '';
if (typeof S === 'undefined' || !S.length) return '';
const ql = q.toLowerCase();
/* Supplements — tier > score > idx. Per-section cap 10. */
const sRanked = [];
for (let i = 0; i < S.length; i++){
const r = suppRank(S[i], ql);
if (r > 0) sRanked.push({ item: S[i], rank: r, score: _supScore(S[i]), idx: i });
}
sRanked.sort((a,b) => b.rank - a.rank || b.score - a.score || a.idx - b.idx);
const suppHits = sRanked.slice(0, 10).map(x => x.item);
/* Articles — tier > idx. Partition into Stacks/Comparisons vs Research. */
const arts = buildArtIndex();
const aRanked = [];
for (let i = 0; i < arts.length; i++){
const r = artRank(arts[i], ql);
if (r > 0) aRanked.push({ item: arts[i], rank: r, idx: i });
}
aRanked.sort((a,b) => b.rank - a.rank || a.idx - b.idx);
const isStackOrCompare = (cat) => /^stack|compare|comparison/i.test(cat || '');
const stackHits = [];
const artHits = [];
for (const x of aRanked){
if (isStackOrCompare(x.item.cat)){
if (stackHits.length < 5) stackHits.push(x.item);
} else {
if (artHits.length < 10) artHits.push(x.item);
}
}
/* No-match empty state — gives explicit feedback instead of silently
collapsing the dropdown. */
if (!suppHits.length && !artHits.length && !stackHits.length){
return '<div class="gs-ac-empty">No matches for “<b>'
+ escH(q) + '</b>”. Try fewer letters or a related word.</div>';
}
let html = '';
if (suppHits.length){
html += `<div class="gs-ac-hdr">Supplements</div>`;
html += suppHits.map(s => {
const tag = (s.tag || '').split(' · ')[0];
return `<div class="gs-ac-item" role="option" data-type="supp" data-name="${escA(s.n)}" onmousedown="event.preventDefault()"><span>${boldMatch(s.n, ql)}</span><span class="gs-ac-tag">${escH(tag)}</span></div>`;
}).join('');
}
if (stackHits.length){
html += `<div class="gs-ac-hdr">Stacks & Comparisons</div>`;
html += stackHits.map(a => {
const dataAttrs = a.href
? `data-type="art" data-href="${escA(a.href)}"`
: `data-type="art" data-art-id="${a.articleId}"`;
const tag = a.cat ? `<span class="gs-ac-tag ${artCatClass(a.cat)}">${escH(a.cat)}</span>` : '';
return `<div class="gs-ac-item" role="option" ${dataAttrs} onmousedown="event.preventDefault()"><span class="gs-ac-art-title">${boldMatch(a.title, ql)}</span>${tag}</div>`;
}).join('');
}
if (artHits.length){
html += `<div class="gs-ac-hdr">Research</div>`;
html += artHits.map(a => {
const dataAttrs = a.href
? `data-type="art" data-href="${escA(a.href)}"`
: `data-type="art" data-art-id="${a.articleId}"`;
/* 2026-05-24 — Layout was stacked (category eyebrow above title) and
rendered centered+broken in the dropdown. Switched to the same
name-left / tag-right pattern used by the Supplements rows so the
dropdown reads consistently across both sections. */
const tag = a.cat ? `<span class="gs-ac-tag ${artCatClass(a.cat)}">${escH(a.cat)}</span>` : '';
return `<div class="gs-ac-item" role="option" ${dataAttrs} onmousedown="event.preventDefault()"><span class="gs-ac-art-title">${boldMatch(a.title, ql)}</span>${tag}</div>`;
}).join('');
}
return html;
}
/* Clear value across all sibling inputs so the input the user picked
from doesn't keep its query while its mate (hidden behind the
scroll line) holds stale text. */
function clearAllInputs(){
inputs.forEach(p => { p.inp.value = ''; });
}
function hideAc(ac){ setTimeout(()=>ac.classList.remove('vis'), 150); }
function pick(item){
const type=item.dataset.type||'supp';
inputs.forEach(p => p.ac.classList.remove('vis'));
if(type==='supp'){
const name = item.dataset.name;
clearAllInputs();
const slug = (window.SS && window.SS.slugify)
? window.SS.slugify(name)
: String(name).toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'');
if (window.SSModal && typeof window.SSModal.open === 'function'){
window.SSModal.open(slug);
return;
}
const href = (window.SS && window.SS.urlFor)
? window.SS.urlFor('supplement', slug)
: ('supplement.html?slug=' + encodeURIComponent(slug));
location.href = href;
return;
} else if(type==='cond'){
clearAllInputs();
const key=item.dataset.key;
if(typeof CONDITIONS!=='undefined'&&CONDITIONS[key]){
const wanted=new Set(CONDITIONS[key].supps);
const items=(typeof S!=='undefined'?S:[]).filter(s=>wanted.has(s.n));
const content=document.getElementById('s-content');
if(content&&typeof renderCard==='function'){
content.innerHTML='<div class="scards">'+items.map(s=>renderCard(s,'')).join('')+'</div>';
scrollToList();
}
}
} else if(type==='art'){
/* Research result — articles either open via the existing
showArticle(N) modal (numbered/featured cards) or by following
the static /a/, /for/, /condition/, /stack/ href, which the
research-modal click interceptor will catch on the homepage. */
clearAllInputs();
const artId = parseInt(item.dataset.artId || '0', 10);
if (artId && typeof window.showArticle === 'function'){
window.showArticle(artId);
return;
}
const href = item.dataset.href;
if (href){
location.href = href;
return;
}
} else if(type==='cat'){
clearAllInputs();
if(typeof setCatFilter==='function'){setCatFilter(item.dataset.name);scrollToList();}
}
}
const deb=(fn,ms)=>{let t;return(...a)=>{clearTimeout(t);t=setTimeout(()=>fn(...a),ms);};};
/* Bind events to one (input, ac) pair. Each pair maintains its own
keyboard-cursor index so up/down arrows in one search field don't
affect the other. The companion input is kept in sync via the
existing block-8 input-sync handler. */
function bind(inp, ac){
let acIdx = -1;
function show(q){
const html = buildHtml(q);
if (!html) { ac.classList.remove('vis'); return; }
acIdx = -1;
ac.innerHTML = html;
ac.classList.add('vis');
}
const debouncedShow = deb(show, 120);
ac.addEventListener('click', e => {
const item = e.target.closest('.gs-ac-item');
if (item) pick(item);
});
inp.addEventListener('input', e => debouncedShow(e.target.value));
inp.addEventListener('focus', e => { if (e.target.value.trim()) show(e.target.value); });
inp.addEventListener('blur', () => hideAc(ac));
inp.addEventListener('keydown', e => {
const items = ac.classList.contains('vis') ? ac.querySelectorAll('.gs-ac-item') : [];
if (e.key === 'ArrowDown' && items.length){
e.preventDefault(); acIdx = Math.min(acIdx + 1, items.length - 1);
items.forEach((it, i) => it.classList.toggle('active', i === acIdx));
} else if (e.key === 'ArrowUp' && items.length){
e.preventDefault(); acIdx = Math.max(acIdx - 1, 0);
items.forEach((it, i) => it.classList.toggle('active', i === acIdx));
} else if (e.key === 'Enter'){
if (acIdx >= 0 && items[acIdx]){ e.preventDefault(); pick(items[acIdx]); }
ac.classList.remove('vis');
} else if (e.key === 'Escape'){
ac.classList.remove('vis'); acIdx = -1;
}
});
/* Exact-name submit shortcut (originally 2026-05-13).
If the user types a query that exactly matches a supplement name
and hits Enter without picking from the AC, jump straight to the
supplement card. Bound per-form so it works for hero OR sticky. */
if (inp.form) {
inp.form.addEventListener('submit', function(e){
const q = String(inp.value || '').trim();
if (!q) return;
if (typeof S === 'undefined' || !S.length) return;
const ql = q.toLowerCase();