-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1785 lines (1509 loc) · 69.8 KB
/
script.js
File metadata and controls
1785 lines (1509 loc) · 69.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** * ==========================================
* CONFIGURATION & CUSTOMIZATION
* Edit these values to update the app catalog behavior, branding, and notices.
* ==========================================
*/
const CONFIG = {
owner: 'nullcpy',
repo: 'rvb',
cacheDuration: 5, // Cache duration in minutes
// App Categories for the top filter buttons (maps filter-btn dataset to keywords)
appCategories: {
google: ['youtube', 'google'],
meta: ['threads', 'instagram', 'messenger', 'facebook']
},
// Words ignored in the dynamic app filters (must be lowercase)
sharedAppWordStoplist: new Set([
'revanced', 'patched', 'patch', 'extended', 'advanced',
'theme', 'edition', 'android', 'app', 'google',
'meta', 'facebook', 'instagram', 'messenger'
]),
// Known tokens indicating a patch name starts (must be lowercase)
knownPatchTokens: new Set(['revanced', 'morphe', 'anddea', 'rvx']),
// Known tokens indicating a variant (must be lowercase)
variantKeywords: new Set(['exp', 'nord', 'mocha', 'privacy', 'materialu', 'foss', 'gplay', 'piko', 'adobo', 'patcheddit']),
// Known architectures (used for regex parsing)
knownArchs: [
'arm64-v8a', 'arm64', 'aarch64', 'armeabi-v7a', 'arm-v7a',
'arm32', 'x86_64', 'x86', 'universal', 'all'
],
// Brand name overrides (keys must be lowercase)
brandOverrides: {
youtube: 'YouTube', revanced: 'ReVanced', tiktok: 'TikTok', soundcloud: 'SoundCloud', xrecorder: 'XRecorder', calcnote: 'CalcNote', imdb: 'IMDb', trakt: 'trakt.TV',
vpn: 'VPN', rvx: 'ReVanced Extended', anddea: 'ReVanced Advanced', exp: 'Experimental', macrodroid: 'MacroDroid', ticktick: 'TickTick', fing: 'Fing - Network Tools',
mocha: 'Mocha Theme', nord: 'Nord Theme', materialu: 'Material You', photoshop: 'Adobe Photoshop', lightroom: 'Adobe Lightroom', xodo: 'Xodo PDF Reader & Editor',
gplay: 'Google Play', foss: 'FOSS', gboard: 'Google Keyboard', wps: 'WPS', rar: 'RAR', adguard: 'AdGuard', moonplus: 'Moon+', eyecon: 'Eyecon Caller ID & Spam Block'
},
// Map app slugs to true Android Package IDs for Obtainium
// Keys MUST be the fully normalized appName (lowercase, no spaces, no symbols)
appIds: {
'adguard': 'com.adguard.android.contentblocker',
'adobelightroom': 'com.adobe.lrmobile',
'adobephotoshopmix': 'com.adobe.psmobile',
'autosync': 'com.ttxapps.autosync',
'calcnote': 'com.appumstudios.calcnote',
'cricbuzz': 'com.cricbuzz.android',
'documentscanner': 'com.cv.docscanner',
'duolingo': 'com.duolingo',
'eyeconcalleridspamblock': 'com.eyecon.global',
'fingnetworktools': 'com.overlook.android.fing',
'googlekeyboard': 'com.google.android.inputmethod.latin',
'googlenews': 'com.google.android.apps.magazines',
'googlephotos': 'com.google.android.apps.photos',
'googlerecorder': 'com.google.android.apps.recorder',
'iconpacker': 'cn.ommiao.iconpacker',
'instagram': 'com.instagram.android',
'macrodroid': 'com.arlosoft.macrodroid',
'merriamwebsterdictionary': 'com.merriamwebster',
'messenger': 'com.facebook.orca',
'microsoftlens': 'com.microsoft.office.officelens',
'moonplusreader': 'com.flyersoft.moonreader',
'pandora': 'com.pandora.android',
'photomath': 'com.microblink.photomath',
'pinterest': 'com.pinterest',
'podcastaddict': 'com.bambuna.podcastaddict',
'protonmail': 'ch.protonmail.android',
'protonvpn': 'ch.protonvpn.android',
'reddit': 'com.reddit.frontpage',
'smartlauncher6': 'ginlemon.flowerfree',
'solidexplorer': 'pl.solidexplorer2',
'soundcloud': 'com.soundcloud.android',
'symfonium': 'app.symfonik.music.player',
// Use an object for variant-specific IDs
'telegram': {
default: 'org.telegram.messenger',
foss: 'org.telegram.messenger.web'
},
'threads': 'com.instagram.barcelona',
'ticktick': 'com.ticktick.task',
'truecaller': 'com.truecaller',
'tumblr': 'com.tumblr',
'twitch': 'tv.twitch.android.app',
'viber': 'com.viber.voip',
'wallcraft': 'com.wallpaperscraft.wallpaper',
'rar': 'com.rarlab.rar',
'wpsoffice': 'cn.wps.moffice_eng',
'twitter': 'com.twitter.android',
'xodopdfreadereditor': 'com.xodo.pdf.reader',
'xrecorder': 'video.other.screenrecorder',
'youtube': 'com.google.android.youtube',
'youtubemusic': 'com.google.android.apps.youtube.music'
},
// App-specific notices to display on App Cards
appNotices: [
{
triggers: ['youtube', 'google'], // App name keywords that trigger this notice
className: 'microg-note', // Defines the CSS prefix
title: 'Login Issue',
text: 'Signing into Google account on APK (not Module) requires MicroG. Please install one from below before trying to sign in.',
links: [
{ label: 'Morphe', url: 'https://github.com/MorpheApp/MicroG-RE/releases/latest' },
{ label: 'ReVanced', url: 'https://github.com/ReVanced/GmsCore/releases/latest' }
]
},
{
triggers: ['twitter'],
className: 'twitter-login-note',
title: 'Login Issue',
text: 'Since October 2025, Twitter has started checking whether the app is modified or if the phone integrity fails during login. These checks are server-side, not client-side.',
links: [
{ label: 'Workarounds', url: 'https://t.me/pikopatches/1/59772' }
]
}
]
};
// State
let allReleases = [];
let cachedFullCatalog = [];
let searchTerm = '';
let appViewFilter = 'all';
let dynamicAppFilters = [];
let currentAppCatalog = [];
let activeModalAppKey = null;
let activeModalPatchKey = null;
let modalBuildFilter = 'all';
let themeMode = 'system';
// Render State for Infinite Scroll
let currentVisibleCount = 0;
const RENDER_CHUNK_SIZE = 50;
const SHARED_APP_WORD_MIN_COUNT = 3;
const SHARED_APP_WORD_FALLBACK_COUNT = 2;
// Caches for Memoization
const parseCache = new Map();
const tokenCache = new Map();
// Initialize
document.addEventListener('DOMContentLoaded', () => {
setupTheme();
setupEventListeners();
loadReleases();
});
// Theme Management
function setupTheme() {
const savedTheme = localStorage.getItem('theme');
themeMode = savedTheme === 'light' || savedTheme === 'dark' || savedTheme === 'system'
? savedTheme
: 'system';
applyTheme(themeMode);
const mediaQuery = window.matchMedia('(prefers-color-scheme: light)');
mediaQuery.addEventListener('change', () => {
if (themeMode !== 'system') {
return;
}
applyTheme('system');
});
}
function applyTheme(theme) {
const isLight = theme === 'light'
? true
: theme === 'dark'
? false
: window.matchMedia('(prefers-color-scheme: light)').matches;
document.body.classList.toggle('light-mode', isLight);
const themeBtn = document.getElementById('themeBtn');
themeBtn.textContent = theme === 'system' ? '🖥️' : theme === 'light' ? '☀️' : '🌙';
themeBtn.setAttribute('aria-label', `Theme mode: ${theme}`);
}
// Event Listeners
function setupEventListeners() {
let searchTimeout;
// Theme button
document.getElementById('themeBtn').addEventListener('click', () => {
const nextTheme = themeMode === 'system'
? 'light'
: themeMode === 'light'
? 'dark'
: 'system';
themeMode = nextTheme;
localStorage.setItem('theme', nextTheme);
applyTheme(nextTheme);
});
const menuBtn = document.getElementById('menuBtn');
const actionMenu = document.getElementById('actionMenu');
if (menuBtn && actionMenu) {
menuBtn.addEventListener('click', (e) => {
e.stopPropagation();
actionMenu.classList.toggle('open');
menuBtn.setAttribute('aria-expanded', actionMenu.classList.contains('open'));
});
document.addEventListener('click', (e) => {
if (actionMenu.classList.contains('open') && !actionMenu.contains(e.target)) {
actionMenu.classList.remove('open');
menuBtn.setAttribute('aria-expanded', 'false');
}
});
}
// 1. Debounced Search Input
const searchInput = document.getElementById('searchInput');
searchInput.addEventListener('input', (e) => {
clearTimeout(searchTimeout);
searchTimeout = setTimeout(() => {
searchTerm = e.target.value.toLowerCase();
filterAndRenderReleases();
}, 250);
});
searchInput.addEventListener('focus', (e) => {
if (window.innerWidth <= 768) {
const searchBox = e.target.closest('.search-box') || e.target;
const y = searchBox.getBoundingClientRect().top + window.scrollY - 15;
window.scrollTo({ top: y, behavior: 'smooth' });
}
});
const appFilterButtons = document.getElementById('appFilterButtons');
if (appFilterButtons) {
appFilterButtons.addEventListener('click', (e) => {
const filterBtn = e.target.closest('.filter-btn');
if (!filterBtn) return;
appViewFilter = filterBtn.dataset.filter || 'all';
filterAndRenderReleases();
});
}
document.getElementById('builds').addEventListener('click', (e) => {
const collapsedCard = e.target.closest('.app-card:not([open])');
if (collapsedCard && !e.target.closest('.app-card-summary')) {
collapsedCard.open = true;
return;
}
const trigger = e.target.closest('.patch-open-box');
if (!trigger) return;
openPatchModal(trigger.dataset.appKey, trigger.dataset.patchKey, trigger.dataset.filter || 'all');
});
document.getElementById('patchModal').addEventListener('click', (e) => {
const filterBtn = e.target.closest('.modal-filter-btn');
if (filterBtn) {
if (filterBtn.disabled) return;
modalBuildFilter = filterBtn.dataset.filter;
renderOpenPatchModal();
return;
}
if (e.target.id === 'patchModal' || e.target.closest('.modal-close')) {
closePatchModal();
}
});
document.getElementById('obtainiumBtn').addEventListener('click', (e) => {
e.stopPropagation();
openObtainiumModal();
});
document.getElementById('obtainiumModal').addEventListener('click', (e) => {
if (e.target.id === 'obtainiumModal' || e.target.closest('.modal-close')) {
closeObtainiumModal();
}
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
closePatchModal();
closeObtainiumModal();
}
});
// 2. Infinite Scroll Observer
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
renderNextChunk();
}
}, { rootMargin: '400px' });
const sentinel = document.createElement('div');
sentinel.id = 'scroll-sentinel';
sentinel.style.height = '1px';
document.getElementById('builds').after(sentinel);
observer.observe(sentinel);
}
// Fetch releases from local static cache (generated by GitHub Actions)
async function loadReleases() {
try {
// 1. Trigger the yellow spinning state immediately
setPillState('checking', 'Checking for updates...');
const cached = getCachedReleases();
if (cached) {
allReleases = cached;
document.getElementById('loading').style.display = 'none';
document.getElementById('error').style.display = 'none';
rebuildCatalogCache();
updateLastUpdateTimestamp();
filterAndRenderReleases();
return;
}
document.getElementById('loading').style.display = 'block';
document.getElementById('error').style.display = 'none';
// Add a timestamp to bypass GitHub Pages CDN cache
const cacheBuster = new Date().getTime();
let fetchedData = null;
let useFallback = true;
try {
const response = await fetch(`releases.json?v=${cacheBuster}`);
if (response.ok) {
const data = await response.json();
if (Array.isArray(data) && data.length > 0) {
fetchedData = data;
useFallback = false;
}
}
} catch (e) {
console.warn('Network error fetching releases.json (likely file:// protocol).', e);
}
// Fallback to live API if releases.json is missing, empty, or fetch threw an error
if (useFallback) {
console.warn('Static cache not found or empty. Falling back to live API...');
const response = await fetch(
`https://api.github.com/repos/${CONFIG.owner}/${CONFIG.repo}/releases`,
{ headers: { 'Accept': 'application/vnd.github.v3+json' } }
);
if (!response.ok) {
throw new Error(`Failed to fetch data: ${response.status}`);
}
fetchedData = await response.json();
}
allReleases = fetchedData;
cacheReleases(allReleases);
rebuildCatalogCache();
document.getElementById('loading').style.display = 'none';
updateLastUpdateTimestamp();
filterAndRenderReleases();
} catch (error) {
console.error('Error loading releases:', error);
// 2. Trigger the red error state if fetching fails
setPillState('error', 'Failed to check updates');
document.getElementById('loading').style.display = 'none';
document.getElementById('error').style.display = 'block';
document.getElementById('error').textContent = `Failed to load releases: ${error.message}`;
}
}
// Caching utilities for LocalStorage
function getCachedReleases() {
const cached = localStorage.getItem('releases_cache');
const timestamp = localStorage.getItem('releases_cache_time');
if (!cached || !timestamp) return null;
const age = (Date.now() - parseInt(timestamp)) / (1000 * 60);
if (age > CONFIG.cacheDuration) {
localStorage.removeItem('releases_cache');
localStorage.removeItem('releases_cache_time');
return null;
}
return JSON.parse(cached);
}
function cacheReleases(releases) {
localStorage.setItem('releases_cache', JSON.stringify(releases));
localStorage.setItem('releases_cache_time', Date.now().toString());
}
// Build and cache the full app catalog — called once when release data changes
function rebuildCatalogCache() {
cachedFullCatalog = buildAppCatalog(allReleases.filter(r => !r.draft));
dynamicAppFilters = getDynamicAppFilters(cachedFullCatalog);
}
// Apply a search query to an already-built catalog without rebuilding from scratch
function filterCatalogBySearch(catalog, query) {
if (!query) return catalog;
const normalizedQuery = normalizeForSearch(query);
return catalog
.map(app => {
const filteredPatches = app.patches
.map(patch => {
const filteredBuilds = patch.builds
.map(build => ({
...build,
assets: build.assets.filter(asset =>
assetMatchesSearch(
asset.parsed, asset,
{ name: build.build, tag_name: build.build },
query, normalizedQuery
)
)
}))
.filter(build => build.assets.length > 0);
return filteredBuilds.length > 0 ? { ...patch, builds: filteredBuilds } : null;
})
.filter(Boolean);
return filteredPatches.length > 0 ? { ...app, patches: filteredPatches } : null;
})
.filter(Boolean);
}
// Filter and render releases
function filterAndRenderReleases() {
renderDynamicAppFilterButtons(dynamicAppFilters);
if (appViewFilter.startsWith('word-') && !dynamicAppFilters.some(filter => filter.key === appViewFilter)) {
appViewFilter = 'all';
}
const searchedCatalog = filterCatalogBySearch(cachedFullCatalog, searchTerm);
const filteredApps = applyAppViewFilter(searchedCatalog);
renderAppCards(filteredApps);
updateAppFilterButtons();
document.getElementById('loading').style.display = 'none';
}
function updateAppFilterButtons() {
document.querySelectorAll('#appFilterButtons .filter-btn').forEach(btn => {
btn.classList.toggle('active', btn.dataset.filter === appViewFilter);
});
}
function getAppLatestPublishedAt(app) {
return app.patches.reduce((latest, patch) => {
const patchTime = new Date(patch.latestPublishedAt).getTime();
return Number.isNaN(patchTime) ? latest : Math.max(latest, patchTime);
}, 0);
}
function getAppTotalDownloads(app) {
let total = 0;
(app.patches || []).forEach(patch => {
(patch.builds || []).forEach(build => {
(build.assets || []).forEach(asset => {
total += (asset.download_count || 0);
});
});
});
return total;
}
function applyAppViewFilter(apps) {
if (CONFIG.appCategories[appViewFilter]) {
return apps.filter(app => {
const name = normalizeForSearch(app.appName);
return CONFIG.appCategories[appViewFilter].some(keyword => name.includes(keyword));
});
}
if (appViewFilter.startsWith('word-')) {
const word = appViewFilter.slice(5);
return apps.filter(app => getAppNameWords(app.appName).includes(word));
}
if (appViewFilter === 'recent') {
return [...apps].sort((a, b) => getAppLatestPublishedAt(b) - getAppLatestPublishedAt(a));
}
if (appViewFilter === 'popular') {
return [...apps].sort((a, b) => getAppTotalDownloads(b) - getAppTotalDownloads(a));
}
return apps;
}
function buildAppCatalog(releases, query = '') {
const normalizedQuery = normalizeForSearch(query);
const sortedReleases = [...releases].sort((a, b) =>
new Date(b.published_at) - new Date(a.published_at)
);
const appMap = new Map();
sortedReleases.forEach(release => {
const isArchive = release.tag_name === 'stable' || release.tag_name === 'beta';
let releaseType = release.prerelease ? 'beta' : 'stable';
if (release.tag_name === 'stable') releaseType = 'stable';
if (release.tag_name === 'beta') releaseType = 'beta';
(release.assets || []).forEach(asset => {
const arch = detectArchitecture(asset.name);
const fileType = getFileType(asset.name);
const parsed = parseAssetDisplay(asset.name, arch, fileType);
if (!assetMatchesSearch(parsed, asset, release, query, normalizedQuery)) {
return;
}
const appKey = normalizeForSearch(parsed.appName);
if (!appKey) return;
if (!appMap.has(appKey)) {
appMap.set(appKey, {
appKey,
appName: parsed.appName,
latestStable: null,
latestBeta: null,
patches: new Map()
});
}
const appEntry = appMap.get(appKey);
setLatestBuildMeta(appEntry, releaseType, release);
const patchKey = normalizeForSearch(parsed.patchName) || 'patchedbuild';
if (!appEntry.patches.has(patchKey)) {
appEntry.patches.set(patchKey, {
patchKey,
patchName: parsed.patchName,
latestVersion: null, // Wait for a real date
latestPublishedAt: 0,
latestStable: null,
latestBeta: null,
latestVariant: null,
latestArchiveStable: null, // NEW FALLBACK
latestArchiveBeta: null, // NEW FALLBACK
builds: new Map()
});
}
const patchEntry = appEntry.patches.get(patchKey);
const buildLabel = getBuildNumberLabel(release);
// Get the true date of the APK upload
const buildDateString = isArchive ? (asset.updated_at || asset.created_at || release.published_at) : release.published_at;
const buildDateMs = new Date(buildDateString).getTime();
// STRICT PROTECTION: Only update the App Card timestamps if it is NOT an archive!
if (!isArchive) {
const patchDate = new Date(patchEntry.latestPublishedAt).getTime();
if (buildDateMs > patchDate) {
patchEntry.latestVersion = parsed.version;
patchEntry.latestPublishedAt = buildDateString;
}
if (!parsed.variant) {
setLatestPatchMeta(patchEntry, releaseType, parsed.version, buildLabel, buildDateString);
} else {
setLatestVariantMeta(patchEntry, parsed.variant, parsed.version, buildLabel, buildDateString);
}
} else {
// FALLBACK: Quietly track the newest archive for Dead Apps
// FIX: Only track non-variants for the generic Stable/Beta fallback boxes!
if (!parsed.variant) {
if (releaseType === 'stable') {
const currentMs = patchEntry.latestArchiveStable ? new Date(patchEntry.latestArchiveStable.publishedAt).getTime() : 0;
if (buildDateMs > currentMs) {
patchEntry.latestArchiveStable = { version: parsed.version, build: buildLabel, publishedAt: buildDateString };
}
} else if (releaseType === 'beta') {
const currentMs = patchEntry.latestArchiveBeta ? new Date(patchEntry.latestArchiveBeta.publishedAt).getTime() : 0;
if (buildDateMs > currentMs) {
patchEntry.latestArchiveBeta = { version: parsed.version, build: buildLabel, publishedAt: buildDateString };
}
}
}
}
// Split archives into their own separate dropdowns based on Version!
const buildKey = isArchive ? `archive-${releaseType}-${parsed.version}` : String(release.id);
if (!patchEntry.builds.has(buildKey)) {
patchEntry.builds.set(buildKey, {
releaseId: release.id,
build: isArchive ? parsed.version : getBuildNumberLabel(release),
releaseType,
isArchive, // Flag for the modal
publishedAt: isArchive ? (asset.updated_at || asset.created_at || release.published_at) : release.published_at,
releaseUrl: release.html_url,
version: parsed.version,
assets: []
});
}
const buildEntry = patchEntry.builds.get(buildKey);
const exists = buildEntry.assets.some(existing => existing.name === asset.name);
if (!exists) {
buildEntry.assets.push({
...asset,
parsed,
arch,
fileType
});
}
});
});
return Array.from(appMap.values())
.map(app => {
// NEW: Apply fallback dates for archive-only apps before sorting
app.patches.forEach(patch => {
if (!patch.latestStable && patch.latestArchiveStable) {
patch.latestStable = patch.latestArchiveStable;
patch.latestStable.isArchiveFallback = true;
const archiveMs = new Date(patch.latestArchiveStable.publishedAt).getTime();
const currentMs = patch.latestPublishedAt ? new Date(patch.latestPublishedAt).getTime() : 0;
if (archiveMs > currentMs) {
patch.latestVersion = patch.latestArchiveStable.version;
patch.latestPublishedAt = patch.latestArchiveStable.publishedAt;
}
}
if (!patch.latestBeta && patch.latestArchiveBeta) {
patch.latestBeta = patch.latestArchiveBeta;
patch.latestBeta.isArchiveFallback = true;
const archiveMs = new Date(patch.latestArchiveBeta.publishedAt).getTime();
const currentMs = patch.latestPublishedAt ? new Date(patch.latestPublishedAt).getTime() : 0;
if (archiveMs > currentMs) {
patch.latestVersion = patch.latestArchiveBeta.version;
patch.latestPublishedAt = patch.latestArchiveBeta.publishedAt;
}
}
});
return {
...app,
patches: Array.from(app.patches.values()).sort((a, b) =>
new Date(b.latestPublishedAt) - new Date(a.latestPublishedAt)
)
.map(patch => ({
...patch,
// Sink archives to the bottom!
builds: Array.from(patch.builds.values()).sort((a, b) => {
// 1. If one is an archive and the other isn't, sink the archive
if (a.isArchive && !b.isArchive) return 1;
if (!a.isArchive && b.isArchive) return -1;
// 2. If BOTH are archives, sort them nicely by version number (highest first)
if (a.isArchive && b.isArchive) {
const versionComparison = b.version.localeCompare(a.version, undefined, { numeric: true, sensitivity: 'base' });
if (versionComparison !== 0) return versionComparison;
// If same version, sort by date (newest first)
return new Date(b.publishedAt) - new Date(a.publishedAt);
}
// 3. Otherwise (normal builds), just sort by date
return new Date(b.publishedAt) - new Date(a.publishedAt);
})
}))
};
})
.filter(app => app.patches.length > 0)
.sort((a, b) => a.appName.localeCompare(b.appName));
}
function assetMatchesSearch(parsed, asset, release, rawQuery, normalizedQuery) {
if (!rawQuery) return true;
return [
parsed.appName,
parsed.patchName,
parsed.version,
parsed.archLabel,
parsed.fileType,
asset.name,
release.name || '',
release.tag_name || ''
].some(value => matchesSearch(String(value || ''), rawQuery, normalizedQuery));
}
function setLatestBuildMeta(appEntry, releaseType, release) {
const key = releaseType === 'beta' ? 'latestBeta' : 'latestStable';
const current = appEntry[key];
const currentDate = current ? new Date(current.publishedAt).getTime() : 0;
const releaseDate = new Date(release.published_at).getTime();
if (!current || releaseDate > currentDate) {
appEntry[key] = {
build: getBuildNumberLabel(release),
publishedAt: release.published_at,
releaseUrl: release.html_url
};
}
}
function setLatestPatchMeta(patchEntry, releaseType, version, build, publishedAt) {
const key = releaseType === 'beta' ? 'latestBeta' : 'latestStable';
const current = patchEntry[key];
const currentDate = current ? new Date(current.publishedAt).getTime() : 0;
const releaseDate = new Date(publishedAt).getTime();
if (!current || releaseDate > currentDate) {
patchEntry[key] = { version, build, publishedAt };
}
}
function setLatestVariantMeta(patchEntry, variant, version, build, publishedAt) {
const current = patchEntry.latestVariant;
const currentDate = current ? new Date(current.publishedAt).getTime() : 0;
const releaseDate = new Date(publishedAt).getTime();
if (!current || releaseDate > currentDate) {
patchEntry.latestVariant = { variant, version, build, publishedAt };
}
}
function getBuildNumberLabel(release) {
return String(release.tag_name || release.name || 'N/A');
}
// Render app cards to DOM (Progressive Rendering)
function renderAppCards(apps) {
const buildsContainer = document.getElementById('builds');
currentAppCatalog = apps;
currentVisibleCount = 0;
buildsContainer.innerHTML = '';
if (apps.length === 0) {
buildsContainer.innerHTML = '<div class="no-results">No apps found.</div>';
return;
}
renderNextChunk();
}
function renderNextChunk() {
const buildsContainer = document.getElementById('builds');
const nextChunk = currentAppCatalog.slice(currentVisibleCount, currentVisibleCount + RENDER_CHUNK_SIZE);
if (nextChunk.length === 0) return;
const tempDiv = document.createElement('div');
tempDiv.innerHTML = nextChunk.map(app => createAppCard(app)).join('');
while (tempDiv.firstChild) {
buildsContainer.appendChild(tempDiv.firstChild);
}
currentVisibleCount += RENDER_CHUNK_SIZE;
}
function createNoticeMarkup(notice) {
const linksMarkup = notice.links.map(link =>
`<a href="${link.url}" target="_blank" rel="noopener noreferrer">${escapeHtml(link.label)}</a>`
).join('\n ');
return `
<div class="app-notice ${escapeHtml(notice.className)}">
<div class="app-notice-title">${escapeHtml(notice.title)}</div>
<div class="app-notice-text">${escapeHtml(notice.text)}</div>
<div class="app-notice-links">
${linksMarkup}
</div>
</div>
`;
}
function createAppCard(app) {
const patchesMarkup = app.patches.map((patch) => createPatchMarkup(app, patch)).join('');
let noticesMarkup = '';
CONFIG.appNotices.forEach(notice => {
const matches = notice.triggers.some(trigger => normalizeForSearch(app.appName).includes(trigger));
if (matches) {
noticesMarkup += createNoticeMarkup(notice);
}
});
return `
<details class="build-card app-card">
<summary class="build-header app-card-summary">
<div class="app-name">${escapeHtml(app.appName)}</div>
<span class="patch-count">${app.patches.length} patch${app.patches.length > 1 ? 'es' : ''}</span>
</summary>
<div class="app-card-body">
${noticesMarkup}
<div class="patches-title">Available patches</div>
<div class="patches-list">
${patchesMarkup}
</div>
</div>
</details>
`;
}
function getDynamicAppFilters(apps) {
const wordToAppKeys = new Map();
apps.forEach(app => {
const words = getAppNameWords(app.appName);
words.forEach(word => {
if (!wordToAppKeys.has(word)) {
wordToAppKeys.set(word, new Set());
}
wordToAppKeys.get(word).add(app.appKey);
});
});
const allWordEntries = Array.from(wordToAppKeys.entries());
const preferredEntries = allWordEntries.filter(([, appKeys]) => appKeys.size >= SHARED_APP_WORD_MIN_COUNT);
const fallbackEntries = allWordEntries.filter(([, appKeys]) => appKeys.size >= SHARED_APP_WORD_FALLBACK_COUNT);
const selectedEntries = preferredEntries.length > 0 ? preferredEntries : fallbackEntries;
return selectedEntries
.sort((a, b) => a[0].localeCompare(b[0])) // Strictly alphabetical sort
.map(([word]) => ({
key: `word-${word}`,
label: toFilterLabel(word)
}));
}
function renderDynamicAppFilterButtons(filters) {
const filterButtons = document.getElementById('appFilterButtons');
if (!filterButtons) return;
filterButtons.querySelectorAll('.dynamic-filter-btn').forEach(btn => btn.remove());
filters.forEach(filter => {
const button = document.createElement('button');
button.className = 'filter-btn dynamic-filter-btn';
button.dataset.filter = filter.key;
button.type = 'button';
button.textContent = filter.label;
filterButtons.appendChild(button);
});
// --- ALPHABETICAL SORTING LOGIC ---
// 1. Grab every button inside the filter container
const allBtns = Array.from(filterButtons.querySelectorAll('.filter-btn'));
// 2. Separate the fixed buttons from the ones we want to sort, in exact order!
const fixedKeys = ['all', 'recent', 'popular'];
const fixedBtns = [];
fixedKeys.forEach(key => {
const foundBtn = allBtns.find(btn => btn.dataset.filter === key);
if (foundBtn) fixedBtns.push(foundBtn);
});
const sortableBtns = allBtns.filter(btn => !fixedKeys.includes(btn.dataset.filter));
// 3. Sort the remaining buttons alphabetically by their text label
sortableBtns.sort((a, b) => a.textContent.localeCompare(b.textContent));
// 4. Re-append them to the container in the exact order we want
fixedBtns.forEach(btn => filterButtons.appendChild(btn));
sortableBtns.forEach(btn => filterButtons.appendChild(btn));
}
function getAppNameWords(appName) {
const words = (appName || '')
.toLowerCase()
.split(/[^a-z0-9]+/)
.filter(Boolean)
.filter(word => word.length >= 3)
.filter(word => !CONFIG.sharedAppWordStoplist.has(word));
return Array.from(new Set(words));
}
function toFilterLabel(value) {
return value.replace(/\b[a-z]/g, char => char.toUpperCase());
}
function createPatchMarkup(app, patch) {
const buildCount = patch.builds.length;
const allMeta = [patch.latestStable, patch.latestBeta, patch.latestVariant].filter(Boolean);
const latestBuild = allMeta.length > 0
? allMeta.reduce((a, b) => new Date(a.publishedAt) > new Date(b.publishedAt) ? a : b).build
: null;
const boxes = [];
if (patch.latestStable) {
const buildMarkup = patch.latestStable.isArchiveFallback ? '' : `<span class="patch-meta-build">Build ${escapeHtml(patch.latestStable.build || 'N/A')}</span>`;
boxes.push({
label: 'Stable',
html: `
<button class="patch-open-box stable" data-app-key="${app.appKey}" data-patch-key="${patch.patchKey}" data-filter="stable" type="button">
<span class="patch-meta-label">Stable</span>
<span class="patch-meta-value">${escapeHtml(patch.latestStable.version)}</span>
${buildMarkup}
<span class="patch-meta-date">${formatDate(patch.latestStable.publishedAt)}</span>
</button>
`});
}
if (patch.latestBeta) {
const buildMarkup = patch.latestBeta.isArchiveFallback ? '' : `<span class="patch-meta-build">Build ${escapeHtml(patch.latestBeta.build || 'N/A')}</span>`;
boxes.push({
label: 'Beta',
html: `
<button class="patch-open-box beta" data-app-key="${app.appKey}" data-patch-key="${patch.patchKey}" data-filter="beta" type="button">
<span class="patch-meta-label">Beta</span>
<span class="patch-meta-value">${escapeHtml(patch.latestBeta.version)}</span>
${buildMarkup}
<span class="patch-meta-date">${formatDate(patch.latestBeta.publishedAt)}</span>
</button>
`});
}
const variants = getUniqueVariants(patch);
variants.forEach(variant => {
const latestVariantBuild = getLatestVariantBuild(patch, variant);
if (latestVariantBuild) {
const buildMarkup = latestVariantBuild.isArchiveFallback ? '' : `<span class="patch-meta-build">Build ${escapeHtml(latestVariantBuild.build || 'N/A')}</span>`;
boxes.push({
label: variant,
html: `
<button class="patch-open-box variant" data-app-key="${app.appKey}" data-patch-key="${patch.patchKey}" data-filter="variant-${variant}" type="button">
<span class="patch-meta-label">${escapeHtml(variant)}</span>
<span class="patch-meta-value">${escapeHtml(latestVariantBuild.version)}</span>
${buildMarkup}
<span class="patch-meta-date">${formatDate(latestVariantBuild.publishedAt)}</span>
</button>
`});
}
});
// Keep logical order: Stable -> Beta -> Variants
const patchMetaBoxes = boxes.map(b => b.html);
if (patchMetaBoxes.length === 0) {
patchMetaBoxes.push(`
<button class="patch-open-box" data-app-key="${app.appKey}" data-patch-key="${patch.patchKey}" data-filter="all" type="button">
<span class="patch-meta-label">Latest</span>
<span class="patch-meta-value">${escapeHtml(patch.latestVersion)}</span>
<span class="patch-meta-date">${formatDate(patch.latestPublishedAt)}</span>
</button>
`);
}
const buildCountBadge = `<span class="patch-build-count">${buildCount} build${buildCount > 1 ? 's' : ''}</span>`;
return `
<div class="patch-entry">
<span class="patch-trigger-left">
<span class="patch-chip-group">
<span class="patch-chip">${escapeHtml(patch.patchName)}</span>
${buildCountBadge}
</span>
<span class="patch-meta-grid">
${patchMetaBoxes.join('')}
</span>
</span>
</div>
`;
}
function openPatchModal(appKey, patchKey, preferredFilter = 'all') {
activeModalAppKey = appKey;
activeModalPatchKey = patchKey;
const app = currentAppCatalog.find(item => item.appKey === appKey);
const patch = app ? app.patches.find(item => item.patchKey === patchKey) : null;
const hasStableBuild = patch ? getFilteredBuildsForFilter(patch, 'stable').length > 0 : false;
const hasBetaBuild = patch ? getFilteredBuildsForFilter(patch, 'beta').length > 0 : false;
const hasVariantBuild = patch ? getFilteredBuildsForFilter(patch, 'variant').length > 0 : false;
const variants = patch ? getUniqueVariants(patch) : []; // Retrieve variants list
const prefersStable = preferredFilter === 'stable' && hasStableBuild;
const prefersBeta = preferredFilter === 'beta' && hasBetaBuild;
const prefersSpecificVariant = preferredFilter.startsWith('variant-') && getFilteredBuildsForFilter(patch, preferredFilter).length > 0;
const prefersGenericVariant = preferredFilter === 'variant' && hasVariantBuild;
const prefersVersion = preferredFilter.startsWith('version-') && getFilteredBuildsForFilter(patch, preferredFilter).length > 0;
if (prefersStable) {
modalBuildFilter = 'stable';
} else if (prefersBeta) {
modalBuildFilter = 'beta';
} else if (prefersSpecificVariant) {