diff options
Diffstat (limited to 'asset-sources/fietsboek.ts')
-rw-r--r-- | asset-sources/fietsboek.ts | 51 |
1 files changed, 48 insertions, 3 deletions
diff --git a/asset-sources/fietsboek.ts b/asset-sources/fietsboek.ts index b885271..ae9e724 100644 --- a/asset-sources/fietsboek.ts +++ b/asset-sources/fietsboek.ts @@ -22,6 +22,19 @@ interface Window { */ type Selector = string; + +/** + * Gets the value of a single cookie. + * + * @param name - Name of the cookie. + * @return The cookie value, or null. + */ +function getCookie(name: string): string | undefined { + return document.cookie.split("; ") + .find((row) => row.startsWith(`${name}=`)) + ?.split("=")[1]; +} + /** * Installs a listener to the given DOM objects. * @@ -400,9 +413,7 @@ addHandler(".button-clear-input", "click", clearInputButtonClicked); * @param event - The triggering event. */ function changeHomeSorting(_event: MouseEvent) { - const currentSorting = document.cookie.split("; ") - .find((row) => row.startsWith("home_sorting=")) - ?.split("=")[1] ?? "asc"; + const currentSorting = getCookie("home_sorting") ?? "asc"; const newSorting = currentSorting == "asc" ? "desc" : "asc"; document.cookie = `home_sorting=${newSorting}; SameSite=Lax`; window.location.reload(); @@ -411,6 +422,40 @@ function changeHomeSorting(_event: MouseEvent) { addHandler("#changeHomeSorting", "click", changeHomeSorting); +/** + * Handler to toggle the favourite status of a track. + * + * This is applied to .favourite-star elements and expects the track ID in + * data-track-id. + * + * @param event - The triggering event. + */ +function toggleTrackFavourite(event: MouseEvent) { + const target = event.target as HTMLElement; + const trackId = target.getAttribute("data-track-id"); + if (trackId === null) { + return; + } + const url = new URL("/me/toggle-favourite", window.location.href); + const formData = new URLSearchParams(); + formData.append("track-id", trackId); + formData.append("csrf_token", getCookie("csrf_token") ?? ""); + fetch(url, { + "method": "POST", + "body": formData, + }).then(response => response.json().then(data => { + const isNowFavourite = data["favourite"]; + if (isNowFavourite) { + target.classList.replace("bi-star", "bi-star-fill"); + } else { + target.classList.replace("bi-star-fill", "bi-star"); + } + })); +} + +addHandler(".favourite-star", "click", toggleTrackFavourite); + + document.addEventListener('DOMContentLoaded', function() { window.fietsboekImageIndex = 0; |