-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
339 lines (294 loc) · 11.7 KB
/
Copy pathmain.js
File metadata and controls
339 lines (294 loc) · 11.7 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
//
// Catalog - Frontend Logic
// This script handles data fetching, searching, filtering, and rendering for code, datasets, models, and spaces.
// Configuration is loaded from config.yaml
//
// SECTION 1: CONFIGURATION AND STATE MANAGEMENT
//
import { load } from 'js-yaml';
import { initializeUIFromConfig, setThemeToggle } from './src/ui/initUserInterface.js';
import { parseUrlParams, updateUrlParams, getCurrentState } from './src/ui/urlManager.js';
import { renderItemList } from './src/ui/render.js';
import { getPlatformApiUrls } from './src/utils/definePlatformVals.js';
import { filterItems, sortItems } from './src/utils/filterAndSort.js';
import { fetchCodeRepos } from './src/api/fetchCodeRepos.js';
import { fetchHfRepos } from './src/api/fetchHfRepos.js';
import { fetchCatalogStats } from './src/api/fetchStats.js';
// Start fetching config immediately when the module loads (before DOMContentLoaded)
// so the fetch is in-flight while the DOM is being parsed.
const configPromise = fetch('config.yaml')
.then(r => {
if (!r.ok) throw new Error(`Failed to load config.yaml: HTTP ${r.status}`);
return r.text();
})
.then(text => load(text));
// Module-scope lets — assigned after config loads, used by all functions below
let CONFIG;
let ORGANIZATION_NAME, HF_ORGANIZATION_NAME, CATALOG_REPO_NAME, PLATFORM, API_BASE_URL, REFRESH_INTERVAL_DAYS, ADDITIONAL_REPOS, ADDITIONAL_HF_REPOS;
let ORG_API_URL, REPO_API_URL, RELEASE_SUFFIX;
let releasesMap = {};
let allItems = {
code: [],
datasets: [],
models: [],
spaces: []
};
let tagsMap = {
code: new Set(),
datasets: new Set(),
models: new Set(),
spaces: new Set()
};
let fetchedData = {
code: false,
datasets: false,
models: false,
spaces: false
};
//
// SECTION 2: DATA FETCHING
//
/**
* Fetches items (code, datasets, models, or spaces) for a given organization from the specified code platform or Hugging Face API.
* @async
* @param {string} repoType - The type of repository to fetch ("code", "datasets", "models", or "spaces").
* @returns {Promise<Array>} An array of item objects.
*/
const fetchHubItems = async (repoType) => {
if (fetchedData[repoType]) {
return allItems[repoType];
}
const skeletons = document.querySelectorAll('.skeleton-card');
skeletons.forEach(s => s.classList.remove('hidden'));
let items = []
if (repoType === 'code') {
// Check that releasesMap is populated; if not, fetch it from releases.json
if (Object.keys(releasesMap).length === 0) {
releasesMap = await fetch('./releases.json')
.then(res => res.ok ? res.json() : {})
.catch(() => ({}));
}
items = await fetchCodeRepos(
PLATFORM,
ADDITIONAL_REPOS,
ORG_API_URL,
REPO_API_URL,
REFRESH_INTERVAL_DAYS,
releasesMap
);
} else {
items = await fetchHfRepos(
repoType,
ADDITIONAL_HF_REPOS,
API_BASE_URL,
HF_ORGANIZATION_NAME,
REFRESH_INTERVAL_DAYS
);
}
// Store fetched items and mark as fetched
allItems[repoType] = items;
fetchedData[repoType] = true;
items.forEach(item => {
item.tags.forEach(tag => tagsMap[repoType].add(tag));
});
skeletons.forEach(s => s.classList.add('hidden'));
return items;
};
//
// SECTION 3: SEARCH, FILTER, AND SORT LOGIC
//
/**
* Applies all filters and sorting to the items and re-renders the list.
* @param {boolean} updateUrl - Whether to update the URL with the current state (default: true).
*/
const applyFiltersAndSort = async (updateUrl = true) => {
const searchTerm = document.getElementById('searchInput').value.toLowerCase();
const sortBy = document.getElementById('sortBy').value;
const tagFilter = document.getElementById('tagFilter').value;
const repoType = document.getElementById('repoType').value;
const archiveFilter = document.getElementById('archiveFilter').value;
let currentItems;
// Update URL with current state if requested
if (updateUrl) {
updateUrlParams(getCurrentState());
}
if (repoType === "all") {
currentItems = [
...allItems.code,
...allItems.datasets,
...allItems.models,
...allItems.spaces
];
} else {
currentItems = allItems[repoType];
}
const filtered = filterItems(currentItems, { searchTerm, tagFilter, archiveFilter });
const sorted = sortItems(filtered, sortBy);
renderItemList(sorted);
};
/**
* Populates the tag filter dropdown with unique tags for the current repository type.
*/
const populateTagFilter = (repoType) => {
const tagFilterElement = document.getElementById('tagFilter');
tagFilterElement.innerHTML = '<option value="">All Tags</option>'; // Reset the options
let allTags = [];
if (repoType === "all") {
// Merge tags from ALL repo types
allTags = [
...tagsMap.code,
...tagsMap.datasets,
...tagsMap.models,
...tagsMap.spaces
];
} else {
allTags = [...tagsMap[repoType]];
}
// remove duplicates and sort tags
// tagsMap already contains normalized (lowercase) tags, so Set automatically handles duplicates
const sortedTags = Array.from(new Set(allTags)).sort();
sortedTags.forEach(tag => {
const option = document.createElement('option');
option.value = tag;
option.textContent = tag;
tagFilterElement.appendChild(option);
});
};
//
// SECTION 4: EVENT LISTENERS AND INITIALIZATION
//
document.addEventListener('DOMContentLoaded', async () => {
// Load config before anything else
try {
CONFIG = await configPromise;
} catch (error) {
console.error('Error loading config.yaml:', error);
// Render visible error banner
const errorDiv = document.createElement('div');
errorDiv.style.cssText = 'position: fixed; top: 20px; left: 50%; transform: translateX(-50%); background: #fee; color: #c33; padding: 15px 20px; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); z-index: 10000; max-width: 90%; text-align: center;';
errorDiv.innerHTML = `<strong>Configuration Error:</strong> ${error.message}. Using default settings.`;
document.body.prepend(errorDiv);
setTimeout(() => errorDiv.remove(), 10000);
// Fall back to defaults so the page isn't completely broken
CONFIG = {
ORGANIZATION_NAME: '', HF_ORGANIZATION_NAME: '', CATALOG_REPO_NAME: '', ORG_NAME: '',
CATALOG_TITLE: 'Catalog', CATALOG_DESCRIPTION: '',
LOGO_URL: '', FAVICON_URL: '',
COLORS: { primary: '#92991c', secondary: '#5d8095', accent: '#0097b2', accentDark: '#4fd1eb', tag: '#9bcb5e' },
PLATFORM: 'github',
API_BASE_URL: 'https://huggingface.co/api/', REFRESH_INTERVAL_DAYS: 30,
ADDITIONAL_REPOS: [], ADDITIONAL_HF_REPOS: [], FONT_FAMILY: 'Inter'
};
}
// Assign module-scope variables used by all functions
// Destructure CONFIG into individual variables for easier access
({
ORGANIZATION_NAME,
HF_ORGANIZATION_NAME,
CATALOG_REPO_NAME,
PLATFORM,
API_BASE_URL,
REFRESH_INTERVAL_DAYS,
ADDITIONAL_REPOS,
ADDITIONAL_HF_REPOS
} = CONFIG);
// Destructure platform-specific API URLs from getPlatformApiUrls
({
org: ORG_API_URL,
repo: REPO_API_URL,
releaseSuffix: RELEASE_SUFFIX
} = getPlatformApiUrls(PLATFORM, ORGANIZATION_NAME));
// Guard: if ORGANIZATION_NAME or HF_ORGANIZATION_NAME is missing (e.g. config.yaml failed to load),
// stop here — proceeding would fire requests like ?author=&full=true which
// could return unbounded results from the Hugging Face API.
if (!ORGANIZATION_NAME || !HF_ORGANIZATION_NAME){
console.error("Organization name is missing for one or both APIs. Halting initialization.");
return;
}
// Initialize UI from config
initializeUIFromConfig(CONFIG);
setThemeToggle();
const searchInput = document.getElementById('searchInput');
const sortBySelect = document.getElementById('sortBy');
const tagFilterSelect = document.getElementById('tagFilter');
const repoTypeSelect = document.getElementById('repoType');
const archiveFilterSelect = document.getElementById('archiveFilter');
// Parse URL parameters to restore state
const urlParams = parseUrlParams();
// Apply URL parameters to form elements if they exist
const validRepoTypes = ['all', 'code', 'datasets', 'models', 'spaces'];
if (urlParams.type && validRepoTypes.includes(urlParams.type)) {
repoTypeSelect.value = urlParams.type;
}
if (urlParams.q) {
searchInput.value = urlParams.q;
}
const validSortValues = ['lastModified', 'createdAt', 'stars_desc', 'stars_asc', 'alphabetical_asc', 'alphabetical_desc'];
if (urlParams.sort && validSortValues.includes(urlParams.sort)) {
sortBySelect.value = urlParams.sort;
}
const initialType = repoTypeSelect.value;
// Restore archive filter from URL
const validArchiveValues = ['active', 'all'];
if (urlParams.archived && validArchiveValues.includes(urlParams.archived)) {
archiveFilterSelect.value = urlParams.archived;
}
// Add input and change event listeners
searchInput.addEventListener('input', applyFiltersAndSort);
sortBySelect.addEventListener('change', applyFiltersAndSort);
tagFilterSelect.addEventListener('change', applyFiltersAndSort);
archiveFilterSelect.addEventListener('change', applyFiltersAndSort);
repoTypeSelect.addEventListener('change', async (event) => {
const newRepoType = event.target.value;
if (newRepoType === "all") {
// Fetch EVERYTHING
await Promise.all([
fetchHubItems("code"),
fetchHubItems("datasets"),
fetchHubItems("models"),
fetchHubItems("spaces")
]);
populateTagFilter("all");
} else {
await fetchHubItems(newRepoType);
populateTagFilter(newRepoType);
}
await applyFiltersAndSort();
});
// Initialize the Catalog Badge (Stars/Forks/Version)
fetchCatalogStats(REPO_API_URL, ORGANIZATION_NAME, CATALOG_REPO_NAME, RELEASE_SUFFIX)
// Load pre-built release data (written by scripts/fetch-releases.js at build time)
releasesMap = await fetch('./releases.json')
.then(res => res.ok ? res.json() : {})
.catch(() => ({}));
//
// >>> INITIAL PAGE LOAD HANDLING <<<
//
if (initialType === "all") {
// If default is ALL, fetch everything at startup
await Promise.all([
fetchHubItems("code"),
fetchHubItems("datasets"),
fetchHubItems("models"),
fetchHubItems("spaces")
]);
populateTagFilter("all");
} else {
// Otherwise fetch just the default repo
await fetchHubItems(initialType);
populateTagFilter(initialType);
}
// Apply tag filter from URL after tags have been populated
if (urlParams.tag) {
// Check if the tag exists in the options
const normalizedUrlTag = urlParams.tag.toLowerCase();
const tagOption = Array.from(tagFilterSelect.options).find(opt => opt.value.toLowerCase() === normalizedUrlTag);
if (tagOption) {
tagFilterSelect.value = tagOption.value;
}
}
// Render initially without updating URL, then sync URL once to reflect actual applied state
// (handles cases where URL params were invalid and not applied)
await applyFiltersAndSort(false);
updateUrlParams(getCurrentState());
});