From 74e4032ffc9faad4fec602f283a32d2af8dec47e Mon Sep 17 00:00:00 2001 From: jvoisin Date: Mon, 11 Mar 2024 17:23:20 +0100 Subject: [PATCH] Small refactor of app.js - replace a lot of `let` with `const` - inline some `querySelectorAll` calls - reduce the scope of some variables - use some ternaries where it makes sense - inline one-line functions --- internal/ui/static/js/app.js | 180 +++++++++++++++-------------------- 1 file changed, 76 insertions(+), 104 deletions(-) diff --git a/internal/ui/static/js/app.js b/internal/ui/static/js/app.js index 809c5c22..51a73e2e 100644 --- a/internal/ui/static/js/app.js +++ b/internal/ui/static/js/app.js @@ -1,25 +1,21 @@ // OnClick attaches a listener to the elements that match the selector. function onClick(selector, callback, noPreventDefault) { - let elements = document.querySelectorAll(selector); - elements.forEach((element) => { + document.querySelectorAll(selector).forEach((element) => { element.onclick = (event) => { if (!noPreventDefault) { event.preventDefault(); } - callback(event); }; }); } function onAuxClick(selector, callback, noPreventDefault) { - let elements = document.querySelectorAll(selector); - elements.forEach((element) => { + document.querySelectorAll(selector).forEach((element) => { element.onauxclick = (event) => { if (!noPreventDefault) { event.preventDefault(); } - callback(event); }; }); @@ -28,22 +24,18 @@ function onAuxClick(selector, callback, noPreventDefault) { // make logo element as button on mobile layout function checkMenuToggleModeByLayout() { const logoElement = document.querySelector(".logo"); - const homePageLinkElement = document.querySelector(".logo > a"); if (!logoElement) return; - const logoToggleButtonLabel = logoElement.getAttribute("data-toggle-button-label"); - const navMenuElement = document.getElementById("header-menu"); - const navMenuElementIsExpanded = navMenuElement.classList.contains("js-menu-show"); + const homePageLinkElement = document.querySelector(".logo > a"); if (document.documentElement.clientWidth < 620) { + const navMenuElement = document.getElementById("header-menu"); + const navMenuElementIsExpanded = navMenuElement.classList.contains("js-menu-show"); + const logoToggleButtonLabel = logoElement.getAttribute("data-toggle-button-label"); logoElement.setAttribute("role", "button"); logoElement.setAttribute("tabindex", "0"); logoElement.setAttribute("aria-label", logoToggleButtonLabel); - if (navMenuElementIsExpanded) { - logoElement.setAttribute("aria-expanded", "true"); - } else { - logoElement.setAttribute("aria-expanded", "false"); - } + logoElement.setAttribute("aria-expanded", navMenuElementIsExpanded?"true":"false"); homePageLinkElement.setAttribute("tabindex", "-1"); } else { logoElement.removeAttribute("role"); @@ -55,24 +47,15 @@ function checkMenuToggleModeByLayout() { } function fixVoiceOverDetailsSummaryBug() { - const detailsElements = document.querySelectorAll("details"); - detailsElements.forEach((details) => { + document.querySelectorAll("details").forEach((details) => { const summaryElement = details.querySelector("summary"); summaryElement.setAttribute("role", "button"); - setSummaryAriaExpandedByDetails(details, summaryElement); + summaryElement.setAttribute("aria-expanded", details.open? "true": "false"); details.addEventListener("toggle", () => { - setSummaryAriaExpandedByDetails(details, summaryElement); + summaryElement.setAttribute("aria-expanded", details.open? "true": "false"); }); }); - - function setSummaryAriaExpandedByDetails(details, summary) { - if (details.open) { - summary.setAttribute("aria-expanded", "true"); - } else { - summary.setAttribute("aria-expanded", "false"); - } - } } // Show and hide the main menu on mobile devices. @@ -85,8 +68,8 @@ function toggleMainMenu(event) { event.preventDefault(); } - let menu = document.querySelector(".header nav ul"); - let menuToggleButton = document.querySelector(".logo"); + const menu = document.querySelector(".header nav ul"); + const menuToggleButton = document.querySelector(".logo"); if (menu.classList.contains("js-menu-show")) { menu.classList.remove("js-menu-show"); menuToggleButton.setAttribute("aria-expanded", false); @@ -98,7 +81,7 @@ function toggleMainMenu(event) { // Handle click events for the main menu (
  • and ). function onClickMainMenuListItem(event) { - let element = event.target; + const element = event.target; if (element.tagName === "A") { window.location.href = element.getAttribute("href"); @@ -109,11 +92,9 @@ function onClickMainMenuListItem(event) { // Change the button label when the page is loading. function handleSubmitButtons() { - let elements = document.querySelectorAll("form"); - elements.forEach((element) => { + document.querySelectorAll("form").forEach((element) => { element.onsubmit = () => { - let button = element.querySelector("button"); - + const button = element.querySelector("button"); if (button) { button.textContent = button.dataset.labelLoading; button.disabled = true; @@ -124,7 +105,7 @@ function handleSubmitButtons() { // Show modal dialog with the list of keyboard shortcuts. function showKeyboardShortcuts() { - let template = document.getElementById("keyboard-shortcuts"); + const template = document.getElementById("keyboard-shortcuts"); if (template !== null) { ModalHandler.open(template.content, "dialog-title"); } @@ -132,8 +113,8 @@ function showKeyboardShortcuts() { // Mark as read visible items of the current page. function markPageAsRead() { - let items = DomHelper.getVisibleElements(".items .item"); - let entryIDs = []; + const items = DomHelper.getVisibleElements(".items .item"); + const entryIDs = []; items.forEach((element) => { element.classList.add("item-status-read"); @@ -144,7 +125,7 @@ function markPageAsRead() { updateEntriesStatus(entryIDs, "read", () => { // Make sure the Ajax request reach the server before we reload the page. - let element = document.querySelector(":is(a, button)[data-action=markPageAsRead]"); + const element = document.querySelector(":is(a, button)[data-action=markPageAsRead]"); let showOnlyUnread = false; if (element) { showOnlyUnread = element.dataset.showOnlyUnread || false; @@ -167,8 +148,8 @@ function markPageAsRead() { * @param {boolean} setToRead */ function handleEntryStatus(item, element, setToRead) { - let toasting = !element; - let currentEntry = findEntry(element); + const toasting = !element; + const currentEntry = findEntry(element); if (currentEntry) { if (!setToRead || currentEntry.querySelector(":is(a, button)[data-toggle-status]").dataset.value == "unread") { toggleEntryStatus(currentEntry, toasting); @@ -188,11 +169,11 @@ function handleEntryStatus(item, element, setToRead) { // Change the entry status to the opposite value. function toggleEntryStatus(element, toasting) { - let entryID = parseInt(element.dataset.id, 10); - let link = element.querySelector(":is(a, button)[data-toggle-status]"); + const entryID = parseInt(element.dataset.id, 10); + const link = element.querySelector(":is(a, button)[data-toggle-status]"); - let currentStatus = link.dataset.value; - let newStatus = currentStatus === "read" ? "unread" : "read"; + const currentStatus = link.dataset.value; + const newStatus = currentStatus === "read" ? "unread" : "read"; link.querySelector("span").textContent = link.dataset.labelLoading; updateEntriesStatus([entryID], newStatus, () => { @@ -228,15 +209,14 @@ function markEntryAsRead(element) { element.classList.remove("item-status-unread"); element.classList.add("item-status-read"); - let entryID = parseInt(element.dataset.id, 10); + const entryID = parseInt(element.dataset.id, 10); updateEntriesStatus([entryID], "read"); } } // Send the Ajax request to refresh all feeds in the background function handleRefreshAllFeeds() { - let url = document.body.dataset.refreshAllFeedsUrl; - + const url = document.body.dataset.refreshAllFeedsUrl; if (url) { window.location.href = url; } @@ -244,8 +224,8 @@ function handleRefreshAllFeeds() { // Send the Ajax request to change entries statuses. function updateEntriesStatus(entryIDs, status, callback) { - let url = document.body.dataset.entriesStatusUrl; - let request = new RequestBuilder(url); + const url = document.body.dataset.entriesStatusUrl; + const request = new RequestBuilder(url); request.withBody({ entry_ids: entryIDs, status: status }); request.withCallback((resp) => { resp.json().then(count => { @@ -265,8 +245,8 @@ function updateEntriesStatus(entryIDs, status, callback) { // Handle save entry from list view and entry view. function handleSaveEntry(element) { - let toasting = !element; - let currentEntry = findEntry(element); + const toasting = !element; + const currentEntry = findEntry(element); if (currentEntry) { saveEntry(currentEntry.querySelector(":is(a, button)[data-save-entry]"), toasting); } @@ -274,22 +254,18 @@ function handleSaveEntry(element) { // Send the Ajax request to save an entry. function saveEntry(element, toasting) { - if (!element) { - return; - } - - if (element.dataset.completed) { + if (!element || element.dataset.completed) { return; } element.innerHTML = '' + element.dataset.labelLoading + ''; - let request = new RequestBuilder(element.dataset.saveUrl); + const request = new RequestBuilder(element.dataset.saveUrl); request.withCallback(() => { element.innerHTML = '' + element.dataset.labelDone + ''; element.dataset.completed = true; if (toasting) { - let iconElement = document.querySelector("template#icon-save"); + const iconElement = document.querySelector("template#icon-save"); showToast(element.dataset.toastDone, iconElement); } }); @@ -298,8 +274,8 @@ function saveEntry(element, toasting) { // Handle bookmark from the list view and entry view. function handleBookmark(element) { - let toasting = !element; - let currentEntry = findEntry(element); + const toasting = !element; + const currentEntry = findEntry(element); if (currentEntry) { toggleBookmark(currentEntry, toasting); } @@ -307,21 +283,19 @@ function handleBookmark(element) { // Send the Ajax request and change the icon when bookmarking an entry. function toggleBookmark(parentElement, toasting) { - let element = parentElement.querySelector(":is(a, button)[data-toggle-bookmark]"); + const element = parentElement.querySelector(":is(a, button)[data-toggle-bookmark]"); if (!element) { return; } element.innerHTML = '' + element.dataset.labelLoading + ''; - let request = new RequestBuilder(element.dataset.bookmarkUrl); + const request = new RequestBuilder(element.dataset.bookmarkUrl); request.withCallback(() => { - - let currentStarStatus = element.dataset.value; - let newStarStatus = currentStarStatus === "star" ? "unstar" : "star"; + const currentStarStatus = element.dataset.value; + const newStarStatus = currentStarStatus === "star" ? "unstar" : "star"; let iconElement, label; - if (currentStarStatus === "star") { iconElement = document.querySelector("template#icon-star"); label = element.dataset.labelStar; @@ -348,15 +322,15 @@ function handleFetchOriginalContent() { return; } - let element = document.querySelector(":is(a, button)[data-fetch-content-entry]"); + const element = document.querySelector(":is(a, button)[data-fetch-content-entry]"); if (!element) { return; } - let previousElement = element.cloneNode(true); + const previousElement = element.cloneNode(true); element.innerHTML = '' + element.dataset.labelLoading + ''; - let request = new RequestBuilder(element.dataset.fetchContentUrl); + const request = new RequestBuilder(element.dataset.fetchContentUrl); request.withCallback((response) => { element.textContent = ''; element.appendChild(previousElement); @@ -364,7 +338,7 @@ function handleFetchOriginalContent() { response.json().then((data) => { if (data.hasOwnProperty("content") && data.hasOwnProperty("reading_time")) { document.querySelector(".entry-content").innerHTML = data.content; - let entryReadingtimeElement = document.querySelector(".entry-reading-time"); + const entryReadingtimeElement = document.querySelector(".entry-reading-time"); if (entryReadingtimeElement) { entryReadingtimeElement.innerHTML = data.reading_time; } @@ -375,7 +349,7 @@ function handleFetchOriginalContent() { } function openOriginalLink(openLinkInCurrentTab) { - let entryLink = document.querySelector(".entry h1 a"); + const entryLink = document.querySelector(".entry h1 a"); if (entryLink !== null) { if (openLinkInCurrentTab) { window.location.href = entryLink.getAttribute("href"); @@ -385,11 +359,11 @@ function openOriginalLink(openLinkInCurrentTab) { return; } - let currentItemOriginalLink = document.querySelector(".current-item :is(a, button)[data-original-link]"); + const currentItemOriginalLink = document.querySelector(".current-item :is(a, button)[data-original-link]"); if (currentItemOriginalLink !== null) { DomHelper.openNewTab(currentItemOriginalLink.getAttribute("href")); - let currentItem = document.querySelector(".current-item"); + const currentItem = document.querySelector(".current-item"); // If we are not on the list of starred items, move to the next item if (document.location.href != document.querySelector(':is(a, button)[data-page=starred]').href) { goToListItem(1); @@ -400,7 +374,7 @@ function openOriginalLink(openLinkInCurrentTab) { function openCommentLink(openLinkInCurrentTab) { if (!isListView()) { - let entryLink = document.querySelector(":is(a, button)[data-comments-link]"); + const entryLink = document.querySelector(":is(a, button)[data-comments-link]"); if (entryLink !== null) { if (openLinkInCurrentTab) { window.location.href = entryLink.getAttribute("href"); @@ -410,7 +384,7 @@ function openCommentLink(openLinkInCurrentTab) { return; } } else { - let currentItemCommentsLink = document.querySelector(".current-item :is(a, button)[data-comments-link]"); + const currentItemCommentsLink = document.querySelector(".current-item :is(a, button)[data-comments-link]"); if (currentItemCommentsLink !== null) { DomHelper.openNewTab(currentItemCommentsLink.getAttribute("href")); } @@ -418,18 +392,18 @@ function openCommentLink(openLinkInCurrentTab) { } function openSelectedItem() { - let currentItemLink = document.querySelector(".current-item .item-title a"); + const currentItemLink = document.querySelector(".current-item .item-title a"); if (currentItemLink !== null) { window.location.href = currentItemLink.getAttribute("href"); } } function unsubscribeFromFeed() { - let unsubscribeLinks = document.querySelectorAll("[data-action=remove-feed]"); + const unsubscribeLinks = document.querySelectorAll("[data-action=remove-feed]"); if (unsubscribeLinks.length === 1) { - let unsubscribeLink = unsubscribeLinks[0]; + const unsubscribeLink = unsubscribeLinks[0]; - let request = new RequestBuilder(unsubscribeLink.dataset.url); + const request = new RequestBuilder(unsubscribeLink.dataset.url); request.withCallback(() => { if (unsubscribeLink.dataset.redirectUrl) { window.location.href = unsubscribeLink.dataset.redirectUrl; @@ -446,7 +420,7 @@ function unsubscribeFromFeed() { * @param {boolean} fallbackSelf Refresh actual page if the page is not found. */ function goToPage(page, fallbackSelf) { - let element = document.querySelector(":is(a, button)[data-page=" + page + "]"); + const element = document.querySelector(":is(a, button)[data-page=" + page + "]"); if (element) { document.location.href = element.href; @@ -481,12 +455,12 @@ function goToFeedOrFeeds() { function goToFeed() { if (isEntry()) { - let feedAnchor = document.querySelector("span.entry-website a"); + const feedAnchor = document.querySelector("span.entry-website a"); if (feedAnchor !== null) { window.location.href = feedAnchor.href; } } else { - let currentItemFeed = document.querySelector(".current-item :is(a, button)[data-feed-link]"); + const currentItemFeed = document.querySelector(".current-item :is(a, button)[data-feed-link]"); if (currentItemFeed !== null) { window.location.href = currentItemFeed.getAttribute("href"); } @@ -497,7 +471,7 @@ function goToFeed() { * @param {number} offset How many items to jump for focus. */ function goToListItem(offset) { - let items = DomHelper.getVisibleElements(".items .item"); + const items = DomHelper.getVisibleElements(".items .item"); if (items.length === 0) { return; } @@ -512,7 +486,8 @@ function goToListItem(offset) { if (items[i].classList.contains("current-item")) { items[i].classList.remove("current-item"); - let item = items[(i + offset + items.length) % items.length]; + const index = (i + offset + items.length) % items.length; + const item = items[index]; item.classList.add("current-item"); DomHelper.scrollPageTo(item); @@ -524,7 +499,7 @@ function goToListItem(offset) { } function scrollToCurrentItem() { - let currentItem = document.querySelector(".current-item"); + const currentItem = document.querySelector(".current-item"); if (currentItem !== null) { DomHelper.scrollPageTo(currentItem, true); } @@ -543,15 +518,14 @@ function incrementUnreadCounter(n) { } function updateUnreadCounterValue(callback) { - let counterElements = document.querySelectorAll("span.unread-counter"); - counterElements.forEach((element) => { - let oldValue = parseInt(element.textContent, 10); + document.querySelectorAll("span.unread-counter").forEach((element) => { + const oldValue = parseInt(element.textContent, 10); element.innerHTML = callback(oldValue); }); if (window.location.href.endsWith('/unread')) { - let oldValue = parseInt(document.title.split('(')[1], 10); - let newValue = callback(oldValue); + const oldValue = parseInt(document.title.split('(')[1], 10); + const newValue = callback(oldValue); document.title = document.title.replace( /(.*?)\(\d+\)(.*?)/, @@ -574,12 +548,10 @@ function findEntry(element) { if (isListView()) { if (element) { return element.closest(".item"); - } else { - return document.querySelector(".current-item"); } - } else { - return document.querySelector(".entry"); + return document.querySelector(".current-item"); } + return document.querySelector(".entry"); } function handleConfirmationMessage(linkElement, callback) { @@ -589,11 +561,11 @@ function handleConfirmationMessage(linkElement, callback) { linkElement.style.display = "none"; - let containerElement = linkElement.parentNode; - let questionElement = document.createElement("span"); + const containerElement = linkElement.parentNode; + const questionElement = document.createElement("span"); function createLoadingElement() { - let loadingElement = document.createElement("span"); + const loadingElement = document.createElement("span"); loadingElement.className = "loading"; loadingElement.appendChild(document.createTextNode(linkElement.dataset.labelLoading)); @@ -601,7 +573,7 @@ function handleConfirmationMessage(linkElement, callback) { containerElement.appendChild(loadingElement); } - let yesElement = document.createElement("button"); + const yesElement = document.createElement("button"); yesElement.appendChild(document.createTextNode(linkElement.dataset.labelYes)); yesElement.onclick = (event) => { event.preventDefault(); @@ -611,7 +583,7 @@ function handleConfirmationMessage(linkElement, callback) { callback(linkElement.dataset.url, linkElement.dataset.redirectUrl); }; - let noElement = document.createElement("button"); + const noElement = document.createElement("button"); noElement.appendChild(document.createTextNode(linkElement.dataset.labelNo)); noElement.onclick = (event) => { event.preventDefault(); @@ -674,7 +646,7 @@ function handlePlayerProgressionSave(playerElement) { currentPositionInSeconds <= (lastKnownPositionInSeconds - recordInterval) ) { playerElement.dataset.lastPosition = currentPositionInSeconds.toString(); - let request = new RequestBuilder(playerElement.dataset.saveUrl); + const request = new RequestBuilder(playerElement.dataset.saveUrl); request.withBody({ progression: currentPositionInSeconds }); request.execute(); } @@ -684,13 +656,13 @@ function handlePlayerProgressionSave(playerElement) { * handle new share entires and already shared entries */ function handleShare() { - let link = document.querySelector(':is(a, button)[data-share-status]'); - let title = document.querySelector("body > main > section > header > h1 > a"); + const link = document.querySelector(':is(a, button)[data-share-status]'); + const title = document.querySelector("body > main > section > header > h1 > a"); if (link.dataset.shareStatus === "shared") { checkShareAPI(title, link.href); } if (link.dataset.shareStatus === "share") { - let request = new RequestBuilder(link.href); + const request = new RequestBuilder(link.href); request.withCallback((r) => { checkShareAPI(title, r.url); }); @@ -721,7 +693,7 @@ function checkShareAPI(title, url) { } function getCsrfToken() { - let element = document.querySelector("body[data-csrf-token]"); + const element = document.querySelector("body[data-csrf-token]"); if (element !== null) { return element.dataset.csrfToken; }