Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
1949 lines (1758 loc) · 71.5 KB
/
Copy pathscript.js
File metadata and controls
1949 lines (1758 loc) · 71.5 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
/*
*-------------------------------------------------------------------------------
* Copyright (C) 2025 philippe
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*-------------------------------------------------------------------------------
*/
// Configuration
const BASE_URL =
(window.location.href).replace("unified-access.html", "").split(/[?#]/)[0];
const IPS_PATH = '/ips/';
const CATEGORIES_URL = 'cfg/categories.json';
const PROJECTS_URL = 'cfg/projects.json';
const REPO_STATS_URL = 'cfg/repo-stats.json';
const REPO_STATS_COLUMN = 'Repo Stats';
const IP_CARD_COLUMN = 'IP Card';
const defaultColumns = ["Name", "Category", "URL", "License", "Status", IP_CARD_COLUMN, REPO_STATS_COLUMN, "Project", "Description"];
const columnLabels = { "IP_CARD_URL": "IP Card", "IP_CARD_PDF_URL": "IP Card PDF", [IP_CARD_COLUMN]: "IP Card" };
let viewMode = "default";
// Cached DOM Elements
const statusEl = document.getElementById('status');
const exportBtn = document.getElementById('export-btn');
const fileInput = document.getElementById('file-input');
const loadRadios = document.querySelectorAll('input[name="load-mode"]');
const table = document.getElementById('data-table');
const thead = table.querySelector('thead');
const tbody = table.querySelector('tbody');
// Screen-reader live region for announcements (visually hidden but readable)
let srStatus = document.getElementById('sr-status');
if (!srStatus) {
srStatus = document.createElement('div');
srStatus.id = 'sr-status';
srStatus.setAttribute('role', 'status');
srStatus.setAttribute('aria-live', 'polite');
// visually hide but keep available to assistive tech
srStatus.style.position = 'absolute';
srStatus.style.left = '-9999px';
srStatus.style.width = '1px';
srStatus.style.height = '1px';
srStatus.style.overflow = 'hidden';
document.body.appendChild(srStatus);
}
// State
let masterData = [];
let filteredData = [];
let columns = [];
let searchText = '';
let filterState = {};
let allowedCategories = [];
let projectsData = [];
// Repository statistics cache: { generated_at, source, repos: {...}, errors: {...} }
// null when the cache could not be loaded at all.
let repoStats = null;
// lowercase "<host>/owner/repo" -> stats record, rebuilt whenever the cache is loaded.
let repoStatsIndex = new Map();
let visibleColumns = [];
let dataLoaded = false; // flag: true once loadDataFromServer finishes
let pendingSearch = null; // stores search term from popstate until data is ready
async function loadAllowedCategories() {
try {
const response = await fetch(CATEGORIES_URL);
if (!response.ok) {
throw new Error(`Failed to load categories: ${response.statusText}`);
}
allowedCategories = await response.json();
} catch (error) {
console.error(error);
statusEl.textContent = 'Error: Could not load categories.';
}
}
async function loadProjectsData() {
try {
const response = await fetch(PROJECTS_URL);
if (!response.ok) {
throw new Error(`Failed to load projects: ${response.statusText}`);
}
projectsData = await response.json();
} catch (error) {
console.error(error);
statusEl.textContent = 'Error: Could not load projects.';
}
}
// Load the pre-computed repository statistics cache. Never throws: a missing
// or broken cache must not prevent the catalogue from rendering.
async function loadRepoStats() {
try {
const response = await fetch(REPO_STATS_URL);
if (!response.ok) {
throw new Error(`Failed to load repository stats: ${response.status}`);
}
const data = await response.json();
if (!data || typeof data !== 'object' || typeof data.repos !== 'object') {
throw new Error('Malformed repository stats cache');
}
repoStats = data;
repoStatsIndex = new Map(
Object.entries(data.repos).map(([key, value]) => [key.toLowerCase(), value])
);
} catch (error) {
console.warn(error);
repoStats = null;
repoStatsIndex = new Map();
statusEl.textContent = 'Catalogue loaded, but repository statistics are unavailable.';
}
}
function findCategory(categoryString) {
if (!categoryString) return null;
const cat = allowedCategories.find(c =>
c.name.toLowerCase() === categoryString.toLowerCase() ||
(c.aliases && c.aliases.map(a => a.toLowerCase()).includes(categoryString.toLowerCase()))
);
return cat ? cat.name : null;
}
// Derive a Category from a filename of the form "name.<category>.json" and
// inject it into every record. Shared by the local-file handler, the raw-file
// fallback and the primary fetch path in loadDataFromServer. Returns [] when
// the derived category is invalid or the payload is not an array.
function injectCategoryFromFilename(data, fileName) {
const dotCount = (fileName.match(/\./g) || []).length;
if (dotCount >= 2) {
const match = fileName.match(/^.*\.(.*?)\.json$/i);
const categoryString = match ? match[1] : fileName.replace(/\.json$/i, '');
const categoryName = findCategory(categoryString);
if (categoryName) {
return Array.isArray(data) ? data.map(item => ({ ...item, Category: categoryName })) : [];
}
console.warn(`Skipping file with invalid category: ${fileName}`);
return [];
}
return Array.isArray(data) ? data : [];
}
// Compute the sorted filter-dropdown option list for a column, based on the
// current masterData and filterState. Shared by buildTable (on open) and
// refreshOpenDropdown (when another filter changes). Selected values first,
// then valid, then invalid (grayed/disabled), each group alphabetical.
function computeColumnFilterItems(col) {
const allPossibleValues = [...new Set(masterData.flatMap(r => {
const v = r[col];
return Array.isArray(v) ? v : [v];
}))].sort();
const selectedValues = new Set(filterState[col] || []);
const otherFilters = { ...filterState };
delete otherFilters[col];
const partiallyFilteredData = masterData.filter(row =>
Object.entries(otherFilters).every(([filterCol, vals]) => {
const cell = row[filterCol];
return Array.isArray(cell) ? cell.some(v => vals.includes(v)) : vals.includes(String(cell));
})
);
const validValues = new Set(partiallyFilteredData.flatMap(r => {
const v = r[col];
return Array.isArray(v) ? v : [v];
}));
const items = allPossibleValues.map(val => ({
value: val,
isSelected: selectedValues.has(val),
isValid: validValues.has(val)
}));
items.sort((a, b) => {
if (a.isSelected !== b.isSelected) return a.isSelected ? -1 : 1;
if (a.isValid !== b.isValid) return a.isValid ? -1 : 1;
return String(a.value ?? '').localeCompare(String(b.value ?? ''));
});
return items;
}
// Derive a GitHub API contents URL from a GitHub Pages or repo URL.
// Examples supported:
// - https://{owner}.github.io/{repo} -> https://api.github.com/repos/{owner}/{repo}/contents/ips
// - https://github.com/{owner}/{repo} -> https://api.github.com/repos/{owner}/{repo}/contents/ips
function deriveGithubApiContentsUrl(base) {
try {
const u = new URL(base);
const host = u.hostname.toLowerCase();
const rawPath = u.pathname.replace(/^\/+|\/+$/g, ''); // trim slashes
// Case: user/project pages like owner.github.io/repo
if (host.endsWith('.github.io')) {
const owner = host.replace('.github.io', '');
const repo = rawPath.split('/')[0] || '';
if (!repo) return null; // can't derive repo
return `https://api.github.com/repos/${owner}/${repo}/contents/ips`;
}
// Case: direct github.com URL
if (host === 'github.com') {
const parts = rawPath.split('/').filter(Boolean);
if (parts.length >= 2) {
const owner = parts[0];
const repo = parts[1];
return `https://api.github.com/repos/${owner}/${repo}/contents/ips`;
}
}
return null;
} catch (e) {
return null;
}
}
// Parse a GitLab project URL into { host, projectPath } for any host whose
// name contains "gitlab" (gitlab.com, self-hosted instances, *.gitlab.io
// Pages). Everything from the "/-/" marker onward is UI navigation and is
// stripped. Known limitation: nested subgroups are not resolved; only the
// first two path segments form the project path.
function parseGitlabProjectUrl(u) {
const host = u.hostname.toLowerCase();
if (host !== 'gitlab.com' && !host.includes('gitlab')) return null;
const parts = u.pathname.replace(/^\/+/g, '').split('/').filter(Boolean);
const dashIdx = parts.indexOf('-'); // GitLab inserts "/-/" before UI routes
let pathParts = dashIdx !== -1 ? parts.slice(0, dashIdx) : parts.slice();
pathParts = pathParts.filter(p => p.length);
if (host.endsWith('.gitlab.io')) {
// Pages URL: the group is the subdomain, first segment is the project.
const group = host.replace(/\.gitlab\.io$/, '');
if (!group || !pathParts.length) return null;
return { host, projectPath: `${group}/${pathParts[0]}` };
}
if (pathParts.length < 2) return null;
return { host, projectPath: pathParts.slice(0, 2).join('/') };
}
// Derive GitLab REST API v4 URLs for the ips/ directory of a GitLab-hosted
// checkout. Returns { listUrl, fileUrl(path) } or null when base is not a
// derivable GitLab project URL.
function deriveGitlabApiUrl(base) {
try {
const parsed = parseGitlabProjectUrl(new URL(base));
if (!parsed) return null;
const encoded = encodeURIComponent(parsed.projectPath);
const apiBase = `https://${parsed.host}/api/v4/projects/${encoded}`;
return {
listUrl: `${apiBase}/repository/tree?path=ips&per_page=100`,
// The raw files endpoint accepts ref=HEAD, so no branch guessing.
fileUrl: p => `${apiBase}/repository/files/${encodeURIComponent(p)}/raw?ref=HEAD`
};
} catch (e) {
return null;
}
}
// Derive repository-API fallback URLs from a hosting base URL, shared by the
// two fallback sites in loadDataFromServer. Returns { gitlabApi, apiUrl } where
// apiUrl is the GitHub contents URL when derivable, otherwise the GitLab tree
// listing URL (or null). gitlabApi is returned so callers can build raw file URLs.
function deriveFallbackApiInfo(base) {
const gitlabApi = deriveGitlabApiUrl(base);
const apiUrl = deriveGithubApiContentsUrl(base) || (gitlabApi ? gitlabApi.listUrl : null);
return { gitlabApi, apiUrl };
}
// Try to derive a raw file URL (raw.githubusercontent.com or GitLab) for a
// given filename. Uses BASE_URL or the provided file url as hints. Best-effort
// only; assumes branch "main" (GitHub) / HEAD (GitLab) if none can be determined.
function deriveRawUrlFromHints(base, filename, hintUrl) {
try {
// 0) GitLab-hosted checkout: https://{host}/{group}/{project}/-/raw/{branch}/ips/{filename}
const gitlabBase = parseGitlabProjectUrl(new URL(base));
if (gitlabBase) {
return `https://${gitlabBase.host}/${gitlabBase.projectPath}/-/raw/HEAD/ips/${filename}`;
}
// 1) Try to extract owner/repo from the API contents URL derived from base
const api = deriveGithubApiContentsUrl(base);
let owner = null, repo = null, branch = 'main';
if (api) {
const m = api.match(/repos\/([^\/]+)\/([^\/]+)\/contents/);
if (m) {
owner = m[1]; repo = m[2];
}
}
// 2) If not found, inspect the hintUrl (could be api.github.com, github.com, or a pages URL)
if (!owner || !repo) {
if (hintUrl) {
try {
const u = new URL(hintUrl);
if (u.hostname === 'api.github.com') {
const parts = u.pathname.split('/').filter(Boolean);
// /repos/{owner}/{repo}/contents/...
const reposIdx = parts.indexOf('repos');
if (reposIdx !== -1 && parts.length >= reposIdx + 3) {
owner = parts[reposIdx + 1];
repo = parts[reposIdx + 2];
}
// Attempt to pick a ref query param if present
const ref = u.searchParams.get('ref');
if (ref) branch = ref;
} else if (u.hostname === 'github.com') {
const parts = u.pathname.split('/').filter(Boolean);
// /{owner}/{repo}/blob/{branch}/path
if (parts.length >= 2) {
owner = parts[0]; repo = parts[1];
const blobIdx = parts.indexOf('blob');
if (blobIdx !== -1 && parts.length > blobIdx + 1) branch = parts[blobIdx + 1];
}
} else if (u.hostname.endsWith('.github.io')) {
owner = u.hostname.replace('.github.io','');
const segments = u.pathname.replace(/^\/+|\/+$/g,'').split('/').filter(Boolean);
if (segments.length) repo = segments[0];
}
} catch (_) {}
}
}
if (owner && repo) {
return `https://raw.githubusercontent.com/${owner}/${repo}/${branch}/ips/${filename}`;
}
} catch (e) {
// fallback returns null
}
return null;
}
// Update or create a small badge element next to `#status` that shows which
// source was ultimately used to build the file list. Use short labels.
function updateFetchSourceBadge(sourceLabel) {
try {
let badge = document.getElementById('fetch-source-badge');
if (!badge) {
badge = document.createElement('span');
badge.id = 'fetch-source-badge';
badge.style.marginLeft = '10px';
badge.style.fontSize = '0.86em';
badge.style.padding = '2px 6px';
badge.style.borderRadius = '4px';
badge.style.background = '#eef';
badge.style.color = '#033';
// insert after the status element so status text updates won't remove it
if (statusEl && statusEl.parentNode) statusEl.parentNode.insertBefore(badge, statusEl.nextSibling);
}
badge.textContent = sourceLabel;
} catch (e) {
// non-fatal
console.debug('Could not update fetch source badge', e);
}
}
// Add event listener for the search input
document.getElementById('search-input').addEventListener('input', e => {
searchText = e.target.value.trim().toLowerCase();
applyFilters();
});
// Entry Point: Handle Load-Mode Switch
loadRadios.forEach(radio => {
radio.addEventListener('change', async () => {
resetTable();
if (radio.value === 'github' && radio.checked) {
fileInput.style.display = 'none';
await Promise.all([loadProjectsData(), loadRepoStats()]);
loadDataFromServer();
}
if (radio.value === 'local' && radio.checked) {
fileInput.style.display = 'inline-block';
statusEl.textContent = 'Select one or more local JSON files.';
await Promise.all([loadProjectsData(), loadRepoStats()]);
}
});
});
// Local File Handling
fileInput.addEventListener('change', async event => {
const files = Array.from(event.target.files);
if (!files.length) return;
resetTable();
try {
await Promise.all([loadAllowedCategories(), loadRepoStats()]);
statusEl.textContent = `Reading ${files.length} local file(s)…`;
const arrs = await Promise.all(files.map(file => {
return new Promise((res, rej) => {
const reader = new FileReader();
reader.onload = () => {
try {
const data = JSON.parse(reader.result);
// Only inject Category if filename has at least 2 dots
const dotCount = (file.name.match(/\./g) || []).length;
if (dotCount >= 2) {
const match = file.name.match(/^.*\.(.*?)\.json$/i);
const categoryString = match ? match[1] : file.name.replace(/\.json$/i,'');
const categoryName = findCategory(categoryString);
if (categoryName) {
res(Array.isArray(data)
? data.map(item => ({ ...item, Category: categoryName }))
: []);
} else {
console.warn(`Skipping file with invalid category: ${file.name}`);
res([]);
}
} else {
res(Array.isArray(data) ? data : []);
}
} catch(e) {
rej(`Invalid JSON: ${file.name}`);
}
};
reader.onerror = () => rej(`Read error: ${file.name}`);
reader.readAsText(file);
});
}));
masterData = arrs.flat();
masterData.sort((a, b) => String(a.Name ?? '').localeCompare(String(b.Name ?? '')));
filteredData = [...masterData];
deriveColumns();
applyFilters();
buildTable();
setInitialFilterSelections(parseFiltersFromQuery()); // Apply URL filters now
statusEl.textContent = 'Local files loaded.';
srStatus.textContent = `${filteredData.length} items loaded from local files.`;
exportBtn.disabled = false;
} catch(err) {
statusEl.textContent = 'Error: ' + err;
console.error(err);
}
});
// Load Virtual Repo IPs info from server (GitHub or self hosted)
async function loadDataFromServer() {
let ips_url;
// Normalize BASE_URL and avoid double-appending IPS_PATH.
// Many callers set BASE_URL to the site root (e.g. https://.../),
// and we append IPS_PATH. But if BASE_URL already contains
// the ips subpath (e.g. someone set BASE_URL = '.../ips/'),
// appending would produce '.../ips/ips/' and result in 404s.
// Build ips_url by separating query part (if present), ensuring
// the base path ends with exactly one IPS_PATH, then reattach query.
const queryPos = BASE_URL.indexOf("?");
const baseNoQuery = queryPos !== -1 ? BASE_URL.slice(0, queryPos) : BASE_URL;
const queryPart = queryPos !== -1 ? BASE_URL.slice(queryPos) : '';
// Ensure there is exactly one trailing slash on baseNoQuery for safe concatenation
const normalizedBase = baseNoQuery.endsWith('/') ? baseNoQuery : baseNoQuery + '/';
if (normalizedBase.endsWith(IPS_PATH)) {
// BASE_URL already points into the ips folder; use it as-is (preserving query)
ips_url = BASE_URL;
} else {
// Append IPS_PATH once, then reattach any query string.
ips_url = normalizedBase + IPS_PATH.replace(/^\//, '');
if (queryPart) ips_url += queryPart;
}
try {
await Promise.all([loadAllowedCategories(), loadRepoStats()]);
statusEl.textContent = 'Fetching file list from the hosting server…';
statusEl.textContent = `Fetching file list from ${ips_url}…`;
// indicate we attempted the same-origin directory listing first
updateFetchSourceBadge('Directory listing (attempt)');
let resp = await fetch(ips_url);
// If the pages URL returns a non-OK status, attempt a GitHub API fallback
// immediately rather than aborting — this handles GitHub Pages 404s or
// directory listings that aren't machine-friendly.
if (!resp.ok) {
console.warn(`Primary fetch failed (${resp.status}) for ${ips_url}`);
statusEl.textContent = `Fetch ${resp.status} from the listing; trying repository API fallback…`;
try {
// Only fall back to APIs derivable from the current location — never
// silently pull someone else's repository.
const gitlabApi = deriveGitlabApiUrl(BASE_URL);
const apiUrl = deriveGithubApiContentsUrl(BASE_URL) || (gitlabApi ? gitlabApi.listUrl : null);
if (!apiUrl) {
throw new Error('no GitHub/GitLab API URL could be derived from this hosting location');
}
const apiResp = await fetch(apiUrl);
if (apiResp.ok) {
// Use the API response body as the primary 'text' source below
const apiText = await apiResp.text();
var text = apiText;
updateFetchSourceBadge('Derived repository API');
} else {
throw new Error(`API fallback fetch ${apiResp.status}`);
}
} catch (e) {
// Re-throw a helpful error for the outer catch to handle and report
throw new Error(`Failed to fetch the IPS list from ${ips_url} (${resp.status}) and the API fallback failed: ${e.message}`);
}
} else {
// Normal path: read the response text from the primary fetch
var text = await resp.text();
updateFetchSourceBadge('Directory listing');
}
let parsed = null;
try {
parsed = JSON.parse(text);
} catch (e) {
parsed = null;
}
let fileEntries = [];
if (Array.isArray(parsed)) {
// Case A: array of strings (filenames) or array of objects (GitHub API)
if (parsed.length && typeof parsed[0] === 'string') {
// Array of filenames — resolve relative to the base URL
const base = ips_url.endsWith('/') ? ips_url : ips_url + '/';
fileEntries = parsed.filter(n => n.endsWith('.json')).map(n => ({ name: n, url: new URL(n, base).toString() }));
} else {
// Array of objects (likely GitHub API). Prefer download_url, fall back to url/html_url
fileEntries = parsed
.filter(i => i && ((i.type === 'file') || (i.name && i.name.endsWith('.json'))))
.map(i => ({ name: i.name, url: i.download_url || i.url || i.html_url }));
}
} else {
// Case B: Not JSON — try to extract hrefs from HTML listing
const hrefs = Array.from(text.matchAll(/href=["']([^"']+\.json)["']/gi)).map(m => m[1]);
fileEntries = hrefs.map(h => {
try {
const full = new URL(h, ips_url).toString();
const name = full.split('/').pop();
return { name, url: full };
} catch (e) {
return null;
}
}).filter(Boolean);
}
// Deduplicate by filename (keep first seen)
const seen = new Map();
fileEntries.forEach(fe => {
if (!fe || !fe.name || !fe.url) return;
if (!fe.name.endsWith('.json')) return;
if (!seen.has(fe.name)) seen.set(fe.name, fe.url);
});
let finalFiles = Array.from(seen.entries()).map(([name, url]) => ({ name, url }));
// If the listing returned no usable files, try a repository API fallback
// derived from the current location (GitHub or GitLab), which reliably
// lists repository contents.
if (finalFiles.length === 0) {
const gitlabApi = deriveGitlabApiUrl(BASE_URL);
const apiUrl = deriveGithubApiContentsUrl(BASE_URL) || (gitlabApi ? gitlabApi.listUrl : null);
if (apiUrl) {
try {
statusEl.textContent = 'No files found in the listing — trying repository API fallback…';
const apiResp = await fetch(apiUrl);
if (apiResp && apiResp.ok) {
const apiJson = await apiResp.json();
if (Array.isArray(apiJson) && apiJson.length) {
let apiFiles;
if (gitlabApi && !deriveGithubApiContentsUrl(BASE_URL)) {
// GitLab tree entries: keep files only, build raw file URLs.
apiFiles = apiJson
.filter(i => i && i.type === 'blob' && i.name && i.name.endsWith('.json'))
.map(i => ({ name: i.name, url: gitlabApi.fileUrl(`ips/${i.path || i.name}`) }));
} else {
apiFiles = apiJson
.filter(i => i && ((i.type === 'file') || (i.name && i.name.endsWith('.json'))))
.map(i => ({ name: i.name, url: i.download_url || i.url || i.html_url }));
}
const seenApi = new Map();
apiFiles.forEach(f => { if (f && f.name && f.url && !seenApi.has(f.name)) seenApi.set(f.name, f.url); });
const apiFinal = Array.from(seenApi.entries()).map(([name, url]) => ({ name, url }));
if (apiFinal.length) {
finalFiles = apiFinal;
updateFetchSourceBadge('Derived repository API');
}
}
}
} catch (e) {
console.warn('Repository API fallback failed', e);
}
}
}
statusEl.textContent = `Found ${finalFiles.length} remote JSONs; loading…`;
const arrs = await Promise.all(finalFiles.map(async f => {
// Try the primary URL first
let r = null;
try { r = await fetch(f.url); } catch (e) { r = null; }
if (!r || !r.ok) {
console.warn(`Failed to fetch ${f.url}: ${r ? r.status : 'network'}`);
// Best-effort: attempt a raw.githubusercontent.com URL derived from hints
const rawUrl = deriveRawUrlFromHints(BASE_URL, f.name, f.url);
if (rawUrl) {
try {
const r2 = await fetch(rawUrl);
if (r2 && r2.ok) {
updateFetchSourceBadge('Raw file fallback');
const txt2 = await r2.text();
try {
const data = JSON.parse(txt2);
// proceed with category injection below
const dotCount = (f.name.match(/\./g) || []).length;
if (dotCount >= 2) {
const match = f.name.match(/^.*\.(.*?)\.json$/i);
const categoryString = match ? match[1] : f.name.replace(/\.json$/i, '');
const categoryName = findCategory(categoryString);
if (categoryName) return Array.isArray(data) ? data.map(item => ({ ...item, Category: categoryName })) : [];
console.warn(`Skipping file with invalid category: ${f.name}`);
return [];
} else {
return Array.isArray(data) ? data : [];
}
} catch (e) {
console.warn(`Invalid JSON at ${rawUrl}`);
return [];
}
}
} catch (e) {
console.warn('raw.githubusercontent fallback failed', e);
}
}
return [];
}
const txt2 = await r.text();
let data;
try {
data = JSON.parse(txt2);
} catch (e) {
console.warn(`Invalid JSON at ${f.url}`);
return [];
}
const dotCount = (f.name.match(/\./g) || []).length;
if (dotCount >= 2) {
const match = f.name.match(/^.*\.(.*?)\.json$/i);
const categoryString = match ? match[1] : f.name.replace(/\.json$/i, '');
const categoryName = findCategory(categoryString);
if (categoryName) {
return Array.isArray(data) ? data.map(item => ({ ...item, Category: categoryName })) : [];
} else {
console.warn(`Skipping file with invalid category: ${f.name}`);
return [];
}
} else {
return Array.isArray(data) ? data : [];
}
}));
masterData = arrs.flat();
masterData.sort((a, b) => String(a.Name ?? '').localeCompare(String(b.Name ?? '')));
filteredData = [...masterData];
deriveColumns();
applyFilters();
buildTable();
setInitialFilterSelections(parseFiltersFromQuery()); // Apply URL filters now
dataLoaded = true;
if (pendingSearch !== null) {
searchText = pendingSearch.toLowerCase();
const searchInput = document.getElementById('search-input');
if (searchInput) searchInput.value = pendingSearch;
pendingSearch = null;
applyFilters();
}
statusEl.textContent = 'Catalogue data loaded.';
srStatus.textContent = `${filteredData.length} items loaded from the catalogue source.`;
exportBtn.disabled = false;
} catch (err) {
statusEl.textContent = 'Error: ' + (err.message || err);
console.error(err);
}
}
// Helpers
function resetTable() {
masterData = [];
filteredData = [];
columns = [];
thead.innerHTML = '';
tbody.innerHTML = '';
exportBtn.disabled = true;
}
function buildTable() {
thead.innerHTML = '';
tbody.innerHTML = '';
let cg = table.querySelector('colgroup');
if (!cg) {
cg = document.createElement('colgroup');
table.insertBefore(cg, thead);
}
cg.innerHTML = '';
// Default initial column widths
const DEFAULT_COL_WIDTHS = {
'Project': '140px',
'Name': '320px',
'Category': '180px',
'License': '170px',
'Status': '170px',
'Repo Stats': '200px',
'IP Card': '110px',
};
visibleColumns.forEach(col => {
const colEl = document.createElement('col');
const w = DEFAULT_COL_WIDTHS[col];
if (w) colEl.style.width = w;
cg.appendChild(colEl);
});
const headerRow = document.createElement('tr');
// Columns whose cells are not simple values: no per-value filter dropdown.
const SKIP_DROPDOWN = new Set(['Description', 'Comment', 'Repo Stats', IP_CARD_COLUMN]);
visibleColumns.forEach((col, i) => {
const th = document.createElement('th');
th.style.position = 'relative';
th.style.verticalAlign = 'top';
// If this column is in the skip-list, render a plain, non-interactive label
if (SKIP_DROPDOWN.has(col)) {
const labelDiv = document.createElement('div');
labelDiv.className = 'header-label';
labelDiv.textContent = col;
labelDiv.style.padding = '6px 4px';
labelDiv.setAttribute('aria-hidden', 'false');
th.appendChild(labelDiv);
headerRow.appendChild(th);
return; // skip dropdown construction and listeners for this column
}
// Header button: use the column name itself as the dropdown toggle for filters
const dropdown = document.createElement('div');
dropdown.className = 'custom-dropdown';
dropdown.tabIndex = 0;
const headerBtn = document.createElement('button');
// text content is just the column name; caret is provided via CSS ::after
headerBtn.textContent = columnLabels[col] || col;
headerBtn.type = 'button';
headerBtn.className = 'header-filter-btn';
// Accessibility: indicate this button opens a popup and manage expanded state
headerBtn.setAttribute('aria-haspopup', 'true');
headerBtn.setAttribute('aria-expanded', 'false');
const portalId = `portal-dropdown-${col.replace(/\s+/g,'_')}-${i}`;
headerBtn.setAttribute('aria-controls', portalId);
// Keyboard: allow Enter/Space to open the dropdown
headerBtn.addEventListener('keydown', e => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
headerBtn.click();
}
});
th.appendChild(headerBtn);
const dropdownContent = document.createElement('div');
dropdownContent.className = 'dropdown-content';
// Accessibility: mark as a popup menu for assistive tech
dropdownContent.setAttribute('role', 'menu');
dropdownContent.setAttribute('aria-label', `Filter ${col}`);
// attach header button as the visible toggle
dropdown.appendChild(headerBtn);
dropdown.appendChild(dropdownContent);
th.appendChild(dropdown);
// Toggle dropdown visibility
headerBtn.addEventListener('click', e => {
e.stopPropagation();
// If this column's portal is already open, close it (toggle behavior)
const existingPortal = document.getElementById(portalId);
if (existingPortal) {
existingPortal.remove();
headerBtn.setAttribute('aria-expanded', 'false');
return;
}
// Clear previous content and rebuild it based on the CURRENT filter state.
dropdownContent.innerHTML = '';
// Add search input to dropdown
const searchInput = document.createElement('input');
searchInput.type = 'text';
searchInput.placeholder = 'Search...';
searchInput.style.width = '100%';
dropdownContent.appendChild(searchInput);
// 1. Get all possible unique values for the current column from the master dataset.
const allPossibleValues = [...new Set(masterData.flatMap(r => {
const v = r[col];
return Array.isArray(v) ? v : [v];
}))].sort();
// 2. Determine which values are currently selected for this column.
const selectedValues = new Set(filterState[col] || []);
// 3. Determine which values are "valid" based on filters applied to *other* columns.
const otherFilters = { ...filterState };
delete otherFilters[col];
const partiallyFilteredData = masterData.filter(row =>
Object.entries(otherFilters).every(([filterCol, vals]) => {
const cell = row[filterCol];
return Array.isArray(cell) ? cell.some(v => vals.includes(v)) : vals.includes(String(cell));
})
);
const validValues = new Set(partiallyFilteredData.flatMap(r => {
const v = r[col];
return Array.isArray(v) ? v : [v];
}));
// 4. Categorize all possible values for sorting and rendering.
const items = allPossibleValues.map(val => ({
value: val,
isSelected: selectedValues.has(val),
isValid: validValues.has(val)
}));
// 5. Sort the items: selected first, then valid, then invalid (grayed out).
items.sort((a, b) => {
if (a.isSelected !== b.isSelected) return a.isSelected ? -1 : 1;
if (a.isValid !== b.isValid) return a.isValid ? -1 : 1;
return String(a.value ?? '').localeCompare(String(b.value ?? ''));
});
// 6. Create and append the checkbox elements.
items.forEach(item => {
const label = document.createElement('label');
label.style.display = 'block';
label.style.padding = '6px';
label.style.cursor = 'pointer';
label.setAttribute('role', 'menuitem');
const cb = document.createElement('input');
cb.type = 'checkbox';
cb.value = item.value;
cb.dataset.column = col;
cb.checked = item.isSelected;
cb.setAttribute('role', 'menuitemcheckbox');
cb.setAttribute('aria-checked', cb.checked ? 'true' : 'false');
if (!item.isValid && !item.isSelected) {
cb.disabled = true;
label.style.color = '#999';
label.style.cursor = 'not-allowed';
}
label.appendChild(cb);
label.appendChild(document.createTextNode(item.value));
dropdownContent.appendChild(label);
});
// --- END: On-demand dropdown generation ---
// Remove any other existing portal dropdowns
document.querySelectorAll('.portal-dropdown').forEach(dc => dc.remove());
// Get button position
const rect = headerBtn.getBoundingClientRect();
// Clone dropdownContent and expose it as a portal dropdown
const portalDropdown = dropdownContent.cloneNode(true);
portalDropdown.className = 'dropdown-content portal-dropdown';
portalDropdown.id = portalId;
portalDropdown.dataset.column = col; // Add column context to the portal
portalDropdown.style.position = 'absolute';
portalDropdown.style.left = rect.left + 'px';
portalDropdown.style.top = (rect.bottom + window.scrollY) + 'px';
portalDropdown.style.zIndex = 99999;
portalDropdown.style.display = 'block';
portalDropdown.style.background = '#fff';
portalDropdown.style.border = '1px solid #ccc';
portalDropdown.style.maxHeight = '400px';
portalDropdown.style.overflowY = 'auto';
portalDropdown.style.width = rect.width + 'px';
// Add search functionality to the portal dropdown's search input
const portalSearchInput = portalDropdown.querySelector('input[type="text"]');
if (portalSearchInput) {
portalSearchInput.addEventListener('input', e => {
const filter = e.target.value.toLowerCase();
const labels = portalDropdown.querySelectorAll('label');
labels.forEach(label => {
const text = label.textContent.toLowerCase();
label.style.display = text.includes(filter) ? 'block' : 'none';
});
});
}
// Sync checked state from original dropdown
portalDropdown.querySelectorAll('input[type="checkbox"]').forEach(cb => {
const orig = dropdownContent.querySelector(`input[value="${cb.value}"]`);
if (orig) {
cb.checked = orig.checked;
cb.setAttribute('aria-checked', cb.checked ? 'true' : 'false');
}
// When changed, update original dropdown and apply filter
cb.addEventListener('change', () => {
if (orig) {
orig.checked = cb.checked;
orig.setAttribute('aria-checked', orig.checked ? 'true' : 'false');
}
cb.setAttribute('aria-checked', cb.checked ? 'true' : 'false');
applyFilters();
refreshOpenDropdown();
});
});
document.body.appendChild(portalDropdown);
// Mark as expanded for assistive tech
headerBtn.setAttribute('aria-expanded', 'true');
// Hide on outside click
document.addEventListener('click', function hideDropdown(ev) {
if (!portalDropdown.contains(ev.target) && ev.target !== headerBtn) {
const p = document.getElementById(portalId);
if (p) {
p.remove();
headerBtn.setAttribute('aria-expanded', 'false');
}
document.removeEventListener('click', hideDropdown);
// remove esc handler if present
document.removeEventListener('keydown', escHandler);
}
});
// Close on Escape key for accessibility
function escHandler(ev) {
if (ev.key === 'Escape' || ev.key === 'Esc') {
if (portalDropdown && portalDropdown.parentNode) {
portalDropdown.remove();
}
headerBtn.setAttribute('aria-expanded', 'false');
document.removeEventListener('keydown', escHandler);
}
}
document.addEventListener('keydown', escHandler);
});
// Hide dropdown when clicking outside (original inline content)
document.addEventListener('click', () => {
dropdownContent.style.display = 'none';
headerBtn.setAttribute('aria-expanded', 'false');
});
dropdown.addEventListener('click', e => e.stopPropagation());
headerRow.appendChild(th);
});
thead.appendChild(headerRow);
makeResizable(headerRow);
// Render rows (even if empty)
renderRows(filteredData);
}
// Returns a numeric score representing the completeness of a row, where lower is better
function getCompletenessScore(row) {
const allFields = [...new Set(masterData.flatMap(Object.keys))];
let emptyCount = 0;
for (const field of allFields) {
const value = row[field];
if (value == null || value === '') {
emptyCount++;
} else if (Array.isArray(value) && value.length === 0) {
emptyCount++;
} else if (String(value).trim().toUpperCase() === 'TBD') {
emptyCount++;
}
}
return emptyCount;
}
// Update applyFilters for OR logic
function applyFilters(initialState = null) {
if (initialState) {
// If an initial state is provided (from URL), use it directly.
filterState = initialState;
} else {
// Otherwise, build the filter state from the DOM (user interaction).
const newFilterState = {};
const openPortal = document.querySelector('.portal-dropdown');
if (openPortal) {
const checkedCbs = openPortal.querySelectorAll('input[type="checkbox"]:checked');
if (checkedCbs.length > 0) {
const col = checkedCbs[0].dataset.column;