-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
229 lines (212 loc) · 7.17 KB
/
script.js
File metadata and controls
229 lines (212 loc) · 7.17 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
const PRIMARY_API = "https://www.apicountries.com/countries";
const FALLBACK_API = "https://restcountries.com/v3.1/all";
function computePageSize() {
return 18;
}
let PAGE_SIZE = computePageSize();
const CORS_PROXY = "https://api.allorigins.win/raw?url=";
const countriesContainer = document.getElementById("countries");
const paginationContainer = document.getElementById("pagination");
const searchInput = document.getElementById("searchInput");
const statusEl = document.getElementById("status");
let allCountries = [];
let filteredCountries = [];
let currentPage = 1;
function setStatus(msg, type = "info") {
if (!statusEl) return;
statusEl.textContent = msg;
statusEl.setAttribute("data-type", type);
}
function renderSkeleton(count) {
countriesContainer.innerHTML = "";
for (let i = 0; i < count; i++) {
const sk = document.createElement("div");
sk.className = "skeleton-card";
countriesContainer.appendChild(sk);
}
}
async function fetchJSONWithProxy(url) {
const proxied = CORS_PROXY + encodeURIComponent(url);
const res = await fetch(proxied);
if (!res.ok) throw new Error(`Proxy failed: ${res.status}`);
const text = await res.text();
return JSON.parse(text);
}
async function fetchJSON(url) {
return await fetchJSONWithProxy(url);
}
function normalizeCountry(item) {
const name =
item?.name?.common ??
item?.name?.official ??
item?.name ??
"";
const flags = item?.flags?.png
? { png: item.flags.png, svg: item.flags.svg ?? "" }
: { png: item?.flagPng ?? item?.flag ?? "", svg: item?.flagSvg ?? "" };
const cca3 = item?.cca3 ?? item?.alpha3Code ?? item?.code ?? "";
const capital = Array.isArray(item?.capital)
? item.capital[0] ?? ""
: item?.capital ?? "";
const borders =
Array.isArray(item?.borders) ? item.borders : item?.borders ?? [];
const population = item?.population ?? 0;
const timezones =
Array.isArray(item?.timezones) ? item.timezones : item?.timezones ?? [];
const currenciesObj = item?.currencies ?? {};
const currencies =
Array.isArray(currenciesObj)
? currenciesObj
: Object.keys(currenciesObj).map((k) => {
const c = currenciesObj[k];
return c?.name ? `${c.name} (${k})` : k;
});
const languagesObj = item?.languages ?? {};
const languages =
Array.isArray(languagesObj)
? languagesObj
: Object.values(languagesObj);
return {
name,
flags,
cca3,
capital,
borders,
population,
timezones,
currencies,
languages,
region: item?.region ?? "",
subregion: item?.subregion ?? "",
continents: Array.isArray(item?.continents) ? item.continents : (item?.continent ? [item.continent] : [])
};
}
async function fetchCountries() {
setStatus("Loading countries…", "loading");
countriesContainer.setAttribute("data-loading", "true");
try {
let data = await fetchJSON(PRIMARY_API);
if (!Array.isArray(data) || data.length === 0) {
throw new Error("Primary API returned no data");
}
return data.map(normalizeCountry);
} catch (primaryErr) {
try {
const data = await fetchJSON(FALLBACK_API);
return data.map(normalizeCountry);
} catch (fallbackErr) {
throw fallbackErr;
}
} finally {
countriesContainer.removeAttribute("data-loading");
}
}
function renderCountriesPage(page) {
currentPage = page;
const start = (page - 1) * PAGE_SIZE;
const items = filteredCountries.slice(start, start + PAGE_SIZE);
countriesContainer.innerHTML = "";
items.forEach((c) => {
const card = document.createElement("button");
card.className = "country-card";
card.type = "button";
card.setAttribute("aria-label", `View details for ${c.name}`);
card.innerHTML = `
<img src="${c.flags.png}" alt="Flag of ${c.name}">
<h3>${c.name}</h3>
<p><span class="chip">${(c.continents && c.continents[0]) ? c.continents[0] : (c.region || "")}</span>${c.subregion ? c.subregion : ""}</p>
`;
card.addEventListener("click", () => {
const codeParam = c.cca3 ? `code=${encodeURIComponent(c.cca3)}` : `name=${encodeURIComponent(c.name)}`;
window.location.href = `detail.html?${codeParam}`;
});
countriesContainer.appendChild(card);
});
countriesContainer.classList.remove("fade-in");
void countriesContainer.offsetWidth;
countriesContainer.classList.add("fade-in");
renderPaginationLimited();
}
function renderPaginationLimited() {
const totalPages = Math.ceil(filteredCountries.length / PAGE_SIZE);
paginationContainer.innerHTML = "";
if (totalPages <= 1) return;
const prev = document.createElement("button");
prev.textContent = "Prev";
prev.disabled = currentPage === 1;
prev.addEventListener("click", () => renderCountriesPage(Math.max(1, currentPage - 1)));
paginationContainer.appendChild(prev);
const pages = [];
const pushPage = (p) => {
const btn = document.createElement("button");
btn.textContent = String(p);
if (p === currentPage) btn.className = "active";
btn.addEventListener("click", () => renderCountriesPage(p));
paginationContainer.appendChild(btn);
};
pushPage(1);
let start = Math.max(2, currentPage - 1);
let end = Math.min(totalPages - 1, currentPage + 1);
if (start > 2) {
const dots = document.createElement("button");
dots.textContent = "…";
dots.disabled = true;
paginationContainer.appendChild(dots);
}
for (let p = start; p <= end; p++) pushPage(p);
if (end < totalPages - 1) {
const dots2 = document.createElement("button");
dots2.textContent = "…";
dots2.disabled = true;
paginationContainer.appendChild(dots2);
}
if (totalPages > 1) pushPage(totalPages);
const next = document.createElement("button");
next.textContent = "Next";
next.disabled = currentPage === totalPages;
next.addEventListener("click", () => renderCountriesPage(Math.min(totalPages, currentPage + 1)));
paginationContainer.appendChild(next);
}
function renderEmpty() {
countriesContainer.innerHTML = '<div class="empty">No results found</div>';
paginationContainer.innerHTML = "";
}
function applySearch() {
const q = (searchInput.value || "").trim().toLowerCase();
filteredCountries = allCountries.filter((c) =>
c.name.toLowerCase().includes(q)
);
if (!filteredCountries.length) {
setStatus("No countries match your search", "info");
renderEmpty();
return;
}
setStatus(`Showing ${filteredCountries.length} result(s)`, "info");
renderCountriesPage(1);
}
async function init() {
try {
renderSkeleton(Math.min(PAGE_SIZE, 24));
allCountries = await fetchCountries();
filteredCountries = [...allCountries];
setStatus(`Loaded ${allCountries.length} countries`, "success");
renderCountriesPage(1);
} catch (err) {
console.error(err);
setStatus("Failed to load countries. Please refresh.", "error");
countriesContainer.innerHTML =
"<p class=\"error\">Failed to load countries.</p>";
}
}
searchInput.addEventListener("input", applySearch);
searchInput.addEventListener("keydown", (e) => {
if (e.key === "Enter") applySearch();
});
window.addEventListener("resize", () => {
const newSize = computePageSize();
if (newSize !== PAGE_SIZE) {
PAGE_SIZE = newSize;
renderCountriesPage(1);
}
});
init();