-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathitem_detail.js
More file actions
245 lines (221 loc) · 7.77 KB
/
Copy pathitem_detail.js
File metadata and controls
245 lines (221 loc) · 7.77 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
/**
* item_detail.js
*
* Shared utility for GameDB item detail pages.
* Each page calls `loadItemDetail(endpoint, renderFn)` on DOMContentLoaded.
*
* The page URL is expected to contain `?id=<item_id>`.
*
* Requires window.GAMEDB_CONFIG to be set by an inline <script> in the page:
* window.GAMEDB_CONFIG = { base_path: "{{ site.baseurl }}", base_url: "{{ site.url }}{{ site.baseurl }}" };
*/
const base_path = (globalThis.GAMEDB_CONFIG?.base_path
? ("/" + globalThis.GAMEDB_CONFIG.base_path).replaceAll(/\/+/g, "/").replace(/\/$/, "")
: "/GameDB");
const base_url = globalThis.location.origin + base_path;
/**
* Read a query-string parameter from the current URL.
* @param {string} name
* @returns {string|null}
*/
function getQueryParam(name) {
const params = new URLSearchParams(globalThis.location.search);
return params.get(name);
}
/**
* Build an IGDB image URL at a given size.
* @param {string} url - raw URL from IGDB (may start with //)
* @param {string} [size="t_cover_big"]
* @returns {string}
*/
function igdbImageUrl(url, size = "t_cover_big") {
if (!url) return null;
return url.replace("t_thumb", size).replace(/^\/\//, "https://");
}
/**
* Create a Bootstrap badge element.
* @param {string} text
* @param {string} [cls="bg-secondary"]
* @returns {HTMLElement}
*/
function makeBadge(text, cls = "bg-secondary") {
const b = document.createElement("span");
b.className = `badge ${cls} me-1 mb-1`;
b.style.whiteSpace = "nowrap";
b.textContent = text;
return b;
}
/**
* Render a key-value row inside a <dl>.
* @param {HTMLElement} dl
* @param {string} label
* @param {string|HTMLElement} value
*/
function addDlRow(dl, label, value) {
const dt = document.createElement("dt");
dt.className = "col-sm-4 col-md-3 fw-semibold";
dt.textContent = label;
dl.appendChild(dt);
const dd = document.createElement("dd");
dd.className = "col-sm-8 col-md-9";
if (value instanceof HTMLElement || value instanceof DocumentFragment) {
dd.appendChild(value);
} else {
dd.textContent = value;
}
dl.appendChild(dd);
}
/**
* Show an error message in #item-error and hide #item-content.
* @param {string} message
*/
function showError(message) {
const errEl = document.getElementById("item-error");
const contentEl = document.getElementById("item-content");
if (errEl) {
errEl.textContent = message;
errEl.classList.remove("d-none");
}
if (contentEl) {
contentEl.classList.add("d-none");
}
const loadingEl = document.getElementById("item-loading");
if (loadingEl) loadingEl.classList.add("d-none");
}
/**
* Load an item from the API and call the render function.
* @param {string} endpoint - e.g. "games", "platforms"
* @param {function} renderFn - called with the item data object
*/
function loadItemDetail(endpoint, renderFn) {
const id = getQueryParam("id");
if (!id) {
showError("No item ID specified. Please go back and select an item.");
return;
}
const url = `${base_url}/${endpoint}/${encodeURIComponent(id)}.json`;
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(`Item not found (HTTP ${response.status})`);
}
return response.json();
})
.then(data => {
const loadingEl = document.getElementById("item-loading");
if (loadingEl) loadingEl.classList.add("d-none");
const contentEl = document.getElementById("item-content");
if (contentEl) contentEl.classList.remove("d-none");
renderFn(data);
})
.catch(err => {
showError(`Failed to load item: ${err.message}`);
});
}
/**
* Render a list of game cards (compact) into a container element.
* Games are fetched from individual game files when needed to get cover art.
* @param {HTMLElement} container
* @param {Array<number|object>} games - array of game IDs or game objects with {id, name, cover}
*/
function renderGameList(container, games) {
if (!games || games.length === 0) {
container.textContent = "No games listed.";
return;
}
const row = document.createElement("div");
row.className = "row row-cols-2 row-cols-sm-3 row-cols-md-4 row-cols-lg-6 g-2";
container.appendChild(row);
// Separate games into those with full data and those that need fetching
const gamesToFetch = [];
const gamesWithData = [];
games.forEach(game => {
const gameId = typeof game === "object" ? game.id : game;
const hasFullData = typeof game === "object" && game.name && game.cover;
if (hasFullData) {
gamesWithData.push(game);
} else {
gamesToFetch.push(gameId);
}
});
// Render games that already have full data
gamesWithData.forEach(game => {
/* istanbul ignore next */
renderGameCard(row, game.id, game.name, game.cover ? igdbImageUrl(game.cover.url, "t_cover_small_2x") : null);
});
// Fetch and render games that only have IDs
if (gamesToFetch.length > 0) {
// Fetch each game's data
const fetchPromises = gamesToFetch.map(gameId => {
return fetch(`${base_path}/games/${gameId}.json`)
.then(r => r.ok ? r.json() : null)
.then(gameData => ({ id: gameId, data: gameData }))
.catch(() => ({ id: gameId, data: null }));
});
Promise.all(fetchPromises).then(results => {
results.forEach(({ id, data }) => {
const name = data ? data.name : null;
const coverUrl = data?.cover ? igdbImageUrl(data.cover.url, "t_cover_small_2x") : null;
renderGameCard(row, id, name, coverUrl);
});
});
}
}
/**
* Helper function to render a single game card
*/
function renderGameCard(row, gameId, gameName, coverUrl) {
const col = document.createElement("div");
col.className = "col";
row.appendChild(col);
const card = document.createElement("a");
card.className = "card h-100 text-decoration-none shadow-sm border-0 rounded-0 game-card";
card.href = `${base_path}/browse/games/?id=${gameId}`;
col.appendChild(card);
if (coverUrl) {
const img = document.createElement("img");
img.className = "card-img-top rounded-0";
img.src = coverUrl;
img.alt = gameName || "";
img.loading = "lazy";
card.appendChild(img);
} else {
const placeholder = document.createElement("div");
placeholder.className = "card-img-top bg-secondary d-flex align-items-center justify-content-center";
placeholder.style.height = "120px";
const icon = document.createElement("span");
icon.className = "material-symbols-outlined text-white";
icon.textContent = "sports_esports";
placeholder.appendChild(icon);
card.appendChild(placeholder);
}
const cardBody = document.createElement("div");
cardBody.className = "card-body p-1";
card.appendChild(cardBody);
if (gameName) {
const nameEl = document.createElement("p");
nameEl.className = "card-text small mb-0 text-truncate";
nameEl.textContent = gameName;
nameEl.title = gameName;
cardBody.appendChild(nameEl);
} else {
// Show game ID as fallback
const nameEl = document.createElement("p");
nameEl.className = "card-text small mb-0 text-muted";
nameEl.textContent = `Game #${gameId}`;
cardBody.appendChild(nameEl);
}
}
/* istanbul ignore next */
if (typeof module !== "undefined") {
module.exports = {
getQueryParam,
igdbImageUrl,
makeBadge,
addDlRow,
showError,
loadItemDetail,
renderGameList,
renderGameCard,
};
}