-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
3149 lines (2811 loc) · 116 KB
/
Copy pathscript.js
File metadata and controls
3149 lines (2811 loc) · 116 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
// ============================================================
// Catalyst Score – Frontend Logic & Telemetry Engine
// ============================================================
const RECENT_AUDITS_KEY = 'catalyst_recent_audits';
// Helper: Fetch wrapper with error handling
async function fetchJSON(url, options = {}) {
const response = await fetch(url, {
headers: {
'Content-Type': 'application/json',
...(options.headers || {}),
},
...options,
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.error || `Request failed (${response.status})`);
}
return data;
}
// ============================================================
// LocalStorage: Recent Audits Management
// ============================================================
function getRecentAudits() {
try {
const raw = localStorage.getItem(RECENT_AUDITS_KEY);
return raw ? JSON.parse(raw) : [];
} catch (e) {
console.error('Failed to read recent audits from localStorage', e);
return [];
}
}
function saveRecentAudit(report) {
if (!report || !report.url) return;
try {
let audits = getRecentAudits();
// Remove existing entry for the same URL or ID if present
audits = audits.filter((a) => a.url !== report.url && a.id !== report.id);
// Add new audit entry at the beginning
const entry = {
id: report.id || Math.random().toString(36).substring(2, 10),
url: report.url,
final_url: report.final_url || report.url,
overall_score: report.overall_score,
grade: report.grade,
timestamp: report.timestamp || new Date().toISOString(),
fullReport: report
};
audits.unshift(entry);
// Keep max 25 audits
if (audits.length > 25) audits = audits.slice(0, 25);
localStorage.setItem(RECENT_AUDITS_KEY, JSON.stringify(audits));
} catch (e) {
console.error('Failed to save recent audit to localStorage', e);
}
}
function deleteRecentAudit(id) {
try {
let audits = getRecentAudits();
audits = audits.filter((a) => a.id !== id);
localStorage.setItem(RECENT_AUDITS_KEY, JSON.stringify(audits));
renderRecentAudits();
if (window.refreshRecentDomainsDropdown) {
window.refreshRecentDomainsDropdown();
}
} catch (e) {
console.error('Failed to delete recent audit', e);
}
}
function clearRecentAudits() {
if (confirm('Are you sure you want to clear all recent audits history?')) {
localStorage.removeItem(RECENT_AUDITS_KEY);
renderRecentAudits();
if (window.refreshRecentDomainsDropdown) {
window.refreshRecentDomainsDropdown();
}
}
}
function renderRecentAudits() {
const container = document.getElementById('recentAuditsList');
const clearBtn = document.getElementById('clearHistoryBtn');
const section = document.getElementById('recentAuditsSection');
if (!container) return;
const audits = getRecentAudits();
if (!audits || audits.length === 0) {
container.innerHTML = `
<div class="empty-state" style="grid-column: 1 / -1; padding: 2rem 1rem; text-align: center; background: #ffffff; border: 1px dashed var(--border-color); border-radius: var(--radius-lg);">
<p style="color: var(--text-muted); font-size: 0.95rem;">No recent audits in local storage yet. Enter a website URL above to generate your first health intelligence report.</p>
</div>
`;
if (clearBtn) clearBtn.style.display = 'none';
return;
}
if (clearBtn) clearBtn.style.display = 'inline-block';
container.innerHTML = audits.map((audit) => {
const formattedDate = formatTimestamp(audit.timestamp);
const gradeClass = `grade-${audit.grade}`;
const scoreColorClass = audit.overall_score >= 90 ? 'score-good' : (audit.overall_score >= 70 ? 'score-warn' : 'score-bad');
let displayHost = audit.url;
try {
displayHost = new URL(audit.url).hostname.replace(/^www\./i, '');
} catch {}
const faviconUrl = `https://www.google.com/s2/favicons?domain=${encodeURIComponent(displayHost)}&sz=32`;
return `
<div class="recent-audit-card">
<div class="recent-card-top">
<div style="display:flex; align-items:center; gap:0.5rem; min-width:0; flex:1;">
<img src="${faviconUrl}" alt="" style="width:20px; height:20px; border-radius:4px; flex-shrink:0;" onerror="this.style.display='none'">
<a href="#" class="recent-card-url" data-id="${escapeHtml(audit.id)}" title="${escapeHtml(audit.url)}">${escapeHtml(displayHost)}</a>
</div>
<div class="recent-card-score">
<span class="recent-score-pill ${scoreColorClass}">${audit.overall_score}</span>
<span class="grade ${gradeClass}" style="font-size:0.8rem; padding:0.15rem 0.5rem;">${audit.grade}</span>
</div>
</div>
<div class="recent-card-date">🕒 ${formattedDate}</div>
<div class="recent-card-actions">
<div style="display:flex; gap:0.4rem;">
<button class="btn btn-secondary btn-sm btn-view-report" data-id="${escapeHtml(audit.id)}">View Report</button>
<a href="/compare.html?urlA=${encodeURIComponent(audit.url)}" class="btn btn-secondary btn-sm">VS Compare</a>
</div>
<button class="btn-icon btn-delete-audit" data-id="${escapeHtml(audit.id)}" title="Delete from history">🗑️</button>
</div>
</div>
`;
}).join('');
// Attach event handlers
container.querySelectorAll('.btn-view-report, .recent-card-url').forEach((el) => {
el.addEventListener('click', (e) => {
e.preventDefault();
const id = el.getAttribute('data-id');
const audit = audits.find((a) => a.id === id);
if (audit && audit.fullReport) {
sessionStorage.setItem('catalystReport', JSON.stringify(audit.fullReport));
window.location.href = '/reports/' + id;
} else if (audit) {
window.location.href = `/reports/${id}`;
}
});
});
container.querySelectorAll('.btn-delete-audit').forEach((el) => {
el.addEventListener('click', (e) => {
e.stopPropagation();
const id = el.getAttribute('data-id');
deleteRecentAudit(id);
});
});
}
// ============================================================
// Autocomplete: Recent Domains Suggestions Engine
// ============================================================
function initRecentDomainsAutocomplete() {
const urlInput = document.getElementById('urlInput');
const dropdown = document.getElementById('recentDomainsDropdown');
const clearBtn = document.getElementById('clearUrlInputBtn');
if (!urlInput || !dropdown) return;
let activeIndex = -1;
let currentMatches = [];
function parseUrlDetails(rawUrl) {
try {
let formatted = rawUrl.trim();
if (!/^https?:\/\//i.test(formatted)) {
formatted = 'https://' + formatted;
}
const parsed = new URL(formatted);
const host = parsed.hostname.replace(/^www\./i, '');
const path = parsed.pathname !== '/' ? parsed.pathname : '';
return {
host: host || rawUrl,
fullDisplay: host + path,
url: rawUrl,
origin: parsed.origin
};
} catch {
return {
host: rawUrl,
fullDisplay: rawUrl,
url: rawUrl,
origin: ''
};
}
}
function getFormattedRecentList() {
const rawAudits = getRecentAudits();
const seen = new Set();
const results = [];
// Fallback sample domains for first-time onboarding
const sampleDomains = [
{ url: 'https://stripe.com', host: 'stripe.com', overall_score: 96, grade: 'A', isSample: true },
{ url: 'https://github.com', host: 'github.com', overall_score: 91, grade: 'A', isSample: true },
{ url: 'https://apple.com', host: 'apple.com', overall_score: 88, grade: 'B', isSample: true },
{ url: 'https://wikipedia.org', host: 'wikipedia.org', overall_score: 84, grade: 'B', isSample: true }
];
for (const audit of rawAudits) {
if (!audit || !audit.url) continue;
const details = parseUrlDetails(audit.url);
const key = details.fullDisplay.toLowerCase();
if (!seen.has(key)) {
seen.add(key);
results.push({
id: audit.id,
url: audit.url,
host: details.host,
fullDisplay: details.fullDisplay,
overall_score: audit.overall_score,
grade: audit.grade,
timestamp: audit.timestamp,
isSample: false
});
}
}
if (results.length === 0) {
return sampleDomains.map((s) => ({
id: null,
url: s.url,
host: s.host,
fullDisplay: s.host,
overall_score: s.overall_score,
grade: s.grade,
timestamp: null,
isSample: true
}));
}
return results;
}
function highlightMatch(text, query) {
if (!query) return escapeHtml(text);
const escapedQuery = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const regex = new RegExp(`(${escapedQuery})`, 'gi');
return escapeHtml(text).replace(regex, '<mark class="domain-match-hl">$1</mark>');
}
function formatRelativeTime(isoString) {
if (!isoString) return '';
try {
const now = new Date();
const past = new Date(isoString);
const diffMs = now - past;
const diffSec = Math.floor(diffMs / 1000);
const diffMin = Math.floor(diffSec / 60);
const diffHour = Math.floor(diffMin / 60);
const diffDay = Math.floor(diffHour / 24);
if (diffSec < 60) return 'Just now';
if (diffMin < 60) return `${diffMin}m ago`;
if (diffHour < 24) return `${diffHour}h ago`;
if (diffDay < 7) return `${diffDay}d ago`;
return past.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
} catch {
return '';
}
}
function renderDropdown(query = '') {
const trimmedQuery = query.trim().toLowerCase();
const allDomains = getFormattedRecentList();
const hasHistory = allDomains.some((d) => !d.isSample);
if (trimmedQuery) {
currentMatches = allDomains.filter(
(d) =>
d.fullDisplay.toLowerCase().includes(trimmedQuery) ||
d.url.toLowerCase().includes(trimmedQuery)
);
} else {
currentMatches = allDomains.slice(0, 8);
}
if (clearBtn) {
clearBtn.style.display = urlInput.value ? 'flex' : 'none';
}
if (currentMatches.length === 0) {
dropdown.innerHTML = `
<div class="dropdown-header">
<div class="dropdown-header-left">
<span>🔍 Recent History</span>
<span class="dropdown-badge">0 found</span>
</div>
</div>
<div class="dropdown-empty">
<div class="dropdown-empty-icon">🌐</div>
<div>No saved audits match "<strong>${escapeHtml(query)}</strong>"</div>
<div style="font-size:0.75rem; color:var(--text-muted); margin-top:0.35rem;">Press <kbd>Enter</kbd> or click <em>Analyze Health</em> to run a new audit.</div>
</div>
`;
dropdown.style.display = 'flex';
urlInput.setAttribute('aria-expanded', 'true');
return;
}
const headerTitle = trimmedQuery
? 'Matching Domains'
: hasHistory
? 'Recent Domains from Storage'
: 'Recommended Starter Domains';
const badgeText = `${currentMatches.length} ${currentMatches.length === 1 ? 'domain' : 'domains'}`;
let html = `
<div class="dropdown-header">
<div class="dropdown-header-left">
<span>🕒 ${headerTitle}</span>
<span class="dropdown-badge">${badgeText}</span>
</div>
${hasHistory ? '<button type="button" class="dropdown-clear-btn" id="dropdownClearAllBtn" title="Clear all recent history">Clear History</button>' : ''}
</div>
<ul class="dropdown-list" role="listbox">
`;
currentMatches.forEach((item, index) => {
const score = item.overall_score !== undefined ? item.overall_score : null;
let scoreColorClass = 'score-good';
if (score !== null && score < 70) scoreColorClass = 'score-bad';
else if (score !== null && score < 90) scoreColorClass = 'score-warn';
const highlightedDisplay = highlightMatch(item.fullDisplay, trimmedQuery);
const relativeTime = formatRelativeTime(item.timestamp);
const isActive = index === activeIndex;
const faviconUrl = `https://www.google.com/s2/favicons?domain=${encodeURIComponent(item.host)}&sz=32`;
html += `
<li
class="dropdown-item ${isActive ? 'active' : ''}"
data-index="${index}"
data-url="${escapeHtml(item.url)}"
role="option"
aria-selected="${isActive}"
id="recent-domain-opt-${index}"
>
<div class="dropdown-item-main">
<img
src="${faviconUrl}"
alt=""
class="dropdown-favicon"
onerror="this.style.display='none'; if(this.nextElementSibling) this.nextElementSibling.style.display='inline-flex';"
>
<span class="dropdown-favicon" style="display:none;">🌐</span>
<div class="dropdown-text-group">
<div class="dropdown-domain">${highlightedDisplay}</div>
<div class="dropdown-meta">
<span>${escapeHtml(item.url)}</span>
${relativeTime ? `<span>• ${relativeTime}</span>` : ''}
${item.isSample ? '<span style="color:var(--primary); font-weight:700;">• Sample</span>' : ''}
</div>
</div>
</div>
<div class="dropdown-item-actions">
${score !== null ? `
<span class="dropdown-score-pill ${scoreColorClass}">
<strong>${score}</strong>
${item.grade ? `<span class="dropdown-grade-pill grade-${item.grade}">${item.grade}</span>` : ''}
</span>
` : ''}
<span class="dropdown-select-hint">Select ↵</span>
${!item.isSample && item.id ? `
<button
type="button"
class="dropdown-delete-btn"
data-delete-id="${escapeHtml(item.id)}"
title="Remove from history"
aria-label="Remove ${escapeHtml(item.host)} from history"
>✕</button>
` : ''}
</div>
</li>
`;
});
html += `
</ul>
<div class="dropdown-footer">
<span><kbd>↑</kbd> <kbd>↓</kbd> Navigate</span>
<span><kbd>↵</kbd> Select</span>
<span><kbd>Esc</kbd> Dismiss</span>
</div>
`;
dropdown.innerHTML = html;
dropdown.style.display = 'flex';
urlInput.setAttribute('aria-expanded', 'true');
// Attach clear history listener
const clearAllBtn = dropdown.querySelector('#dropdownClearAllBtn');
if (clearAllBtn) {
clearAllBtn.addEventListener('click', (e) => {
e.stopPropagation();
clearRecentAudits();
renderDropdown(urlInput.value);
});
}
// Attach individual delete listeners
dropdown.querySelectorAll('.dropdown-delete-btn').forEach((btn) => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
const idToDelete = btn.getAttribute('data-delete-id');
if (idToDelete) {
deleteRecentAudit(idToDelete);
renderDropdown(urlInput.value);
}
});
});
// Attach item selection listeners
dropdown.querySelectorAll('.dropdown-item').forEach((itemEl) => {
itemEl.addEventListener('click', (e) => {
if (e.target.closest('.dropdown-delete-btn')) return;
const selectedUrl = itemEl.getAttribute('data-url');
selectDomain(selectedUrl);
});
});
}
function selectDomain(url) {
if (!url) return;
urlInput.value = url;
closeDropdown();
if (clearBtn) clearBtn.style.display = 'flex';
urlInput.focus();
}
function openDropdown() {
activeIndex = -1;
renderDropdown(urlInput.value);
}
function closeDropdown() {
dropdown.style.display = 'none';
urlInput.setAttribute('aria-expanded', 'false');
activeIndex = -1;
}
function updateActiveOption() {
const items = dropdown.querySelectorAll('.dropdown-item');
items.forEach((el, idx) => {
if (idx === activeIndex) {
el.classList.add('active');
el.setAttribute('aria-selected', 'true');
el.scrollIntoView({ block: 'nearest' });
urlInput.setAttribute('aria-activedescendant', el.id);
} else {
el.classList.remove('active');
el.setAttribute('aria-selected', 'false');
}
});
}
// --- Event Listeners ---
urlInput.addEventListener('input', () => {
activeIndex = -1;
renderDropdown(urlInput.value);
});
urlInput.addEventListener('focus', () => {
openDropdown();
});
urlInput.addEventListener('click', () => {
if (dropdown.style.display === 'none') {
openDropdown();
}
});
urlInput.addEventListener('keydown', (e) => {
if (dropdown.style.display === 'none') {
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
openDropdown();
e.preventDefault();
}
return;
}
if (e.key === 'ArrowDown') {
e.preventDefault();
if (currentMatches.length > 0) {
activeIndex = (activeIndex + 1) % currentMatches.length;
updateActiveOption();
}
} else if (e.key === 'ArrowUp') {
e.preventDefault();
if (currentMatches.length > 0) {
activeIndex = (activeIndex - 1 + currentMatches.length) % currentMatches.length;
updateActiveOption();
}
} else if (e.key === 'Enter') {
if (activeIndex >= 0 && activeIndex < currentMatches.length) {
e.preventDefault();
const selected = currentMatches[activeIndex];
selectDomain(selected.url);
}
} else if (e.key === 'Escape') {
e.preventDefault();
closeDropdown();
} else if (e.key === 'Tab') {
closeDropdown();
}
});
if (clearBtn) {
clearBtn.addEventListener('click', () => {
urlInput.value = '';
clearBtn.style.display = 'none';
urlInput.focus();
renderDropdown('');
});
}
document.addEventListener('click', (e) => {
if (
!urlInput.contains(e.target) &&
!dropdown.contains(e.target) &&
(!clearBtn || !clearBtn.contains(e.target))
) {
closeDropdown();
}
});
window.refreshRecentDomainsDropdown = function () {
if (dropdown.style.display !== 'none') {
renderDropdown(urlInput.value);
}
};
}
// ============================================================
// Granular Audit Progress & Real-Time Telemetry Controller
// ============================================================
const AUDIT_DIMENSIONS_CONFIG = [
{ key: 'seo', name: 'SEO Architecture', icon: '🔍', desc: 'Title, meta, headings & crawler indexability' },
{ key: 'security', name: 'Security & SecOps', icon: '🛡️', desc: 'HTTPS, HSTS, CSP, X-Frame & TLS security' },
{ key: 'performance', name: 'Performance & Vitals', icon: '⚡', desc: 'Core Web Vitals, LCP, CLS & load timing' },
{ key: 'mobile', name: 'Mobile & Touch', icon: '📱', desc: 'Viewport meta, touch targets & responsiveness' },
{ key: 'accessibility', name: 'Accessibility (WCAG)', icon: '♿', desc: 'Alt text, ARIA landmarks, contrast & labels' },
{ key: 'social', name: 'Social Graph & OG', icon: '🌐', desc: 'Open Graph, Twitter cards & preview metadata' },
{ key: 'ethical', name: 'Digital Ethics & Green', icon: '🌱', desc: 'Carbon footprint, sustainability & trackers' },
{ key: 'web_standards', name: 'Web Standards & HTML5', icon: '📐', desc: 'HTML5 DOCTYPE, DOM tree depth & validity' },
{ key: 'ai_readiness', name: 'AI & LLM Readiness', icon: '🤖', desc: 'llms.txt, MCP agent endpoints & schemas' },
{ key: 'ux_ecosystem', name: 'UX & Ecosystem', icon: '✨', desc: 'PWA manifest, modern stack & resource hints' }
];
class GranularProgressController {
constructor(options = {}) {
this.container = options.container || document.getElementById('loading');
this.titleEl = options.titleEl || document.getElementById('progressStatusTitle');
this.subEl = options.subEl || document.getElementById('progressStatusSub');
this.elapsedEl = options.elapsedEl || document.getElementById('progressElapsedTime');
this.percentEl = options.percentEl || document.getElementById('progressPercentText');
this.progressBarFill = options.progressBarFill || document.getElementById('auditProgressBarFill');
this.gridEl = options.gridEl || document.getElementById('dimensionProgressGrid');
this.logEl = options.logEl || document.getElementById('telemetryLogText');
this.prefix = options.idPrefix || 'dimCard_';
this.startTime = 0;
this.timerInterval = null;
this.currentPercent = 0;
this.completedCount = 0;
this.totalCount = 10;
}
initGrid() {
if (!this.gridEl) return;
this.gridEl.innerHTML = '';
AUDIT_DIMENSIONS_CONFIG.forEach((dim) => {
const card = document.createElement('div');
card.id = `${this.prefix}${dim.key}`;
card.className = 'dimension-progress-card state-pending';
card.innerHTML = `
<div class="dim-card-left">
<span class="dim-card-icon" aria-hidden="true">${dim.icon}</span>
<div class="dim-card-text">
<span class="dim-card-title">${dim.name}</span>
<span class="dim-card-desc">${dim.desc}</span>
</div>
</div>
<div class="dim-card-status">
<span class="dim-status-pill pill-pending">○ Queued</span>
</div>
`;
this.gridEl.appendChild(card);
});
}
start(targetUrl) {
if (this.container) this.container.style.display = 'flex';
this.initGrid();
this.startTime = Date.now();
this.currentPercent = 4;
this.completedCount = 0;
this.updateProgress(4, `Auditing ${targetUrl}…`, 'Evaluating 10 core health dimensions in real-time');
this.log(`Initiated telemetry audit connection for ${targetUrl}`);
if (this.timerInterval) clearInterval(this.timerInterval);
this.timerInterval = setInterval(() => {
if (this.elapsedEl) {
const elapsedSec = ((Date.now() - this.startTime) / 1000).toFixed(1);
this.elapsedEl.textContent = `${elapsedSec}s`;
}
}, 100);
}
setDimensionActive(key, customMessage) {
const card = document.getElementById(`${this.prefix}${key}`);
const dim = AUDIT_DIMENSIONS_CONFIG.find((d) => d.key === key);
if (card && !card.classList.contains('state-completed')) {
card.className = 'dimension-progress-card state-active';
const statusEl = card.querySelector('.dim-card-status');
if (statusEl) {
statusEl.innerHTML = `<span class="dim-status-pill pill-active">● Scanning...</span>`;
}
}
if (dim) {
this.log(customMessage || `Scanning ${dim.name}...`);
if (this.subEl) this.subEl.textContent = `Evaluating ${dim.name} (${dim.desc})`;
}
}
setDimensionComplete(key, score, status, detail) {
const card = document.getElementById(`${this.prefix}${key}`);
const dim = AUDIT_DIMENSIONS_CONFIG.find((d) => d.key === key);
this.completedCount = Math.min(10, this.completedCount + 1);
if (card) {
card.className = 'dimension-progress-card state-completed';
const statusEl = card.querySelector('.dim-card-status');
if (statusEl) {
const numericScore = typeof score === 'number' ? Math.round(score) : (score || 0);
const pillClass = numericScore >= 90 ? 'pill-pass' : (numericScore >= 70 ? 'pill-warn' : 'pill-fail');
const badgeIcon = numericScore >= 90 ? '✓' : (numericScore >= 70 ? '▲' : '✕');
statusEl.innerHTML = `<span class="dim-status-pill ${pillClass}">${badgeIcon} ${numericScore}/100</span>`;
}
if (detail) {
const descEl = card.querySelector('.dim-card-desc');
if (descEl) descEl.textContent = detail;
}
}
const newPercent = Math.min(96, Math.round(10 + (this.completedCount / 10) * 85));
const titleMsg = `Audited ${this.completedCount}/10 Dimensions (${dim ? dim.name : key} complete)`;
this.updateProgress(newPercent, titleMsg, `${10 - this.completedCount} dimensions remaining…`);
this.log(`[PASS ${score}/100] ${dim ? dim.name : key}: ${detail || 'Dimension verified'}`);
}
updateProgress(percent, title, sub) {
this.currentPercent = Math.max(this.currentPercent, percent);
if (this.progressBarFill) {
this.progressBarFill.style.width = `${this.currentPercent}%`;
}
if (this.percentEl) {
this.percentEl.textContent = `${this.currentPercent}%`;
}
if (this.titleEl && title) {
this.titleEl.textContent = title;
}
if (this.subEl && sub) {
this.subEl.textContent = sub;
}
}
log(msg) {
if (this.logEl) {
this.logEl.textContent = msg;
}
}
finish(report) {
this.updateProgress(100, 'Audit Complete!', 'Compiling 10-dimension health radar benchmarks…');
this.log(`All 10 dimensions finalized — Overall Score: ${report.overall_score}/100 (Grade ${report.grade})`);
if (this.timerInterval) {
clearInterval(this.timerInterval);
this.timerInterval = null;
}
}
stop() {
if (this.timerInterval) {
clearInterval(this.timerInterval);
this.timerInterval = null;
}
if (this.container) {
this.container.style.display = 'none';
}
}
}
async function executeAuditWithLiveStream(targetUrl, progressController) {
progressController.start(targetUrl);
return new Promise((resolve, reject) => {
let resolved = false;
let sse = null;
let fallbackTimer = null;
const fallbackToStandardFetch = async () => {
if (resolved) return;
if (sse) {
try { sse.close(); } catch(e) {}
sse = null;
}
try {
let simIdx = 0;
const simInterval = setInterval(() => {
if (resolved || simIdx >= AUDIT_DIMENSIONS_CONFIG.length) {
clearInterval(simInterval);
return;
}
const currentDim = AUDIT_DIMENSIONS_CONFIG[simIdx];
progressController.setDimensionActive(currentDim.key);
simIdx++;
}, 800);
const report = await fetchJSON('/api/analyze', {
method: 'POST',
body: JSON.stringify({ url: targetUrl })
});
clearInterval(simInterval);
if (!resolved) {
resolved = true;
Object.keys(report.categories || {}).forEach((catKey) => {
const cat = report.categories[catKey];
progressController.setDimensionComplete(catKey, cat.score, 'pass', `${cat.issues?.length || 0} checks evaluated`);
});
progressController.finish(report);
resolve(report);
}
} catch (err) {
if (!resolved) {
resolved = true;
reject(err);
}
}
};
if (typeof EventSource !== 'undefined') {
try {
const streamUrl = `/api/analyze-stream?url=${encodeURIComponent(targetUrl)}`;
sse = new EventSource(streamUrl);
// Safety fallback if SSE doesn't respond within 4s
fallbackTimer = setTimeout(() => {
if (!resolved && progressController.completedCount === 0) {
console.log('SSE connection slow/quiet, initiating parallel fetch fallback');
fallbackToStandardFetch();
}
}, 4000);
sse.onmessage = (event) => {
if (fallbackTimer) {
clearTimeout(fallbackTimer);
fallbackTimer = null;
}
try {
const data = JSON.parse(event.data);
if (data.type === 'init') {
progressController.updateProgress(data.percent || 5, 'Connecting to Diagnostic Engine…', data.message);
progressController.log(data.message);
} else if (data.type === 'step_start' || data.type === 'step_complete') {
progressController.updateProgress(data.percent || 10, 'Fetching Web Assets…', data.message);
progressController.log(data.message);
} else if (data.type === 'dimension_start') {
progressController.setDimensionActive(data.dimension, data.message);
} else if (data.type === 'dimension_complete') {
progressController.setDimensionComplete(data.dimension, data.score, data.status, data.detail);
} else if (data.type === 'cached_hit') {
progressController.log(data.message);
if (!resolved) {
resolved = true;
sse.close();
Object.keys(data.report.categories || {}).forEach((catKey) => {
const cat = data.report.categories[catKey];
progressController.setDimensionComplete(catKey, cat.score, 'pass', `${cat.issues?.length || 0} checks evaluated`);
});
progressController.finish(data.report);
resolve(data.report);
}
} else if (data.type === 'complete') {
if (!resolved) {
resolved = true;
sse.close();
progressController.finish(data.report);
resolve(data.report);
}
} else if (data.type === 'error') {
if (!resolved) {
resolved = true;
sse.close();
reject(new Error(data.error || 'Audit stream error'));
}
}
} catch (e) {
console.warn('Error parsing SSE event:', e);
}
};
sse.onerror = (err) => {
console.warn('SSE stream error, transitioning to standard fetch:', err);
fallbackToStandardFetch();
};
} catch (e) {
fallbackToStandardFetch();
}
} else {
fallbackToStandardFetch();
}
});
}
// ============================================================
// Homepage (index.html) – Handle form submission & load history
// ============================================================
const analyzeForm = document.getElementById('analyzeForm');
if (analyzeForm) {
// Initialize recent domains autocomplete dropdown
initRecentDomainsAutocomplete();
// Render history on home page
renderRecentAudits();
const clearBtn = document.getElementById('clearHistoryBtn');
if (clearBtn) {
clearBtn.addEventListener('click', clearRecentAudits);
}
// Instantiate Granular Progress Controller for Homepage
const homeProgress = new GranularProgressController({
container: document.getElementById('loading'),
titleEl: document.getElementById('progressStatusTitle'),
subEl: document.getElementById('progressStatusSub'),
elapsedEl: document.getElementById('progressElapsedTime'),
percentEl: document.getElementById('progressPercentText'),
progressBarFill: document.getElementById('auditProgressBarFill'),
gridEl: document.getElementById('dimensionProgressGrid'),
logEl: document.getElementById('telemetryLogText'),
idPrefix: 'dimCard_'
});
if (analyzeForm) analyzeForm.addEventListener('submit', async function (e) {
e.preventDefault();
const urlInput = document.getElementById('urlInput');
const errorDiv = document.getElementById('error');
const submitBtn = document.getElementById('analyzeBtn');
const rawUrl = urlInput.value.trim();
if (!rawUrl) {
errorDiv.textContent = 'Please enter a valid website URL.';
errorDiv.style.display = 'block';
return;
}
let urlToAnalyze = rawUrl;
if (!/^https?:\/\//i.test(urlToAnalyze)) {
urlToAnalyze = 'https://' + urlToAnalyze;
}
errorDiv.style.display = 'none';
submitBtn.disabled = true;
submitBtn.textContent = 'Auditing…';
try {
const report = await executeAuditWithLiveStream(urlToAnalyze, homeProgress);
// Save to localStorage recent history
saveRecentAudit(report);
// Store report in sessionStorage for the report page
sessionStorage.setItem('catalystReport', JSON.stringify(report));
// Brief delay to appreciate the complete 100% state before navigation
setTimeout(() => {
window.location.href = '/reports/' + report.id;
}, 500);
} catch (error) {
homeProgress.stop();
errorDiv.textContent = 'Error: ' + error.message;
errorDiv.style.display = 'block';
submitBtn.disabled = false;
submitBtn.textContent = 'Analyze Health';
}
});
}
// ============================================================
// Report Page (report.html) – Filter, Radar Chart & PDF Export
// ============================================================
const ALL_CATEGORY_KEYS = [
'seo', 'security', 'performance', 'mobile', 'accessibility',
'social', 'ethical', 'web_standards', 'ai_readiness', 'ux_ecosystem'
];
let currentReportData = null;
let currentRadarChart = null;
let activeCategories = new Set(ALL_CATEGORY_KEYS);
let activeStatusFilter = 'all';
let activeSearchQuery = '';
document.addEventListener('DOMContentLoaded', async function () {
const reportContent = document.getElementById('reportContent');
if (!reportContent) return; // Not on report page
let report = null;
const pathParts = window.location.pathname.split('/');
let pathReportId = null;
if (pathParts[1] === 'reports' && pathParts[2] && pathParts[3]) {
pathReportId = `${pathParts[2]}/${pathParts[3]}`;
} else {
const params = new URLSearchParams(window.location.search);
pathReportId = params.get('id');
}
// 1. Try sessionStorage first
const stored = sessionStorage.getItem('catalystReport');
if (stored) {
try {
const parsed = JSON.parse(stored);
// Only use sessionStorage if the ID matches the URL, or if we don't have a URL ID
if (!pathReportId || parsed.id === pathReportId) {
report = parsed;
}
} catch (e) {
console.error('Failed to parse stored report', e);
}
}
// 2. If not in sessionStorage, check path or query parameter
if (!report && pathReportId) {
try {
report = await fetchJSON(`/api/report?id=${encodeURIComponent(pathReportId)}`);
} catch (error) {
reportContent.innerHTML = `<div class="error-box">Failed to load report: ${escapeHtml(error.message)}</div>`;
return;
}
}
// 3. If still no report, prompt user
if (!report) {
reportContent.innerHTML = `
<div class="empty-state">
<p style="font-size:1.1rem; margin-bottom:1rem;">No audit data found for this session.</p>
<a href="index.html" class="btn btn-primary">Run a Website Audit</a>
</div>
`;
return;
}
currentReportData = report;
saveRecentAudit(report);
renderReport(report);
setupReportFilters();
setupReportActions(report);
});
// Setup Filter & Toggle Controls
function setupReportFilters() {
const catCheckboxes = document.querySelectorAll('.cat-checkbox-input');
const selectedCatCount = document.getElementById('selectedCatCount');
function updateCatCountLabel() {
if (selectedCatCount) {
selectedCatCount.textContent = `${activeCategories.size} of ${ALL_CATEGORY_KEYS.length} visible`;
}
}
catCheckboxes.forEach((checkbox) => {
checkbox.addEventListener('change', () => {
const catVal = checkbox.value;
const parentCard = checkbox.closest('.cat-toggle-card');
if (checkbox.checked) {