-
Notifications
You must be signed in to change notification settings - Fork 0
/
sidebar.js
414 lines (351 loc) · 12.2 KB
/
sidebar.js
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
// Constants
const BASE_API_URL = "https://api.sofascore.com/api/v1";
const BASE_APP_URL = "https://api.sofascore.app/api/v1";
const BASE_WEBSITE_URL = "https://www.sofascore.com";
const MAJOR_LEAGUES = ["NBA", "MLB", "NHL", "NFL"];
const REFRESH_INTERVAL = 60000; // 1 minute
// DOM Elements
let sportSelect;
let dateSelect;
let hideFinishedCheckbox;
let hideNotStartedCheckbox;
let longnamesCheckbox;
// Wait for DOM to be loaded
document.addEventListener("DOMContentLoaded", () => {
// Initialize DOM elements
sportSelect = document.getElementById("sport-select");
dateSelect = document.getElementById("date-select");
hideFinishedCheckbox = document.getElementById("hide-finished");
hideNotStartedCheckbox = document.getElementById("hide-not-started");
longnamesCheckbox = document.getElementById("longnames");
// Initialize the application
initializeApp();
});
// Utility Functions
function getCurrentDate() {
const today = new Date();
const year = today.getFullYear();
const month = String(today.getMonth() + 1).padStart(2, "0");
const day = String(today.getDate()).padStart(2, "0");
return `${year}-${month}-${day}`;
}
function formatEventTime(timestamp) {
const eventDate = new Date(timestamp * 1000);
let hours = eventDate.getHours();
const minutes = eventDate.getMinutes().toString().padStart(2, "0");
const ampm = hours >= 12 ? "PM" : "AM";
hours = hours % 12 || 12; // Convert 0 to 12
return `${hours}:${minutes} ${ampm}`;
}
// Settings Management
function loadSettings() {
const sport = localStorage.getItem("selectedSport");
const hideFinished = localStorage.getItem("hideFinished");
const hideNotStarted = localStorage.getItem("hideNotStarted");
const longnames = localStorage.getItem("longnames");
sportSelect.value = sport || "football"; // Default to football
hideFinishedCheckbox.checked = hideFinished === "true"; // Default to not checked
hideNotStartedCheckbox.checked = hideNotStarted === "true"; // Default to not checked
longnamesCheckbox.checked = longnames === "true"; // Default to not checked
}
function saveSettings() {
localStorage.setItem("selectedSport", sportSelect.value);
localStorage.setItem("hideFinished", hideFinishedCheckbox.checked);
localStorage.setItem("hideNotStarted", hideNotStartedCheckbox.checked);
localStorage.setItem("longnames", longnamesCheckbox.checked);
}
// Event Listeners
function setupEventListeners() {
sportSelect.addEventListener("change", handleSportChange);
dateSelect.addEventListener("change", handleDateChange);
hideFinishedCheckbox.addEventListener("change", handleFilterChange);
hideNotStartedCheckbox.addEventListener("change", handleFilterChange);
longnamesCheckbox.addEventListener("change", handleLongNamesChange);
}
function handleSportChange() {
saveSettings();
fetchData(sportSelect.value, dateSelect.value);
}
function handleDateChange() {
saveSettings();
fetchData(sportSelect.value, this.value);
}
function handleFilterChange() {
saveSettings();
fetchData(sportSelect.value, dateSelect.value);
}
function handleLongNamesChange() {
saveSettings();
fetchData(sportSelect.value, dateSelect.value);
}
// Data Fetching and Processing
async function fetchData(sport, date) {
try {
const data = await fetchEventData(sport, date);
const scoresDiv = document.getElementById("scores");
scoresDiv.innerHTML = "";
const filters = {
date,
hideFinished: hideFinishedCheckbox.checked,
hideNotStarted: hideNotStartedCheckbox.checked,
longnames: longnamesCheckbox.checked,
};
if (data.events.length === 0) {
const sport =
sportSelect.options[sportSelect.selectedIndex].text.toLowerCase();
displayNoEventsMessage(
scoresDiv,
`No ${sport} events are scheduled for today.`
);
return;
}
const sortedEvents = sortEvents(data.events);
renderEvents(sortedEvents, filters);
if (scoresDiv.children.length === 0) {
displayNoEventsMessage(
scoresDiv,
"No events match the selected filters."
);
}
} catch (error) {
console.error("Fetch error:", error);
displayNoEventsMessage(scoresDiv, "An error occurred while fetching data.");
}
}
async function fetchEventData(sport, date) {
const response = await fetch(
`${BASE_API_URL}/sport/${sport}/scheduled-events/${date}`
);
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
}
function sortEvents(events) {
return events.sort((a, b) => {
const leagueA = a.tournament.name;
const leagueB = b.tournament.name;
const isMajorA = MAJOR_LEAGUES.some((major) => leagueA.includes(major));
const isMajorB = MAJOR_LEAGUES.some((major) => leagueB.includes(major));
if (isMajorA && !isMajorB) return -1;
if (!isMajorA && isMajorB) return 1;
return 0;
});
}
// Rendering Functions
function renderEvents(events, filters) {
const scoresDiv = document.getElementById("scores");
const displayedLeagues = new Set();
events.forEach((event) => {
const eventDateObj = new Date((event.startTimestamp - 4 * 3600) * 1000); // shift to EST
const selectedDateObj = new Date(filters.date);
if (
shouldFilterEvent(event, { ...filters, eventDateObj, selectedDateObj })
) {
return;
}
const league = event.tournament.name;
if (!displayedLeagues.has(league)) {
addLeagueHeader(scoresDiv, league);
displayedLeagues.add(league);
}
renderEvent(scoresDiv, event, filters.longnames);
});
}
function shouldFilterEvent(event, filters) {
const { hideFinished, hideNotStarted, eventDateObj, selectedDateObj } =
filters;
const eventType = event.status.type;
return (
eventDateObj < selectedDateObj ||
(hideFinished && eventType === "finished") ||
(hideNotStarted && eventType === "notstarted")
);
}
function displayNoEventsMessage(scoresDiv, message) {
const noEventsMessage = document.createElement("p");
noEventsMessage.textContent = message;
scoresDiv.appendChild(noEventsMessage);
}
function addLeagueHeader(scoresDiv, league) {
const leagueTitle = document.createElement("h3");
leagueTitle.style.fontWeight = "bold";
leagueTitle.textContent = league;
scoresDiv.appendChild(leagueTitle);
}
// Main function to render an event
function renderEvent(scoresDiv, event, longnames) {
const gameContainer = createGameContainer();
// Create event info and teams containers
const eventInfoContainer = createEventInfoContainer(
event.startTimestamp,
event.status.type
);
const teamsContainer = createTeamsContainer(event, longnames);
// Set up click event to open match URL
gameContainer.onclick = () => {
const sport = sportSelect.value;
const url = `${BASE_WEBSITE_URL}/${sport}/match/${event.slug}/${event.customId}`;
window.open(url, "_blank");
};
gameContainer.style.cursor = "pointer";
// Append child elements to game container
gameContainer.appendChild(eventInfoContainer);
gameContainer.appendChild(teamsContainer);
// Append game container to scores div
scoresDiv.appendChild(gameContainer);
}
// Create a game container
function createGameContainer() {
const gameContainer = document.createElement("div");
gameContainer.style.display = "flex";
gameContainer.style.alignItems = "center";
gameContainer.style.marginBottom = "10px";
return gameContainer;
}
// Create an event info container
function createEventInfoContainer(startTime, eventType) {
const eventInfoContainer = document.createElement("div");
eventInfoContainer.style.display = "flex";
eventInfoContainer.style.flexDirection = "column";
eventInfoContainer.style.alignItems = "center";
eventInfoContainer.style.marginRight = "20px";
eventInfoContainer.style.minWidth = "72px";
// Add event timestamp
const eventTimestamp = document.createElement("span");
eventTimestamp.textContent = formatEventTime(startTime);
eventInfoContainer.appendChild(eventTimestamp);
// Add event type text
const eventTypeText = createEventTypeText(eventType);
eventInfoContainer.appendChild(eventTypeText);
return eventInfoContainer;
}
// Create event type text element
function createEventTypeText(eventType) {
const eventTypeText = document.createElement("span");
eventTypeText.style.color = getEventTypeColor(eventType);
eventTypeText.textContent = getEventTypeText(eventType);
return eventTypeText;
}
// Helper function to get color based on event type
function getEventTypeColor(eventType) {
switch (eventType) {
case "inprogress":
return "orange";
case "finished":
return "green";
case "notstarted":
return "white";
case "postponed":
return "red";
default:
return "white";
}
}
// Helper function to get text based on event type
function getEventTypeText(eventType) {
switch (eventType) {
case "inprogress":
return "In Progress";
case "finished":
return "Finished";
case "notstarted":
return "Not Started";
case "postponed":
return "Postponed";
default:
return "Unknown";
}
}
// Create a container for teams
function createTeamsContainer(event, longnames) {
const teamsContainer = document.createElement("div");
// Create team divs for home and away teams
const homeTeamDiv = createTeamDiv(event.homeTeam, event.homeScore, longnames);
const awayTeamDiv = createTeamDiv(event.awayTeam, event.awayScore, longnames);
// Dim the losing team
dimLosingTeam(event, homeTeamDiv, awayTeamDiv);
// Append team divs to teams container
teamsContainer.appendChild(homeTeamDiv);
teamsContainer.appendChild(awayTeamDiv);
return teamsContainer;
}
// Create a team div
function createTeamDiv(team, score, longnames) {
const teamDiv = document.createElement("div");
teamDiv.style.display = "flex";
teamDiv.style.alignItems = "center";
teamDiv.style.justifyContent = "space-between";
teamDiv.style.width = "100%";
teamDiv.style.marginBottom = "5px";
const teamInfoDiv = createTeamInfoDiv(team, longnames);
const scoreDiv = createScoreDiv(score);
teamDiv.appendChild(teamInfoDiv);
teamDiv.appendChild(scoreDiv);
return teamDiv;
}
// Create a div for team info
function createTeamInfoDiv(team, longnames) {
const teamInfoDiv = document.createElement("div");
teamInfoDiv.style.display = "flex";
teamInfoDiv.style.alignItems = "center";
teamInfoDiv.style.flexGrow = "1";
const teamLogo = createTeamLogo(team);
const teamNameText = createTeamNameText(team, longnames);
teamInfoDiv.appendChild(teamLogo);
teamInfoDiv.appendChild(teamNameText);
return teamInfoDiv;
}
// Create team logo element
function createTeamLogo(team) {
const teamLogo = document.createElement("img");
teamLogo.src = `${BASE_APP_URL}/team/${team.id}/image`;
teamLogo.alt = `${team.name} logo`;
teamLogo.style.width = "24px";
teamLogo.style.height = "24px";
teamLogo.style.marginRight = "10px";
return teamLogo;
}
// Create team name text element
function createTeamNameText(team, longnames) {
const teamName = longnames ? team.name : team.shortName;
const teamNameText = document.createElement("span");
teamNameText.textContent = teamName;
teamNameText.style.width = "150px";
teamNameText.style.whiteSpace = "nowrap";
teamNameText.style.overflow = "hidden";
teamNameText.style.textOverflow = "ellipsis";
teamNameText.style.textAlign = "left";
return teamNameText;
}
// Create score div
function createScoreDiv(score) {
const scoreDiv = document.createElement("div");
scoreDiv.style.textAlign = "right";
scoreDiv.style.minWidth = "40px";
scoreDiv.textContent =
score !== null && score !== undefined ? score.display : "";
return scoreDiv;
}
// Dim the losing team based on the event
function dimLosingTeam(event, homeTeamDiv, awayTeamDiv) {
const homeTeamText = homeTeamDiv.querySelector("span");
const awayTeamText = awayTeamDiv.querySelector("span");
if (event.winnerCode === 1) {
awayTeamText.style.opacity = "0.5";
} else if (event.winnerCode === 2) {
homeTeamText.style.opacity = "0.5";
}
}
// Initialization and Refresh
function initializeApp() {
loadSettings();
const currentDate = getCurrentDate();
dateSelect.value = currentDate;
fetchData(sportSelect.value, currentDate);
setupEventListeners();
setInterval(refreshData, REFRESH_INTERVAL);
}
function refreshData() {
fetchData(sportSelect.value, dateSelect.value);
}