-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfeedcycle.js
More file actions
2919 lines (2802 loc) · 131 KB
/
feedcycle.js
File metadata and controls
2919 lines (2802 loc) · 131 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
/* Feed Cycle 2.0.1
Overview
--------
This file is an initial implementation of the version 2 single‑page application redesign.
It intentionally keeps the surface area small while establishing the new architectural
primitives so further features can “relax” into separate panels instead of competing for
simultaneous screen space.
Core Concepts Implemented
- Panel stack (lightweight) with back navigation + scroll restoration.
- Data (feeds/subscriptions + settings) persisted; article items kept ephemeral (runtime only).
- Basic feed refresh (direct fetch) supporting RSS & Atom (podcast enclosures TODO).
- OPML import/export + sample feed injection.
- Filter/Search panel (simple substring search currently) and infinite scroll batching.
- Media player toolbar scaffold (play/pause/progress + accessible draggable cue knob).
- Theme toggle (system / light / dark) using <html data-theme> attribute.
- Accessibility foundations: ARIA roles, keyboard for back, slider, and cards.
Deferred / Upcoming (to port / implement)
- Proxy & cache strategy + adaptive proxy ordering from v1 (CORS resilience).
- Rich search scoring (substring + regex + soundex + cosine) & token index.
- Virtualized window rendering for large article sets (v1 virtualization logic).
- Tags (future). Favourites + read-state now persisted (v2 scaffold increment).
- Media (audio/video) extraction & binding to central player (podcast + enclosure support).
- Advanced HTML sanitization / media safety utilities from v1.
- Rate limit awareness & scheduled refresh throttle respecting last download times.
- Scroll-into-position when filtering by subscription from an article view.
- Settings panes: About / Privacy / Licence content population (placeholders not yet added).
- Offline hydration using Cache API.
- Internationalization hooks & improved date formatting strategy.
Guiding Principles
- Small, explicit DOM + no framework; data driven via templates.
- Progressive enhancement: baseline works without advanced JS features.
- Accessibility over cleverness; semantic roles and keyboard parity.
- Local-first: keep user data (feeds & settings) in LocalStorage, large content ephemeral.
File Structure (v2 initial)
- feedcycle.html : Markup shells + <template> panels.
- feedcycle.css : Layout, themes, panel & media player styles.
- feedcycle.js : This scaffold (panels, state, fetching, minimal search, media player).
*/
(function(){
'use strict';
const VERSION = '2.0.3';
const LS_KEY = 'feedcycle-v2';
const DEBUG = false; // Set true for verbose console output
const DEFAULTS = { theme:'system', feeds:[], categories:[], lastFetch:{}, lastFetchUrl:{}, settings:{ refreshMinutes:30, cacheMaxAgeMinutes:60, corsProxy:'' }, read:{}, favorites:{}, tags:{}, autoTags:{}, proxyScores:{}, proxyScoresResetAt:0, feedRateLimits:{}, lastFetchAttempt:{}, feed404Counts:{} }; // posts ephemeral + tags mapping postId -> [tag]
// Quiet logging - only shows in console when DEBUG is true
const dbg = (...args) => { if(DEBUG) console.log('[FeedCycle]', ...args); };
// state will be loaded after proxy scoring utilities are defined
let state; // defer assignment
let posts = {}; // id -> post (ephemeral)
let lastFilteredPosts = [];
let lastRenderedCount = 0;
let pendingListRefresh = false;
let isInitialLoading = true; // true until first hydration/refresh completes
const INITIAL_RENDER_COUNT = 120;
const CACHE_MAX_AGE_DAYS = 30; // prune cache entries older than this
const CHUNK_SIZE = 120;
// ---------- Proxy & Caching (ported/minimal from v1) ----------
const PROXIES = [
// AllOrigins: use JSON endpoint (better CORS reliability) and unwrap via maybeExtractXmlFromJson
{ name: 'AllOrigins', kind: 'param-enc', base: 'https://api.allorigins.win/get?url=' },
{ name: 'corsproxy.io', kind: 'param-enc', base: 'https://corsproxy.io/?url=' },
{ name: 'CodeTabs', kind: 'param-enc', base: 'https://api.codetabs.com/v1/proxy?quest=' }
];
const proxyStats = new Map(); // name -> {success, fail, lastSuccess, lastFail, score}
const proxyTempDisabledUntil = new Map(); // name -> ts
const PROXY_DISABLE_MS = 10*60*1000;
const FETCH_TIMEOUT_MS = 12000;
const CACHE_NAME = 'feedcycle-cache-v2';
const RATE_LIMIT_BACKOFF_BASE_MS = 60*1000;
const RATE_LIMIT_BACKOFF_MAX_MS = 30*60*1000;
const feedRateLimit = new Map(); // feedId -> { attempt, until, delay }
function hydrateFeedRateLimitsFromState(){
if(!state?.feedRateLimits) return;
Object.entries(state.feedRateLimits).forEach(([fid, rec])=>{
if(!fid || !rec || typeof rec !== 'object') return;
if(feedRateLimit.has(fid)) return;
feedRateLimit.set(fid, { attempt: rec.attempt||0, until: rec.until||0, delay: rec.delay||0 });
});
}
// Enhanced proxy scoring with decay and weighted penalties
const PROXY_FAIL_WEIGHT = 3;
const PROXY_SUCCESS_WEIGHT = 1;
const PROXY_DECAY_MS = 30*60*1000; // 30 minutes
const PROXY_MIN_SAMPLE = 2; // dampen volatility for very small sample sizes
function recalcProxyScore(name){
const now = Date.now();
const s = proxyStats.get(name) || {success:0, fail:0, lastSuccess:0, lastFail:0, score:0};
const decay = (t)=> t? Math.exp(- (now - t) / PROXY_DECAY_MS) : 1;
const successW = s.success * decay(s.lastSuccess);
const failW = s.fail * decay(s.lastFail);
const raw = (successW * PROXY_SUCCESS_WEIGHT) - (failW * PROXY_FAIL_WEIGHT);
const attempts = s.success + s.fail;
const confidence = attempts < PROXY_MIN_SAMPLE ? 0.25 : 1;
s.score = raw * confidence;
proxyStats.set(name, s);
return s.score;
}
function recordProxyResult(name, ok){
if(!name) return;
const s = proxyStats.get(name) || {success:0, fail:0, lastSuccess:0, lastFail:0, score:0};
if(ok){ s.success += 1; s.lastSuccess = Date.now(); }
else { s.fail += 1; s.lastFail = Date.now(); }
proxyStats.set(name, s);
recalcProxyScore(name);
}
function proxyScore(p){ const s = proxyStats.get(p.name); return s? s.score||0 : 0; }
// Now that proxy machinery exists, load state (hydrating proxy stats) and maybe rebase
state = loadState();
function maybeRebaseProxyScores(){
try{
const NOW = Date.now();
const ONE_MONTH_MS = 30*24*60*60*1000; // approximate month
const last = state.proxyScoresResetAt || 0;
if(NOW - last < ONE_MONTH_MS) return; // not yet time
const names = PROXIES.map(p=>p.name);
names.forEach(n=>{ if(!proxyStats.has(n)) proxyStats.set(n,{success:0,fail:0,lastSuccess:0,lastFail:0,score:0}); recalcProxyScore(n); });
const ordered = names.map(n=>({name:n, s: proxyStats.get(n)||{}})).sort((a,b)=> (b.s.score||0) - (a.s.score||0));
const m = ordered.length || 1;
const now = Date.now();
ordered.forEach((entry, idx)=>{
const syntheticSuccess = (m - idx) + 1; // ensures descending, >=2 successes for top
const stats = { success: syntheticSuccess, fail:0, lastSuccess: now, lastFail:0, score:0 };
proxyStats.set(entry.name, stats);
recalcProxyScore(entry.name);
});
state.proxyScoresResetAt = NOW;
saveState();
dbg('Proxy scores rebased (monthly normalization)');
}catch(e){ dbg('Proxy score rebase skipped', e); }
}
maybeRebaseProxyScores();
function buildProxiedUrl(targetUrl, proxySpec){
if(typeof proxySpec === 'string'){
const p = proxySpec.trim();
if(!p) return targetUrl;
if(p.includes('%s')) return p.replace('%s', encodeURIComponent(targetUrl));
if(/[=]$/.test(p) || /[?&]url=$/i.test(p)) return p + encodeURIComponent(targetUrl);
return p + targetUrl;
}
const { kind, base, name } = proxySpec;
if(kind==='param-enc'){
let u = base + encodeURIComponent(targetUrl);
if(name==='AllOrigins') u += `&cache=${Date.now()}`; // bust any stale caching quirks
return u;
}
if(kind==='prefix'){
let clean = targetUrl;
if(!/^https?:/i.test(clean)){
try{ clean = new URL(clean, location.href).href; }catch{}
}
return base + clean.replace(/^https?:\/\//i, (match)=> match.toLowerCase() );
}
return targetUrl;
}
function getProxyCandidates(){
const manual = state.settings.corsProxy?.trim();
if(manual){
// When a manual proxy is configured, only use that (plus the direct fallback later)
return [manual];
}
const now = Date.now();
let active = PROXIES.filter(p=> !(proxyTempDisabledUntil.get(p.name)>now));
// If all public proxies are temporarily disabled, fall back to the full set instead of going direct.
if(!active.length) active = [...PROXIES];
// Ensure each has an initialized score object (prevents NaN sorting jitter)
for(const p of active){ if(!proxyStats.has(p.name)) proxyStats.set(p.name, {success:0,fail:0,lastSuccess:0,lastFail:0,score:0}); }
// Order by score (descending)
active.sort((a,b)=> proxyScore(b)-proxyScore(a));
return active;
}
async function fetchWithCache(url){
const maxAge = clamp((state.settings.cacheMaxAgeMinutes||60)*60*1000, 5*60*1000, 24*60*60*1000);
try{
if(typeof caches !== 'undefined'){
const cache = await caches.open(CACHE_NAME);
const req = new Request(url);
const hit = await cache.match(req);
if(hit){
const date = new Date(hit.headers.get('date')||0).getTime();
if(Date.now()-date < maxAge){ return hit.text(); }
}
const controller = new AbortController();
const to = setTimeout(()=> controller.abort(), FETCH_TIMEOUT_MS);
let res;
try{ res = await fetch(req, { signal: controller.signal }); }
finally{ clearTimeout(to); }
let text = '';
try{ text = await res.text(); }catch{}
if(res.ok){
const stored = new Response(text, { headers:{ 'content-type': res.headers.get('content-type')||'text/xml; charset=utf-8', 'date': new Date().toUTCString() }});
try{ await cache.put(req, stored); }catch{}
return text;
}
if(hit) return hit.text();
const snippet = (text||'').slice(0,240).replace(/\s+/g,' ').trim();
const detail = snippet ? ` (${snippet})` : '';
throw new Error(`HTTP ${res.status} ${res.statusText||''}${detail} @ ${url}`.trim());
}
}catch(e){ /* fall through to no-cache fetch below */ }
const controller = new AbortController();
const to = setTimeout(()=> controller.abort(), FETCH_TIMEOUT_MS);
let res; let text='';
try{ res = await fetch(url, { signal: controller.signal }); }
finally { clearTimeout(to); }
try{ text = await res.text(); }catch{}
if(!res.ok){
const snippet = (text||'').slice(0,240).replace(/\s+/g,' ').trim();
const detail = snippet ? ` (${snippet})` : '';
throw new Error(`HTTP ${res.status} ${res.statusText||''}${detail} @ ${url}`.trim());
}
return text;
}
function xmlHasParserError(xml){
try{ const doc = new DOMParser().parseFromString(xml,'text/xml'); return !!doc.querySelector('parsererror'); }catch{ return true; }
}
function maybeExtractXmlFromJson(text){
try{ const o = JSON.parse(text); if(o && typeof o.contents==='string') return o.contents; }catch{}
return null;
}
function addCacheBuster(u){ try{ return u + (u.includes('?')?'&':'?') + 't=' + Date.now(); }catch{ return u; } }
function getFeedRateLimit(feedId){
if(!feedId) return null;
const entry = feedRateLimit.get(feedId);
if(!entry) return null;
if(entry.until <= Date.now()){
feedRateLimit.delete(feedId);
if(state.feedRateLimits) delete state.feedRateLimits[feedId];
saveState();
return null;
}
return { ...entry, retryIn: Math.max(0, entry.until - Date.now()) };
}
function applyFeedRateLimit(feed){
const feedId = typeof feed === 'string' ? feed : feed?.id;
if(!feedId) return null;
const now = Date.now();
const existing = feedRateLimit.get(feedId);
let attempt = existing? existing.attempt : 0;
if(existing && existing.until <= now){ attempt = 0; }
attempt += 1;
const delay = Math.min(RATE_LIMIT_BACKOFF_BASE_MS * (2 ** (attempt - 1)), RATE_LIMIT_BACKOFF_MAX_MS);
const entry = { attempt, until: now + delay, delay };
feedRateLimit.set(feedId, entry);
state.feedRateLimits = state.feedRateLimits || {};
state.feedRateLimits[feedId] = entry;
state.lastFetchAttempt = state.lastFetchAttempt || {};
state.lastFetchAttempt[feedId] = now;
state.lastFetch[feedId] = now;
if(feed && typeof feed === 'object'){
const current = feed.refreshMinutes || state.settings.refreshMinutes || 30;
const nextMinutes = clamp(current + 5, 5, 24*60);
feed.refreshMinutes = nextMinutes;
}
saveState();
return { ...entry, retryIn: delay };
}
function clearFeedRateLimit(feedId){
if(!feedId) return;
let changed = false;
if(feedRateLimit.delete(feedId)) changed = true;
if(state.feedRateLimits && feedId in state.feedRateLimits){
delete state.feedRateLimits[feedId];
changed = true;
}
if(changed) saveState();
}
function isFeedEnabled(feed){ return feed?.enabled !== false; }
function resetFeed404(feedId){
if(!feedId) return;
if(state.feed404Counts && state.feed404Counts[feedId]){
delete state.feed404Counts[feedId];
saveState();
}
}
function incrementFeed404(feed){
const feedId = typeof feed==='string'? feed : feed?.id;
if(!feedId) return 0;
state.feed404Counts = state.feed404Counts || {};
const next = (state.feed404Counts[feedId]||0)+1;
state.feed404Counts[feedId] = next;
if(next >= 3){
const f = state.feeds.find(x=> x.id===feedId);
if(f){ f.enabled = false; }
}
saveState();
return next;
}
// ---------- Utilities ----------
const $ = sel=> document.querySelector(sel);
const byId = id=> document.getElementById(id);
const el = (tag, props={}, ...kids)=>{ const n=document.createElement(tag); for(const [k,v] of Object.entries(props)){ if(k==='class') n.className=v; else if(k==='html') n.innerHTML=v; else if(k.startsWith('on')&&typeof v==='function') n.addEventListener(k.substring(2),v); else if(v===true) n.setAttribute(k,''); else if(v!==false && v!=null) n.setAttribute(k,v);} for(const k of kids){ if(k==null) continue; if(Array.isArray(k)) n.append(...k); else if(k.nodeType) n.append(k); else n.append(String(k)); } return n; };
const SVG_NS = 'http://www.w3.org/2000/svg';
function svgIcon(useHref){
const svg = document.createElementNS(SVG_NS,'svg');
svg.setAttribute('class','icon');
svg.setAttribute('aria-hidden','true');
const use = document.createElementNS(SVG_NS,'use');
use.setAttribute('href', useHref);
svg.appendChild(use);
return svg;
}
const hashId = s=>{ let h=2166136261>>>0; for(let i=0;i<s.length;i++){ h^=s.charCodeAt(i); h=Math.imul(h,16777619);} return (h>>>0).toString(36); };
const clamp = (n,a,b)=> Math.max(a, Math.min(b,n));
function saveState(){
try{
// Serialize proxyStats lightweight: only keep scalar fields
if(proxyStats && typeof proxyStats.forEach==='function'){
const out = {};
proxyStats.forEach((v,k)=>{ out[k] = { success:v.success||0, fail:v.fail||0, lastSuccess:v.lastSuccess||0, lastFail:v.lastFail||0, score:v.score||0 }; });
state.proxyScores = out;
}
if(feedRateLimit && typeof feedRateLimit.forEach==='function'){
const out = {};
feedRateLimit.forEach((v,k)=>{ out[k] = { attempt:v.attempt||0, until:v.until||0, delay:v.delay||0 }; });
state.feedRateLimits = out;
}
state.lastFetchAttempt = state.lastFetchAttempt || {};
state.feed404Counts = state.feed404Counts || {};
localStorage.setItem(LS_KEY, JSON.stringify(state));
}catch(e){ console.warn('Save failed', e);} }
function loadState(){
try{
const raw = JSON.parse(localStorage.getItem(LS_KEY)||'{}');
const merged = Object.assign({}, DEFAULTS, raw);
// hydrate proxyStats
if(merged.proxyScores){
Object.entries(merged.proxyScores).forEach(([name, s])=>{
if(!s || typeof s !== 'object') return;
proxyStats.set(name, { success:s.success||0, fail:s.fail||0, lastSuccess:s.lastSuccess||0, lastFail:s.lastFail||0, score:s.score||0 });
});
}
if(merged.feedRateLimits){
Object.entries(merged.feedRateLimits).forEach(([fid, rec])=>{
if(!rec || typeof rec !== 'object') return;
feedRateLimit.set(fid, { attempt: rec.attempt||0, until: rec.until||0, delay: rec.delay||0 });
});
}
merged.lastFetchAttempt = merged.lastFetchAttempt || {};
merged.feed404Counts = merged.feed404Counts && typeof merged.feed404Counts==='object' ? merged.feed404Counts : {};
merged.feeds = (merged.feeds||[]).map(f=> ({ ...f, enabled: f?.enabled !== false }));
return merged;
}catch{ return {...DEFAULTS}; }
}
function applyTheme(){
document.documentElement.setAttribute('data-theme', state.theme||'system');
const btn = byId('btn-theme');
if(btn){
const use = btn.querySelector('#themeIconUse');
const map = { dark:'#i-moon', light:'#i-sun', system:'#i-auto' };
if(use) use.setAttribute('href', map[state.theme] || '#i-auto');
btn.title = `Theme: ${state.theme}`;
btn.setAttribute('aria-label', `Theme ${state.theme} (toggle)`);
}
}
// Set up accessible fullscreen toggle button and keep icon/labels in sync.
function setupFullscreenToggle(){
const btn = byId('btn-fullscreen');
if(!btn) return;
const iconUse = btn.querySelector('#fullscreenIconUse');
const getFullscreenElement = ()=> document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
const updateUi = ()=>{
const active = !!getFullscreenElement();
const label = active ? 'Exit fullscreen' : 'Enter fullscreen';
btn.setAttribute('aria-pressed', active ? 'true' : 'false');
btn.setAttribute('aria-label', label);
btn.title = label;
if(iconUse){ iconUse.setAttribute('href', active ? '#i-fullscreen-exit' : '#i-fullscreen'); }
};
const requestFullscreen = (target)=>{
if(!target) return;
const fn = target.requestFullscreen || target.webkitRequestFullscreen || target.mozRequestFullScreen || target.msRequestFullscreen;
if(typeof fn === 'function'){
try{
const result = fn.call(target);
if(result && typeof result.catch==='function'){ result.catch(()=>{}); }
}catch(e){ console.warn('Fullscreen request failed', e); }
}
};
const exitFullscreen = ()=>{
const fn = document.exitFullscreen || document.webkitExitFullscreen || document.mozCancelFullScreen || document.msExitFullscreen;
if(typeof fn === 'function'){
try{
const result = fn.call(document);
if(result && typeof result.catch==='function'){ result.catch(()=>{}); }
}catch(e){ console.warn('Fullscreen exit failed', e); }
}
};
btn.addEventListener('click', ()=>{
if(getFullscreenElement()){ exitFullscreen(); }
else { requestFullscreen(document.documentElement); }
});
['fullscreenchange','webkitfullscreenchange','mozfullscreenchange','MSFullscreenChange'].forEach(evt=> document.addEventListener(evt, updateUi));
['fullscreenerror','webkitfullscreenerror','mozfullscreenerror','MSFullscreenError'].forEach(evt=> document.addEventListener(evt, updateUi));
updateUi();
}
// ---------- Panel Stack ----------
const stackEl = byId('panel-stack');
const backStack = []; // {id, scroll, keep, el}
let suspendListRenders = false; // prevent list rerenders while viewing an article
function showPanel(id, opts={}){
const top = stackEl.lastElementChild;
const topId = top?.dataset.panel;
if(topId==='videoViewer' && id!=='videoViewer'){
cleanupActiveVideo();
}
if(id==='articleViewer' && top){
const scrollEl = top.querySelector('.panel-body');
backStack.push({ id: topId, scroll: scrollEl? scrollEl.scrollTop:0, keep:true, el: top });
// Keep list panel in DOM without layout shift
top.style.visibility='hidden';
top.setAttribute('aria-hidden','true');
suspendListRenders = (topId==='articlesInfiniteScrollable');
renderPanel(id, opts.data); focusPanel(id);
// Reset newly shown panel scroll
const nb = stackEl.lastElementChild?.querySelector('.panel-body'); if(nb) nb.scrollTop = 0;
if(nb) nb.focus?.();
} else if(id==='videoViewer' && topId==='articleViewer'){
const scrollEl = top.querySelector('.panel-body');
backStack.push({ id: topId, scroll: scrollEl? scrollEl.scrollTop:0, keep:true, el: top });
top.style.visibility='hidden';
top.setAttribute('aria-hidden','true');
renderPanel(id, opts.data); focusPanel(id);
const nb = stackEl.lastElementChild?.querySelector('.panel-body'); if(nb) nb.scrollTop = 0;
if(nb) nb.focus?.();
}else{
if(top){
const scrollEl = top.querySelector('.panel-body');
backStack.push({ id: topId, scroll: scrollEl? scrollEl.scrollTop:0 });
while(stackEl.firstChild){ stackEl.removeChild(stackEl.firstChild); }
}
renderPanel(id, opts.data); focusPanel(id);
const nb = stackEl.lastElementChild?.querySelector('.panel-body'); if(nb) nb.scrollTop = 0;
if(nb) nb.focus?.();
}
try{ const st = { panel:id, ts:Date.now() }; history.pushState(st, '', '#'+id); }catch{}
}
function back(){
if(!backStack.length) return;
const top = stackEl.lastElementChild;
if(top?.dataset.panel==='videoViewer'){
cleanupActiveVideo();
}
const prev = backStack.pop();
if(prev.keep && prev.el){
if(top && top!==prev.el) top.remove();
prev.el.style.visibility='';
prev.el.removeAttribute('aria-hidden');
let body = prev.el.querySelector('.panel-body');
const restoreScroll = ()=>{ if(body) body.scrollTop = prev.scroll||0; };
if(prev.id==='articlesInfiniteScrollable'){
suspendListRenders=false;
if(pendingListRefresh){
pendingListRefresh=false;
const desiredScroll = prev.scroll||0;
renderArticles();
body = prev.el.querySelector('.panel-body');
if(body) body.scrollTop = desiredScroll;
} else {
restoreScroll();
}
} else {
restoreScroll();
}
focusPanel(prev.id);
} else {
while(stackEl.firstChild){ stackEl.removeChild(stackEl.firstChild); }
renderPanel(prev.id);
const body = stackEl.lastElementChild?.querySelector('.panel-body'); if(body) body.scrollTop = prev.scroll||0;
focusPanel(prev.id);
}
}
function focusPanel(id){ const p = stackEl.querySelector(`[data-panel="${id}"]`); if(p){ const h = p.querySelector('.panel-bar h2, .panel-bar button.back-btn') || p; h.focus?.(); } }
function renderPanel(id, data){
const tpl = byId('tpl-'+ camelToKebab(id));
if(!tpl){ stackEl.append(el('div',{class:'panel empty','data-panel':id},`Unknown panel: ${id}`)); return; }
const frag = tpl.content.cloneNode(true);
const root = frag.querySelector('[data-panel]');
// Ensure a .panel-body exists for isolated scrolling
if(root && !root.querySelector('.panel-body')){
const body = el('div',{class:'panel-body'});
// Move all non panel-bar children into body
[...root.childNodes].forEach(n=>{
if(n.nodeType===1 && n.classList.contains('panel-bar')) return; // keep bar outside
if(n===body) return;
body.append(n);
});
root.append(body);
}
stackEl.append(root);
wirePanel(root, id, data);
}
function camelToKebab(s){ return s.replace(/[A-Z]/g,m=> '-'+m.toLowerCase()).replace(/^-/, ''); }
function wirePanel(root, id, data){
root.querySelectorAll('[data-action="back"]').forEach(btn=> btn.addEventListener('click', (e)=>{ e.preventDefault(); if(backStack.length){ history.back(); } else { back(); } }));
if(id==='settingsMain'){
root.querySelectorAll('[data-nav]').forEach(b=> b.addEventListener('click', ()=> showPanel(b.dataset.nav)));
}
if(id==='settingsSubscriptions'){
renderSubscriptionsList();
root.querySelector('[data-action="add-sub"]').addEventListener('click', ()=>{
const url = prompt('Feed URL (RSS/Atom):'); if(!url) return;
const f = { id: hashId(url), url, title: url, category:'' };
if(!state.feeds.find(x=>x.id===f.id)) state.feeds.push(f);
saveState(); renderSubscriptionsList();
});
}
if(id==='subscriptionEdit' && data){
renderSubscriptionEdit(data);
}
if(id==='settingsData'){
root.querySelector('[button][data-action]');
root.querySelectorAll('[data-action]').forEach(btn=>{
btn.addEventListener('click', ()=> handleDataAction(btn.dataset.action));
});
}
if(id==='settingsPreferences'){
const form = root.querySelector('#prefsForm');
const themeInputs = form.querySelectorAll('input[name="theme"]');
themeInputs.forEach(r=>{ r.checked = (state.theme||'system')===r.value; });
const refreshInput = form.querySelector('#globalRefreshInput');
const cacheInput = form.querySelector('#cacheMaxAgeInput');
const proxyInput = form.querySelector('#corsProxyInput');
refreshInput.value = state.settings.refreshMinutes || 30;
if(cacheInput) cacheInput.value = state.settings.cacheMaxAgeMinutes || 60;
if(proxyInput) proxyInput.value = state.settings.corsProxy || '';
form.addEventListener('submit', e=>{
e.preventDefault();
const selTheme = [...themeInputs].find(r=>r.checked)?.value||'system';
state.theme = selTheme; applyTheme();
const v = parseInt(refreshInput.value,10); if(!isNaN(v) && v>=5) state.settings.refreshMinutes = v;
if(cacheInput){ const c = parseInt(cacheInput.value,10); if(!isNaN(c) && c>=5) state.settings.cacheMaxAgeMinutes = c; }
if(proxyInput){ state.settings.corsProxy = proxyInput.value.trim(); }
saveState();
const status = form.querySelector('#prefsStatus'); if(status) status.textContent='Saved';
setTimeout(()=> back(), 300);
}, { once:true });
form.querySelector('[data-action="back"]').addEventListener('click', back, { once:true });
}
if(id==='filterAndSortSettings'){
const form = root.querySelector('#filterForm');
populateFilters(form);
form?.addEventListener('submit', e=>{
e.preventDefault();
applyFilterForm(form);
renderArticles();
if(backStack.length){ history.back(); } else back();
});
form?.querySelector('[data-action="reset"]')?.addEventListener('click', ()=>{
Object.assign(currentFilters, { ...FILTER_DEFAULTS, tagList: [] });
populateFilters(form);
renderArticles();
});
form?.querySelector('[data-action="cancel"]')?.addEventListener('click', ()=>{
populateFilters(form); // revert any unsaved edits
if(backStack.length){ history.back(); } else back();
});
}
if(id==='articlesInfiniteScrollable'){
renderArticles();
root.querySelector('[data-action="quick-refresh"]').onclick = ()=> refreshAll(true);
root.querySelector('[data-action="open-filter"]').onclick = ()=> showPanel('filterAndSortSettings');
setupInfiniteScroll(root);
}
if(id==='articleViewer' && data){ renderArticleViewer(data); }
if(id==='videoViewer' && data){ renderVideoViewer(data); }
}
// ---------- Filters ----------
const SORT_DEFAULT = 'published-desc';
const SORT_OPTIONS = new Set(['published-desc','published-asc','title-asc','title-desc','feed-asc','feed-desc','host-asc','host-desc','favorite','unread']);
const MEDIA_AUTO_TAGS = ['audio','video'];
const FILTER_DEFAULTS = Object.freeze({ q:'', subscription:'', category:'', tag:'', tagList:[], unread:false, fav:false, readState:'', dateFrom:'', dateTo:'', sort: SORT_DEFAULT });
const currentFilters = { ...FILTER_DEFAULTS, tagList: [] }; // mutable runtime copy
function populateFilters(form){
if(!form) return;
const selSub = form.querySelector('#filterSubscription');
const selCat = form.querySelector('#filterCategory');
const tagWrap = form.querySelector('#filterTagsWrap');
const feeds = state.feeds.slice().sort((a,b)=> (a.title||a.url||'').localeCompare(b.title||b.url||''));
if(selSub){
selSub.innerHTML = '<option value="">All subscriptions</option>' + feeds.map(f=> `<option value="${f.id}">${esc(f.title||f.url)}</option>`).join('');
selSub.value = currentFilters.subscription || '';
}
const cats = Array.from(new Set(state.feeds.map(f=> f.category).filter(Boolean))).sort((a,b)=> a.localeCompare(b));
if(selCat){
selCat.innerHTML = '<option value="">All categories</option>' + cats.map(c=> `<option>${esc(c)}</option>`).join('');
selCat.value = currentFilters.category || '';
}
if(tagWrap){
const allTags = Array.from(new Set(Object.values(state.tags||{}).flat()))
.map(t=> (t||'').trim())
.filter(Boolean)
.sort((a,b)=> a.localeCompare(b));
tagWrap.innerHTML='';
const baseSelections = Array.isArray(currentFilters.tagList) && currentFilters.tagList.length ? currentFilters.tagList : (currentFilters.tag? [currentFilters.tag]:[]);
const selected = new Set(baseSelections.map(t=> (t||'').trim()).filter(Boolean));
if(!allTags.length){
tagWrap.append(el('span',{class:'muted'},'No tags yet.'));
} else {
allTags.forEach(t=>{
const isSelected = selected.has(t);
const btn = el('button',{type:'button',class:'tag-toggle'+(isSelected?' is-selected':''), 'data-tag':t, 'aria-pressed':isSelected?'true':'false'}, t);
btn.addEventListener('click',()=>{
const active = !btn.classList.contains('is-selected');
btn.classList.toggle('is-selected', active);
btn.setAttribute('aria-pressed', active?'true':'false');
});
tagWrap.append(btn);
});
}
}
const sortSelect = form.querySelector('#filterSort');
if(sortSelect){
const value = SORT_OPTIONS.has(currentFilters.sort) ? currentFilters.sort : SORT_DEFAULT;
sortSelect.value = value;
}
const searchInput = form.querySelector('#filterSearch'); if(searchInput) searchInput.value = currentFilters.q || '';
const favOnly = form.querySelector('input[name="favOnly"]'); if(favOnly) favOnly.checked = !!currentFilters.fav;
const readStateInputs = form.querySelectorAll('input[name="readState"]');
const desired = currentFilters.readState ? currentFilters.readState : (currentFilters.unread? 'unread':'all');
readStateInputs.forEach(r=>{ r.checked = (r.value === (desired||'all')); });
const fromInput = form.querySelector('#filterDateFrom'); if(fromInput) fromInput.value = currentFilters.dateFrom || '';
const toInput = form.querySelector('#filterDateTo'); if(toInput) toInput.value = currentFilters.dateTo || '';
}
function applyFilterForm(form){
if(!form) return;
const data = new FormData(form);
const q = (data.get('q')||'').toString().trim();
const subscription = (data.get('subscription')||'').toString();
const category = (data.get('category')||'').toString();
const favOnlyInput = form.querySelector('input[name="favOnly"]');
const fav = !!(favOnlyInput && favOnlyInput.checked);
const readStateRaw = (data.get('readState')||'all').toString();
const readState = readStateRaw==='all'? '' : readStateRaw;
const unread = readState==='unread';
const tagWrap = form.querySelector('#filterTagsWrap');
const tagSelection = tagWrap ? [...tagWrap.querySelectorAll('.tag-toggle.is-selected')].map(btn=> (btn.dataset.tag||'').trim()).filter(Boolean) : [];
const tagList = Array.from(new Set(tagSelection));
const dateFrom = (data.get('dateFrom')||'').toString();
const dateTo = (data.get('dateTo')||'').toString();
const sortRaw = (data.get('sort')||SORT_DEFAULT).toString();
const sort = SORT_OPTIONS.has(sortRaw)? sortRaw : SORT_DEFAULT;
currentFilters.q = q;
currentFilters.subscription = subscription;
currentFilters.category = category;
currentFilters.fav = fav;
currentFilters.readState = readState;
currentFilters.unread = unread;
currentFilters.tagList = tagList;
currentFilters.tag = tagList.length===1 ? tagList[0] : '';
currentFilters.dateFrom = dateFrom;
currentFilters.dateTo = dateTo;
currentFilters.sort = sort;
}
function getFilteredPosts(){
const feedMap = new Map(state.feeds.map(f=> [f.id,f]));
const hostCache = new Map();
const getHost = (post)=>{
if(hostCache.has(post.id)) return hostCache.get(post.id);
const host = safeHost(post.link||'') || '';
hostCache.set(post.id, host);
return host;
};
const getFeedTitle = (feedId)=>{
const feed = feedMap.get(feedId);
return (feed?.title || feed?.url || '').trim();
};
const getPublishedTime = (post)=>{
const ts = new Date(post.published||post.updated||0).getTime();
return isNaN(ts)? 0 : ts;
};
const fallbackCompare = (a,b)=>{
const diff = getPublishedTime(b) - getPublishedTime(a);
if(diff) return diff;
const titleDiff = (a.title||'').localeCompare(b.title||'', undefined, { sensitivity:'base', numeric:true });
if(titleDiff) return titleDiff;
return (a.id||'').localeCompare(b.id||'');
};
let arr = Object.values(posts);
if(currentFilters.subscription){
arr = arr.filter(p=> p.feedId === currentFilters.subscription);
}
if(currentFilters.category){
arr = arr.filter(p=> (feedMap.get(p.feedId)?.category||'') === currentFilters.category);
}
if(currentFilters.unread){
arr = arr.filter(p=> !p.read);
}
if(currentFilters.fav){
arr = arr.filter(p=> p.favorite);
}
if(currentFilters.readState === 'read'){
arr = arr.filter(p=> p.read);
}
if(currentFilters.readState === 'unread'){
arr = arr.filter(p=> !p.read);
}
const tagList = (currentFilters.tagList&¤tFilters.tagList.length)? currentFilters.tagList : [];
if(tagList.length){
arr = arr.filter(p=>{
const tags = state.tags[p.id]||[];
return tagList.some(t=> tags.includes(t));
});
} else if(currentFilters.tag){
arr = arr.filter(p=> (state.tags[p.id]||[]).includes(currentFilters.tag));
}
const fromTime = currentFilters.dateFrom ? new Date(currentFilters.dateFrom).getTime() : NaN;
const toTime = currentFilters.dateTo ? new Date(currentFilters.dateTo).getTime() : NaN;
if(!isNaN(fromTime)){
arr = arr.filter(p=>{
const tp = new Date(p.published||p.updated||0).getTime();
return !isNaN(tp) && tp >= fromTime;
});
}
if(!isNaN(toTime)){
const inclusiveTo = toTime + 24*60*60*1000 - 1;
arr = arr.filter(p=>{
const tp = new Date(p.published||p.updated||0).getTime();
return !isNaN(tp) && tp <= inclusiveTo;
});
}
if(currentFilters.q){
const q = currentFilters.q.toLowerCase();
arr = arr.filter(p=> (p.title||'').toLowerCase().includes(q) || (p.summary||'').toLowerCase().includes(q));
}
const sortKey = SORT_OPTIONS.has(currentFilters.sort) ? currentFilters.sort : SORT_DEFAULT;
arr.sort((a,b)=>{
switch(sortKey){
case 'published-asc':{
const diff = getPublishedTime(a) - getPublishedTime(b);
if(diff) return diff;
break;
}
case 'title-asc':
case 'title-desc':{
const dir = sortKey==='title-asc'? 1 : -1;
const diff = (a.title||'').localeCompare(b.title||'', undefined, { sensitivity:'base', numeric:true });
if(diff) return dir * diff;
break;
}
case 'feed-asc':
case 'feed-desc':{
const dir = sortKey==='feed-asc'? 1 : -1;
const diff = getFeedTitle(a.feedId).localeCompare(getFeedTitle(b.feedId), undefined, { sensitivity:'base', numeric:true });
if(diff) return dir * diff;
break;
}
case 'host-asc':
case 'host-desc':{
const dir = sortKey==='host-asc'? 1 : -1;
const diff = getHost(a).localeCompare(getHost(b), undefined, { sensitivity:'base', numeric:true });
if(diff) return dir * diff;
break;
}
case 'favorite':{
const diff = Number(b.favorite) - Number(a.favorite);
if(diff) return diff;
break;
}
case 'unread':{
if(a.read !== b.read) return a.read ? 1 : -1;
break;
}
case 'published-desc':
default:
break;
}
return fallbackCompare(a,b);
});
return arr;
}
// ---------- Articles List ----------
function renderArticles(){
const panel = stackEl.querySelector('[data-panel="articlesInfiniteScrollable"]'); if(!panel) return;
const list = panel.querySelector('#articlesList'); if(!list) return;
const filtered = getFilteredPosts();
lastFilteredPosts = filtered;
const total = filtered.length;
const emptyMessage = isInitialLoading ? 'Loading articles…' : 'No articles match these filters.';
if(suspendListRenders){
pendingListRefresh = true;
lastRenderedCount = Math.min(lastRenderedCount, total);
if(total===0){
if(!list.querySelector('.empty')){
list.innerHTML='';
list.append(el('div',{class:'empty'}, emptyMessage));
}
}
return;
}
pendingListRefresh = false;
list.innerHTML='';
if(!total){
list.append(el('div',{class:'empty'}, emptyMessage));
lastRenderedCount = 0;
return;
}
lastRenderedCount = 0;
renderNextArticleChunk(list, INITIAL_RENDER_COUNT);
ensureArticleListFilled(list);
}
function renderNextArticleChunk(list, count=CHUNK_SIZE){
if(!lastFilteredPosts.length) return 0;
const start = lastRenderedCount;
const end = Math.min(lastFilteredPosts.length, start + count);
for(let i=start; i<end; i++){
list.append(articleCard(lastFilteredPosts[i]));
}
lastRenderedCount = end;
return end - start;
}
function ensureArticleListFilled(list){
const frame = list._scrollFrame;
if(!frame) return;
const threshold = frame.clientHeight + 400;
let guard = 16;
while(lastRenderedCount < lastFilteredPosts.length && frame.scrollHeight <= threshold && guard-- > 0){
if(!renderNextArticleChunk(list)) break;
}
}
function articleCard(p){
const isFav = !!p.favorite;
const classes = ['card', p.read? 'read':'unread'];
if(isFav) classes.push('favorite');
const c = el('div',{class:classes.join(' '), role:'article', tabindex:0, 'data-post-id':p.id, 'aria-label': (p.title||'Article') + (p.read? ' (read)':' (unread)')});
const favBtn = el('button',{class:'fav', type:'button', title: isFav? 'Remove favourite':'Add favourite', 'aria-label': isFav? 'Remove favourite':'Add favourite', 'aria-pressed': String(isFav), 'data-post-id': p.id}, isFav? '★':'☆');
favBtn.addEventListener('click', (e)=>{
e.stopPropagation();
toggleFavorite(p.id);
});
c.append(favBtn);
const realImg = pickImage(p);
const mw = el('div',{class:'card-media'});
if(realImg){
const im = el('img',{src:realImg, alt:'', loading:'lazy', decoding:'async', referrerpolicy:'no-referrer'});
im.addEventListener('error', ()=>{
if(im.dataset.fallback) return;
im.dataset.fallback='1';
const svg = generateInlinePlaceholderSVG(p);
if(svg){ mw.innerHTML = svg; }
else { im.src = onePixelPng(); }
});
mw.append(im);
} else {
// No sync image found, show placeholder initially
mw.innerHTML = generateInlinePlaceholderSVG(p) || `<img src="${onePixelPng()}" alt="" loading="lazy" decoding="async">`;
// Try async image loading for Open Graph fallback
pickImageAsync(p).then(asyncImg => {
if(asyncImg && asyncImg !== realImg) {
// Replace placeholder with async image
const newIm = el('img',{src:asyncImg, alt:'', loading:'lazy', decoding:'async', referrerpolicy:'no-referrer'});
newIm.addEventListener('error', ()=>{
if(newIm.dataset.fallback) return;
newIm.dataset.fallback='1';
const svg = generateInlinePlaceholderSVG(p);
if(svg){ mw.innerHTML = svg; }
else { newIm.src = onePixelPng(); }
});
mw.innerHTML = '';
mw.append(newIm);
}
}).catch(() => {
// Async loading failed, keep placeholder
});
}
c.append(mw);
c.append(el('h3',{}, p.title||'(untitled)'));
const chips = el('div',{class:'chips'});
p.read = true;
state.read[p.id]=true;
const feed = state.feeds.find(f=> f.id===p.feedId);
if(feed){
const feedChip = el('button',{class:'chip feed-chip', title:'Filter by subscription','aria-label':'Filter by '+(feed.title||feed.url), onclick:(e)=>{ e.stopPropagation(); currentFilters.subscription=feed.id; renderArticles(); }}, feed.title||feed.url);
chips.append(feedChip);
if(feed.category){ const catChip = el('button',{class:'chip cat-chip', title:'Filter by category','aria-label':'Filter by category '+feed.category, onclick:(e)=>{ e.stopPropagation(); currentFilters.category=feed.category; renderArticles(); }}, feed.category); chips.append(catChip); }
}
// Tag chips (existing)
const tagList = state.tags[p.id]||[];
if(tagList.length){
tagList.forEach(t=> chips.append(createTagFilterChip(t)));
}
// Read state chip
const readChip = el('button',{class:'chip read-chip', title:'Quick filter by read state', 'aria-label': p.read? 'Filter unread':'Filter read', onclick:(e)=>{ e.stopPropagation(); currentFilters.readState = p.read? 'unread':'read'; renderArticles(); }}, p.read? 'Read':'Unread');
chips.append(readChip);
if(chips.children.length) c.append(chips);
const host = safeHost(p.link||'');
c.append(el('div',{class:'meta'}, [host,' • ',fmtDate(p.published)]));
c.append(el('div',{class:'excerpt'}, p.summary||stripHtml(p.content||'').slice(0,180)));
c.onclick = ()=>{ openArticle(p); };
c.addEventListener('keydown', e=>{ if(e.key==='Enter'||e.key===' '){ e.preventDefault(); openArticle(p);} });
return c;
}
let lastArticlesScroll = 0;
function rememberArticlesScroll(){
const panel = stackEl.querySelector('[data-panel="articlesInfiniteScrollable"]');
if(panel){ const body = panel.querySelector('.panel-body'); if(body) lastArticlesScroll = body.scrollTop; }
}
function restoreArticlesScroll(){
const panel = stackEl.querySelector('[data-panel="articlesInfiniteScrollable"]');
if(panel){ const body = panel.querySelector('.panel-body'); if(body) body.scrollTop = lastArticlesScroll; }
}
function openArticle(p){
rememberArticlesScroll();
showPanel('articleViewer', { data: p });
requestAnimationFrame(()=>{ const pv = stackEl.querySelector('[data-panel="articleViewer"] .panel-body'); if(pv) pv.scrollTop = 0; });
}
function renderSubscriptionsList(){
const body = byId('subsBody'); if(!body) return; body.innerHTML='';
if(!state.feeds.length){ body.append(el('div',{class:'empty'},'No subscriptions yet. Use + to add.')); return; }
const list = el('div',{class:'subs-list'});
state.feeds.sort((a,b)=> (a.category||'').localeCompare(b.category||'') || (a.title||'').localeCompare(b.title||'')).forEach(f=>{
const row = el('div',{class:'row'});
const titleBlock = el('strong',{}, f.title||f.url);
if(!isFeedEnabled(f)) titleBlock.append(el('span',{class:'muted', style:'margin-left:8px;'}, '(disabled)'));
const catLabel = el('span',{class:'muted'}, f.category? `(${f.category})`:'');
const actions = el('div',{class:'subs-actions'});
const editBtn = el('button',{title:'Edit subscription', 'aria-label':'Edit '+(f.title||f.url), onclick:()=>{ showPanel('subscriptionEdit', { data: f.id }); }}, 'Edit');
const delBtn = el('button',{title:'Remove subscription', 'aria-label':'Remove '+(f.title||f.url), onclick:()=>{ if(confirm('Remove this subscription?')){ removeSubscription(f.id); } }}, '🗑');
actions.append(editBtn, delBtn);
row.append(titleBlock, catLabel, actions);
list.append(row);
});
body.append(list);
}
function renderArticleViewer(p){
const body = byId('articleBody'); if(!body) return;
body.innerHTML='';
body.classList.add('article-viewer');
body.dataset.postId = p.id;
const feed = state.feeds.find(f=> f.id===p.feedId);
const heroUrl = pickImage(p);
const host = safeHost(p.link||'');
const published = fmtDate(p.published);
const publishedIso = (()=>{
const ts = Date.parse(p.published||'');
return isNaN(ts)? null : new Date(ts).toISOString();
})();
const readingStats = computeReadingStats(p);
const contextChips = el('div',{class:'chips article-context'}, []);
if(feed){
const feedChip = el('button',{class:'chip feed-chip', title:'Filter by subscription','aria-label':'Filter by '+(feed.title||feed.url), onclick:(e)=>{ e.stopPropagation(); currentFilters.subscription=feed.id; renderArticles(); }}, feed.title||feed.url);
contextChips.append(feedChip);
if(feed.category){
contextChips.append(el('button',{class:'chip cat-chip', title:'Filter by category','aria-label':'Filter by category '+feed.category, onclick:(e)=>{ e.stopPropagation(); currentFilters.category=feed.category; renderArticles(); }}, feed.category));
}
}
const readStateChip = el('button',{class:'chip read-chip', title:'Quick filter by read state','aria-label': p.read? 'Filter unread':'Filter read', onclick:(e)=>{ e.stopPropagation(); currentFilters.readState = p.read? 'unread':'read'; renderArticles(); }}, p.read? 'Read':'Unread');
contextChips.append(readStateChip);
const header = el('header',{class:'article-head'},[
contextChips,
el('h1',{class:'article-title', id:'articleViewerTitle'}, p.title||'(untitled)'),
el('div',{class:'article-meta'},[
published? el('span',{class:'meta-item'}, ['Published ', publishedIso? el('time',{datetime:publishedIso}, published) : published]) : null,
host? el('span',{class:'meta-item'}, ['Source ', host]) : null,
readingStats.minutes? el('span',{class:'meta-item'}, [`${readingStats.minutes} min read`, readingStats.words? ` • ${readingStats.words} words`:'' ]) : null
].filter(Boolean)),
(function(){
const actions = el('div',{class:'article-actions'});
const favBtn = el('button',{type:'button', class:'action-btn favorite-toggle', 'aria-pressed':'false', 'aria-label':'Add favourite', 'data-post-id':p.id});
const favIcon = svgIcon('#i-star');
const favLabel = el('span',{class:'favorite-toggle-label'},' Favourite');
favBtn.append(favIcon, favLabel);
favBtn.addEventListener('click', ()=>{
toggleFavorite(p.id);
syncArticleViewerFavoriteState(p.id);
});
actions.append(favBtn);
// compute a sensible original-article URL:
(function(){
let href = p.link || '';
// if no link or link is just a hash/empty, attempt to extract first anchor from content
try{
if(!href || href.trim()==='#' || href.trim()===''){
const dp = new DOMParser();
const doc = dp.parseFromString(p.content||'', 'text/html');
const a = doc.querySelector('a[href]');