app.js 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  1. // Sentinel values for specific list navigation.
  2. const TOP = 9999;
  3. const BOTTOM = -9999;
  4. // Simple Polyfill for browsers that don't support Trusted Types
  5. // See https://caniuse.com/?search=trusted%20types
  6. if (!window.trustedTypes || !trustedTypes.createPolicy) {
  7. window.trustedTypes = {
  8. createPolicy: (name, policy) => ({
  9. createScriptURL: src => src,
  10. createHTML: html => html,
  11. })
  12. };
  13. }
  14. /**
  15. * Send a POST request to the specified URL with the given body.
  16. *
  17. * @param {string} url - The URL to send the request to.
  18. * @param {Object} [body] - The body of the request (optional).
  19. * @returns {Promise<Response>} The response from the fetch request.
  20. */
  21. function sendPOSTRequest(url, body = null) {
  22. const options = {
  23. method: "POST",
  24. headers: {
  25. "X-Csrf-Token": document.body.dataset.csrfToken || ""
  26. }
  27. };
  28. if (body !== null) {
  29. options.headers["Content-Type"] = "application/json";
  30. options.body = JSON.stringify(body);
  31. }
  32. return fetch(url, options);
  33. }
  34. /**
  35. * Open a new tab with the given URL.
  36. *
  37. * @param {string} url
  38. */
  39. function openNewTab(url) {
  40. const win = window.open("");
  41. win.opener = null;
  42. win.location = url;
  43. win.focus();
  44. }
  45. /**
  46. * Scroll the page to the given element.
  47. *
  48. * @param {Element} element
  49. * @param {boolean} evenIfOnScreen
  50. */
  51. function scrollPageTo(element, evenIfOnScreen) {
  52. const windowScrollPosition = window.scrollY;
  53. const windowHeight = document.documentElement.clientHeight;
  54. const viewportPosition = windowScrollPosition + windowHeight;
  55. const itemBottomPosition = element.offsetTop + element.offsetHeight;
  56. if (evenIfOnScreen || viewportPosition - itemBottomPosition < 0 || viewportPosition - element.offsetTop > windowHeight) {
  57. window.scrollTo(0, element.offsetTop - 10);
  58. }
  59. }
  60. /**
  61. * Attach a click event listener to elements matching the selector.
  62. *
  63. * @param {string} selector
  64. * @param {function} callback
  65. * @param {boolean} noPreventDefault
  66. */
  67. function onClick(selector, callback, noPreventDefault) {
  68. document.querySelectorAll(selector).forEach((element) => {
  69. element.onclick = (event) => {
  70. if (!noPreventDefault) {
  71. event.preventDefault();
  72. }
  73. callback(event);
  74. };
  75. });
  76. }
  77. /**
  78. * Attach an auxiliary click event listener to elements matching the selector.
  79. *
  80. * @param {string} selector
  81. * @param {function} callback
  82. * @param {boolean} noPreventDefault
  83. */
  84. function onAuxClick(selector, callback, noPreventDefault) {
  85. document.querySelectorAll(selector).forEach((element) => {
  86. element.onauxclick = (event) => {
  87. if (!noPreventDefault) {
  88. event.preventDefault();
  89. }
  90. callback(event);
  91. };
  92. });
  93. }
  94. /**
  95. * Filter visible elements based on the selector.
  96. *
  97. * @param {string} selector
  98. * @returns {Array<Element>}
  99. */
  100. function getVisibleElements(selector) {
  101. const elements = document.querySelectorAll(selector);
  102. return [...elements].filter((element) => element.offsetParent !== null);
  103. }
  104. /**
  105. * Get all visible entries on the current page.
  106. *
  107. * @return {Array<Element>}
  108. */
  109. function getVisibleEntries() {
  110. return getVisibleElements(".items .item");
  111. }
  112. /**
  113. * Check if the current view is a list view.
  114. *
  115. * @returns {boolean}
  116. */
  117. function isListView() {
  118. return document.querySelector(".items") !== null;
  119. }
  120. /**
  121. * Check if the current view is an entry view.
  122. *
  123. * @return {boolean}
  124. */
  125. function isEntryView() {
  126. return document.querySelector("section.entry") !== null;
  127. }
  128. /**
  129. * Find the entry element for the given element.
  130. *
  131. * @returns {Element|null}
  132. */
  133. function findEntry(element) {
  134. if (isListView()) {
  135. if (element) {
  136. return element.closest(".item");
  137. }
  138. return document.querySelector(".current-item");
  139. }
  140. return document.querySelector(".entry");
  141. }
  142. /**
  143. * Create an icon label element with the given text.
  144. *
  145. * @param {string} labelText - The text to display in the icon label.
  146. * @returns {Element} The created icon label element.
  147. */
  148. function createIconLabelElement(labelText) {
  149. const labelElement = document.createElement("span");
  150. labelElement.classList.add("icon-label");
  151. labelElement.textContent = labelText;
  152. return labelElement;
  153. }
  154. /**
  155. * Set the icon and label element in the parent element.
  156. *
  157. * @param {Element} parentElement - The parent element to insert the icon and label into.
  158. * @param {string} iconName - The name of the icon to display.
  159. * @param {string} labelText - The text to display in the label.
  160. */
  161. function setIconAndLabelElement(parentElement, iconName, labelText) {
  162. const iconElement = document.querySelector(`template#icon-${iconName}`);
  163. if (iconElement) {
  164. const iconClone = iconElement.content.cloneNode(true);
  165. parentElement.textContent = ""; // Clear existing content
  166. parentElement.appendChild(iconClone);
  167. }
  168. if (labelText) {
  169. const labelElement = createIconLabelElement(labelText);
  170. parentElement.appendChild(labelElement);
  171. }
  172. }
  173. /**
  174. * Set the button to a loading state and return a clone of the original button element.
  175. *
  176. * @param {Element} buttonElement - The button element to set to loading state.
  177. * @return {Element} The original button element cloned before modification.
  178. */
  179. function setButtonToLoadingState(buttonElement) {
  180. const originalButtonElement = buttonElement.cloneNode(true);
  181. buttonElement.textContent = "";
  182. buttonElement.appendChild(createIconLabelElement(buttonElement.dataset.labelLoading));
  183. return originalButtonElement;
  184. }
  185. /**
  186. * Restore the button to its original state.
  187. *
  188. * @param {Element} buttonElement The button element to restore.
  189. * @param {Element} originalButtonElement The original button element to restore from.
  190. * @returns {void}
  191. */
  192. function restoreButtonState(buttonElement, originalButtonElement) {
  193. buttonElement.textContent = "";
  194. buttonElement.appendChild(originalButtonElement);
  195. }
  196. /**
  197. * Set the button to a saved state.
  198. *
  199. * @param {Element} buttonElement The button element to set to saved state.
  200. */
  201. function setButtonToSavedState(buttonElement) {
  202. buttonElement.dataset.completed = "true";
  203. setIconAndLabelElement(buttonElement, "save", buttonElement.dataset.labelDone);
  204. }
  205. /**
  206. * Set the star button state.
  207. *
  208. * @param {Element} buttonElement - The button element to update.
  209. * @param {string} newState - The new state to set ("star" or "unstar").
  210. */
  211. function setStarredButtonState(buttonElement, newState) {
  212. buttonElement.dataset.value = newState;
  213. const iconType = newState === "star" ? "unstar" : "star";
  214. setIconAndLabelElement(buttonElement, iconType, buttonElement.dataset[newState === "star" ? "labelUnstar" : "labelStar"]);
  215. }
  216. /**
  217. * Set the read status button state.
  218. *
  219. * @param {Element} buttonElement - The button element to update.
  220. * @param {string} newState - The new state to set ("read" or "unread").
  221. */
  222. function setReadStatusButtonState(buttonElement, newState) {
  223. buttonElement.dataset.value = newState;
  224. const iconType = newState === "read" ? "unread" : "read";
  225. setIconAndLabelElement(buttonElement, iconType, buttonElement.dataset[newState === "read" ? "labelUnread" : "labelRead"]);
  226. }
  227. /**
  228. * Show a toast notification.
  229. *
  230. * @param {string} iconType - The type of icon to display.
  231. * @param {string} notificationMessage - The message to display in the toast.
  232. * @returns {void}
  233. */
  234. function showToastNotification(iconType, notificationMessage) {
  235. const toastMsgElement = document.createElement("span");
  236. toastMsgElement.id = "toast-msg";
  237. setIconAndLabelElement(toastMsgElement, iconType, notificationMessage);
  238. const toastElementWrapper = document.createElement("div");
  239. toastElementWrapper.id = "toast-wrapper";
  240. toastElementWrapper.setAttribute("role", "alert");
  241. toastElementWrapper.setAttribute("aria-live", "assertive");
  242. toastElementWrapper.setAttribute("aria-atomic", "true");
  243. toastElementWrapper.appendChild(toastMsgElement);
  244. toastElementWrapper.addEventListener("animationend", () => {
  245. toastElementWrapper.remove();
  246. });
  247. document.body.appendChild(toastElementWrapper);
  248. setTimeout(() => toastElementWrapper.classList.add("toast-animate"), 100);
  249. }
  250. /**
  251. * Navigate to a specific page.
  252. *
  253. * @param {string} page - The page to navigate to.
  254. * @param {boolean} reloadOnFail - If true, reload the current page if the target page is not found.
  255. */
  256. function goToPage(page, reloadOnFail = false) {
  257. const element = document.querySelector(":is(a, button)[data-page=" + page + "]");
  258. if (element) {
  259. document.location.href = element.href;
  260. } else if (reloadOnFail) {
  261. window.location.reload();
  262. }
  263. }
  264. /**
  265. * Navigate to the previous page.
  266. *
  267. * If the offset is a KeyboardEvent, it will navigate to the previous item in the list.
  268. * If the offset is a number, it will jump that many items in the list.
  269. * If the offset is TOP, it will jump to the first item in the list.
  270. * If the offset is BOTTOM, it will jump to the last item in the list.
  271. * If the current view is an entry view, it will redirect to the previous page.
  272. *
  273. * @param {number|KeyboardEvent} offset - How many items to jump for focus.
  274. */
  275. function goToPreviousPage(offset) {
  276. if (offset instanceof KeyboardEvent) offset = -1;
  277. if (isListView()) {
  278. goToListItem(offset);
  279. } else {
  280. goToPage("previous");
  281. }
  282. }
  283. /**
  284. * Navigate to the next page.
  285. *
  286. * If the offset is a KeyboardEvent, it will navigate to the next item in the list.
  287. * If the offset is a number, it will jump that many items in the list.
  288. * If the offset is TOP, it will jump to the first item in the list.
  289. * If the offset is BOTTOM, it will jump to the last item in the list.
  290. * If the current view is an entry view, it will redirect to the next page.
  291. *
  292. * @param {number|KeyboardEvent} offset - How many items to jump for focus.
  293. */
  294. function goToNextPage(offset) {
  295. if (offset instanceof KeyboardEvent) offset = 1;
  296. if (isListView()) {
  297. goToListItem(offset);
  298. } else {
  299. goToPage("next");
  300. }
  301. }
  302. /**
  303. * Navigate to the individual feed or feeds page.
  304. *
  305. * If the current view is an entry view, it will redirect to the feed link of the entry.
  306. * If the current view is a list view, it will redirect to the feeds page.
  307. */
  308. function goToFeedOrFeedsPage() {
  309. if (isEntryView()) {
  310. goToFeedPage();
  311. } else {
  312. goToPage("feeds");
  313. }
  314. }
  315. /**
  316. * Navigate to the feed page of the current entry.
  317. *
  318. * If the current view is an entry view, it will redirect to the feed link of the entry.
  319. * If the current view is a list view, it will redirect to the feed link of the currently selected item.
  320. * If no feed link is available, it will do nothing.
  321. */
  322. function goToFeedPage() {
  323. if (isEntryView()) {
  324. const feedAnchor = document.querySelector("span.entry-website a");
  325. if (feedAnchor !== null) {
  326. window.location.href = feedAnchor.href;
  327. }
  328. } else {
  329. const currentItemFeed = document.querySelector(".current-item :is(a, button)[data-feed-link]");
  330. if (currentItemFeed !== null) {
  331. window.location.href = currentItemFeed.getAttribute("href");
  332. }
  333. }
  334. }
  335. /**
  336. * Navigate to the add subscription page.
  337. *
  338. * @returns {void}
  339. */
  340. function goToAddSubscriptionPage() {
  341. window.location.href = document.body.dataset.addSubscriptionUrl;
  342. }
  343. /**
  344. * Navigate to the next or previous item in the list.
  345. *
  346. * If the offset is TOP, it will jump to the first item in the list.
  347. * If the offset is BOTTOM, it will jump to the last item in the list.
  348. * If the offset is a number, it will jump that many items in the list.
  349. * If the current view is an entry view, it will redirect to the next or previous page.
  350. *
  351. * @param {number} offset - How many items to jump for focus.
  352. * @return {void}
  353. */
  354. function goToListItem(offset) {
  355. const items = getVisibleEntries();
  356. if (items.length === 0) {
  357. return;
  358. }
  359. const currentItem = document.querySelector(".current-item");
  360. // If no current item exists, select the first item
  361. if (!currentItem) {
  362. items[0].classList.add("current-item");
  363. items[0].focus();
  364. scrollPageTo(items[0]);
  365. return;
  366. }
  367. // Find the index of the current item
  368. const currentIndex = items.indexOf(currentItem);
  369. if (currentIndex === -1) {
  370. // Current item not found in visible items, select first item
  371. currentItem.classList.remove("current-item");
  372. items[0].classList.add("current-item");
  373. items[0].focus();
  374. scrollPageTo(items[0]);
  375. return;
  376. }
  377. // Calculate the new item index
  378. let newIndex;
  379. if (offset === TOP) {
  380. newIndex = 0;
  381. } else if (offset === BOTTOM) {
  382. newIndex = items.length - 1;
  383. } else {
  384. newIndex = (currentIndex + offset + items.length) % items.length;
  385. }
  386. // Update selection if moving to a different item
  387. if (newIndex !== currentIndex) {
  388. const newItem = items[newIndex];
  389. currentItem.classList.remove("current-item");
  390. newItem.classList.add("current-item");
  391. newItem.focus();
  392. scrollPageTo(newItem);
  393. }
  394. }
  395. /**
  396. * Handle the share action for the entry.
  397. *
  398. * If the share status is "shared", it will trigger the Web Share API.
  399. * If the share status is "share", it will send an Ajax request to fetch the share URL and then trigger the Web Share API.
  400. * If the Web Share API is not supported, it will redirect to the entry URL.
  401. */
  402. async function handleEntryShareAction() {
  403. const link = document.querySelector(':is(a, button)[data-share-status]');
  404. if (link.dataset.shareStatus === "shared") {
  405. const title = document.querySelector(".entry-header > h1 > a");
  406. const url = link.href;
  407. if (!navigator.canShare) {
  408. console.error("Your browser doesn't support the Web Share API.");
  409. window.location = url;
  410. return;
  411. }
  412. try {
  413. await navigator.share({
  414. title: title ? title.textContent : url,
  415. url: url
  416. });
  417. } catch (err) {
  418. console.error(err);
  419. }
  420. }
  421. }
  422. /**
  423. * Toggle the ARIA attributes on the main menu based on the viewport width.
  424. */
  425. function toggleAriaAttributesOnMainMenu() {
  426. const logoElement = document.querySelector(".logo");
  427. const homePageLinkElement = document.querySelector(".logo > a");
  428. if (!logoElement || !homePageLinkElement) return;
  429. const isMobile = document.documentElement.clientWidth < 650;
  430. if (isMobile) {
  431. const navMenuElement = document.getElementById("header-menu");
  432. const isExpanded = navMenuElement?.classList.contains("js-menu-show") ?? false;
  433. const toggleButtonLabel = logoElement.getAttribute("data-toggle-button-label");
  434. // Set mobile menu button attributes
  435. Object.assign(logoElement, {
  436. role: "button",
  437. tabIndex: 0,
  438. ariaLabel: toggleButtonLabel,
  439. ariaExpanded: isExpanded.toString()
  440. });
  441. homePageLinkElement.tabIndex = -1;
  442. } else {
  443. // Remove mobile menu button attributes
  444. ["role", "tabindex", "aria-expanded", "aria-label"].forEach(attr =>
  445. logoElement.removeAttribute(attr)
  446. );
  447. homePageLinkElement.removeAttribute("tabindex");
  448. }
  449. }
  450. /**
  451. * Toggle the main menu dropdown.
  452. *
  453. * @param {Event} event - The event object.
  454. */
  455. function toggleMainMenuDropdown(event) {
  456. // Only handle Enter, Space, or click events
  457. if (event.type === "keydown" && !["Enter", " "].includes(event.key)) {
  458. return;
  459. }
  460. // Prevent default only if element has role attribute (mobile menu button)
  461. if (event.currentTarget.getAttribute("role")) {
  462. event.preventDefault();
  463. }
  464. const navigationMenu = document.querySelector(".header nav ul");
  465. const menuToggleButton = document.querySelector(".logo");
  466. if (!navigationMenu || !menuToggleButton) {
  467. return;
  468. }
  469. const isShowing = navigationMenu.classList.toggle("js-menu-show");
  470. menuToggleButton.setAttribute("aria-expanded", isShowing.toString());
  471. }
  472. /**
  473. * Initialize the main menu handlers.
  474. */
  475. function initializeMainMenuHandlers() {
  476. toggleAriaAttributesOnMainMenu();
  477. window.addEventListener("resize", toggleAriaAttributesOnMainMenu, { passive: true });
  478. const logoElement = document.querySelector(".logo");
  479. if (logoElement) {
  480. logoElement.addEventListener("click", toggleMainMenuDropdown);
  481. logoElement.addEventListener("keydown", toggleMainMenuDropdown);
  482. }
  483. onClick(".header nav li", (event) => {
  484. const linkElement = event.target.closest("a") || event.target.querySelector("a");
  485. if (linkElement) {
  486. window.location.href = linkElement.getAttribute("href");
  487. }
  488. });
  489. }
  490. /**
  491. * This function changes the button label to the loading state and disables the button.
  492. *
  493. * @returns {void}
  494. */
  495. function initializeFormHandlers() {
  496. document.querySelectorAll("form").forEach((element) => {
  497. element.onsubmit = () => {
  498. const buttons = element.querySelectorAll("button[type=submit]");
  499. buttons.forEach((button) => {
  500. if (button.dataset.labelLoading) {
  501. button.textContent = button.dataset.labelLoading;
  502. }
  503. button.disabled = true;
  504. });
  505. };
  506. });
  507. }
  508. /**
  509. * Show the keyboard shortcuts modal.
  510. */
  511. function showKeyboardShortcutsAction() {
  512. const template = document.getElementById("keyboard-shortcuts");
  513. KeyboardModalHandler.open(template.content, "dialog-title");
  514. }
  515. /**
  516. * Mark all visible entries on the current page as read.
  517. */
  518. function markPageAsReadAction() {
  519. const items = getVisibleEntries();
  520. if (items.length === 0) return;
  521. const entryIDs = items.map((element) => {
  522. element.classList.add("item-status-read");
  523. return parseInt(element.dataset.id, 10);
  524. });
  525. updateEntriesStatus(entryIDs, "read", () => {
  526. const element = document.querySelector(":is(a, button)[data-action=markPageAsRead]");
  527. const showOnlyUnread = element?.dataset.showOnlyUnread || false;
  528. if (showOnlyUnread) {
  529. window.location.reload();
  530. } else {
  531. goToPage("next", true);
  532. }
  533. });
  534. }
  535. /**
  536. * Handle entry status changes from the list view and entry view.
  537. * Focus the next or the previous entry if it exists.
  538. *
  539. * @param {string} navigationDirection Navigation direction: "previous" or "next".
  540. * @param {Element} element Element that triggered the action.
  541. * @param {boolean} setToRead If true, set the entry to read instead of toggling the status.
  542. * @returns {void}
  543. */
  544. function handleEntryStatus(navigationDirection, element, setToRead) {
  545. const currentEntry = findEntry(element);
  546. if (currentEntry) {
  547. if (!setToRead || currentEntry.querySelector(":is(a, button)[data-toggle-status]").dataset.value === "unread") {
  548. toggleEntryStatus(currentEntry, isEntryView());
  549. }
  550. if (isListView() && currentEntry.classList.contains('current-item')) {
  551. switch (navigationDirection) {
  552. case "previous":
  553. goToListItem(-1);
  554. break;
  555. case "next":
  556. goToListItem(1);
  557. break;
  558. }
  559. }
  560. }
  561. }
  562. /**
  563. * Toggle the entry status between "read" and "unread".
  564. *
  565. * @param {Element} element The entry element to toggle the status for.
  566. * @param {boolean} toasting If true, show a toast notification after toggling the status.
  567. */
  568. function toggleEntryStatus(element, toasting) {
  569. const entryID = parseInt(element.dataset.id, 10);
  570. const buttonElement = element.querySelector(":is(a, button)[data-toggle-status]");
  571. if (!buttonElement) return;
  572. const currentStatus = buttonElement.dataset.value;
  573. const newStatus = currentStatus === "read" ? "unread" : "read";
  574. setButtonToLoadingState(buttonElement);
  575. updateEntriesStatus([entryID], newStatus, () => {
  576. setReadStatusButtonState(buttonElement, newStatus);
  577. if (toasting) {
  578. showToastNotification(newStatus, currentStatus === "read" ? buttonElement.dataset.toastUnread : buttonElement.dataset.toastRead);
  579. }
  580. if (element.classList.contains("item-status-" + currentStatus)) {
  581. element.classList.remove("item-status-" + currentStatus);
  582. element.classList.add("item-status-" + newStatus);
  583. }
  584. if (isListView() && getVisibleEntries().length === 0) {
  585. window.location.reload();
  586. }
  587. });
  588. }
  589. /**
  590. * Handle the refresh of all feeds.
  591. *
  592. * This function redirects the user to the URL specified in the data-refresh-all-feeds-url attribute of the body element.
  593. */
  594. function handleRefreshAllFeedsAction() {
  595. const refreshAllFeedsUrl = document.body.dataset.refreshAllFeedsUrl;
  596. if (refreshAllFeedsUrl) {
  597. window.location.href = refreshAllFeedsUrl;
  598. }
  599. }
  600. /**
  601. * Update the status of multiple entries.
  602. *
  603. * @param {Array<number>} entryIDs - The IDs of the entries to update.
  604. * @param {string} status - The new status to set for the entries (e.g., "read", "unread").
  605. */
  606. function updateEntriesStatus(entryIDs, status, callback) {
  607. const url = document.body.dataset.entriesStatusUrl;
  608. sendPOSTRequest(url, { entry_ids: entryIDs, status: status }).then((resp) => {
  609. resp.json().then(count => {
  610. if (callback) {
  611. callback(resp);
  612. }
  613. updateUnreadCounterValue(status === "read" ? -count : count);
  614. });
  615. });
  616. }
  617. /**
  618. * Handle save entry from list view and entry view.
  619. *
  620. * @param {Element|null} element - The element that triggered the save action (optional).
  621. */
  622. function handleSaveEntryAction(element = null) {
  623. const currentEntry = findEntry(element);
  624. if (!currentEntry) return;
  625. const buttonElement = currentEntry.querySelector(":is(a, button)[data-save-entry]");
  626. if (!buttonElement || buttonElement.dataset.completed) return;
  627. setButtonToLoadingState(buttonElement);
  628. sendPOSTRequest(buttonElement.dataset.saveUrl).then(() => {
  629. setButtonToSavedState(buttonElement);
  630. if (isEntryView()) {
  631. showToastNotification("save", buttonElement.dataset.toastDone);
  632. }
  633. });
  634. }
  635. /**
  636. * Handle starring an entry.
  637. *
  638. * @param {Element} element - The element that triggered the star action.
  639. */
  640. function handleStarAction(element) {
  641. const currentEntry = findEntry(element);
  642. if (!currentEntry) return;
  643. const buttonElement = currentEntry.querySelector(":is(a, button)[data-toggle-starred]");
  644. if (!buttonElement) return;
  645. setButtonToLoadingState(buttonElement);
  646. sendPOSTRequest(buttonElement.dataset.starUrl).then(() => {
  647. const currentState = buttonElement.dataset.value;
  648. const isStarred = currentState === "star";
  649. const newStarStatus = isStarred ? "unstar" : "star";
  650. setStarredButtonState(buttonElement, newStarStatus);
  651. if (isEntryView()) {
  652. showToastNotification(currentState, buttonElement.dataset[isStarred ? "toastUnstar" : "toastStar"]);
  653. }
  654. });
  655. }
  656. /**
  657. * Handle fetching the original content of an entry.
  658. *
  659. * @returns {void}
  660. */
  661. function handleFetchOriginalContentAction() {
  662. if (isListView()) return;
  663. const buttonElement = document.querySelector(":is(a, button)[data-fetch-content-entry]");
  664. if (!buttonElement) return;
  665. const originalButtonElement = setButtonToLoadingState(buttonElement);
  666. sendPOSTRequest(buttonElement.dataset.fetchContentUrl).then((response) => {
  667. restoreButtonState(buttonElement, originalButtonElement);
  668. response.json().then((data) => {
  669. if (data.content && data.reading_time) {
  670. const ttpolicy = trustedTypes.createPolicy('html', {createHTML: html => html});
  671. document.querySelector(".entry-content").innerHTML = ttpolicy.createHTML(data.content);
  672. const entryReadingtimeElement = document.querySelector(".entry-reading-time");
  673. if (entryReadingtimeElement) {
  674. entryReadingtimeElement.textContent = data.reading_time;
  675. }
  676. }
  677. });
  678. });
  679. }
  680. /**
  681. * Open the original link of an entry.
  682. *
  683. * @param {boolean} openLinkInCurrentTab - Whether to open the link in the current tab.
  684. * @returns {void}
  685. */
  686. function openOriginalLinkAction(openLinkInCurrentTab) {
  687. if (isEntryView()) {
  688. openOriginalLinkFromEntryView(openLinkInCurrentTab);
  689. } else if (isListView()) {
  690. openOriginalLinkFromListView();
  691. }
  692. }
  693. /**
  694. * Open the original link from entry view.
  695. *
  696. * @param {boolean} openLinkInCurrentTab - Whether to open the link in the current tab.
  697. * @returns {void}
  698. */
  699. function openOriginalLinkFromEntryView(openLinkInCurrentTab) {
  700. const entryLink = document.querySelector(".entry h1 a");
  701. if (!entryLink) return;
  702. const url = entryLink.getAttribute("href");
  703. if (openLinkInCurrentTab) {
  704. window.location.href = url;
  705. } else {
  706. openNewTab(url);
  707. }
  708. }
  709. /**
  710. * Open the original link from list view.
  711. *
  712. * @returns {void}
  713. */
  714. function openOriginalLinkFromListView() {
  715. const currentItem = document.querySelector(".current-item");
  716. const originalLink = currentItem?.querySelector(":is(a, button)[data-original-link]");
  717. if (!currentItem || !originalLink) return;
  718. // Open the link
  719. openNewTab(originalLink.getAttribute("href"));
  720. // Don't navigate or mark as read on starred page
  721. const isStarredPage = document.location.href === document.querySelector(':is(a, button)[data-page=starred]').href;
  722. if (isStarredPage) return;
  723. // Navigate to next item
  724. goToListItem(1);
  725. // Mark as read if currently unread
  726. if (currentItem.classList.contains("item-status-unread")) {
  727. currentItem.classList.remove("item-status-unread");
  728. currentItem.classList.add("item-status-read");
  729. const entryID = parseInt(currentItem.dataset.id, 10);
  730. updateEntriesStatus([entryID], "read");
  731. }
  732. }
  733. /**
  734. * Open the comments link of an entry.
  735. *
  736. * @param {boolean} openLinkInCurrentTab - Whether to open the link in the current tab.
  737. * @returns {void}
  738. */
  739. function openCommentLinkAction(openLinkInCurrentTab) {
  740. const entryLink = document.querySelector(isListView() ? ".current-item :is(a, button)[data-comments-link]" : ":is(a, button)[data-comments-link]");
  741. if (entryLink) {
  742. if (openLinkInCurrentTab) {
  743. window.location.href = entryLink.getAttribute("href");
  744. } else {
  745. openNewTab(entryLink.getAttribute("href"));
  746. }
  747. }
  748. }
  749. /**
  750. * Open the selected item in the current view.
  751. *
  752. * If the current view is a list view, it will navigate to the link of the currently selected item.
  753. * If the current view is an entry view, it will navigate to the link of the entry.
  754. */
  755. function openSelectedItemAction() {
  756. const currentItemLink = document.querySelector(".current-item .item-title a");
  757. if (currentItemLink) {
  758. window.location.href = currentItemLink.getAttribute("href");
  759. }
  760. }
  761. /**
  762. * Unsubscribe from the feed of the currently selected item.
  763. */
  764. function handleRemoveFeedAction() {
  765. const unsubscribeLink = document.querySelector("[data-action=remove-feed]");
  766. if (unsubscribeLink) {
  767. sendPOSTRequest(unsubscribeLink.dataset.url).then(() => {
  768. window.location.href = unsubscribeLink.dataset.redirectUrl || window.location.href;
  769. });
  770. }
  771. }
  772. /**
  773. * Scroll the page to the currently selected item.
  774. */
  775. function scrollToCurrentItemAction() {
  776. const currentItem = document.querySelector(".current-item");
  777. if (currentItem) {
  778. scrollPageTo(currentItem, true);
  779. }
  780. }
  781. /**
  782. * Update the unread counter value.
  783. *
  784. * @param {number} delta - The amount to change the counter by.
  785. */
  786. function updateUnreadCounterValue(delta) {
  787. document.querySelectorAll("span.unread-counter").forEach((element) => {
  788. const oldValue = parseInt(element.textContent, 10);
  789. element.textContent = oldValue + delta;
  790. });
  791. if (window.location.href.endsWith('/unread')) {
  792. const oldValue = parseInt(document.title.split('(')[1], 10);
  793. const newValue = oldValue + delta;
  794. document.title = document.title.replace(/(.*?)\(\d+\)(.*?)/, `$1(${newValue})$2`);
  795. }
  796. }
  797. /**
  798. * Handle confirmation messages for actions that require user confirmation.
  799. *
  800. * This function modifies the link element to show a confirmation question with "Yes" and "No" buttons.
  801. * If the user clicks "Yes", it calls the provided callback with the URL and redirect URL.
  802. * If the user clicks "No", it either redirects to a no-action URL or restores the link element.
  803. *
  804. * @param {Element} linkElement - The link or button element that triggered the confirmation.
  805. * @param {function} callback - The callback function to execute if the user confirms the action.
  806. * @returns {void}
  807. */
  808. function handleConfirmationMessage(linkElement, callback) {
  809. if (linkElement.tagName !== 'A' && linkElement.tagName !== "BUTTON") {
  810. linkElement = linkElement.parentNode;
  811. }
  812. linkElement.style.display = "none";
  813. const containerElement = linkElement.parentNode;
  814. const questionElement = document.createElement("span");
  815. function createLoadingElement() {
  816. const loadingElement = document.createElement("span");
  817. loadingElement.className = "loading";
  818. loadingElement.appendChild(document.createTextNode(linkElement.dataset.labelLoading));
  819. questionElement.remove();
  820. containerElement.appendChild(loadingElement);
  821. }
  822. const yesElement = document.createElement("button");
  823. yesElement.appendChild(document.createTextNode(linkElement.dataset.labelYes));
  824. yesElement.onclick = (event) => {
  825. event.preventDefault();
  826. createLoadingElement();
  827. callback(linkElement.dataset.url, linkElement.dataset.redirectUrl);
  828. };
  829. const noElement = document.createElement("button");
  830. noElement.appendChild(document.createTextNode(linkElement.dataset.labelNo));
  831. noElement.onclick = (event) => {
  832. event.preventDefault();
  833. const noActionUrl = linkElement.dataset.noActionUrl;
  834. if (noActionUrl) {
  835. createLoadingElement();
  836. callback(noActionUrl, linkElement.dataset.redirectUrl);
  837. } else {
  838. linkElement.style.display = "inline";
  839. questionElement.remove();
  840. }
  841. };
  842. questionElement.className = "confirm";
  843. questionElement.appendChild(document.createTextNode(linkElement.dataset.labelQuestion + " "));
  844. questionElement.appendChild(yesElement);
  845. questionElement.appendChild(document.createTextNode(", "));
  846. questionElement.appendChild(noElement);
  847. containerElement.appendChild(questionElement);
  848. }
  849. /**
  850. * Check if the player is actually playing a media
  851. *
  852. * @param mediaElement the player element itself
  853. * @returns {boolean}
  854. */
  855. function isPlayerPlaying(mediaElement) {
  856. return mediaElement &&
  857. mediaElement.currentTime > 0 &&
  858. !mediaElement.paused &&
  859. !mediaElement.ended &&
  860. mediaElement.readyState > 2; // https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/readyState
  861. }
  862. /**
  863. * Handle player progression save and mark as read on completion.
  864. *
  865. * This function is triggered on the `timeupdate` event of the media player.
  866. * It saves the current playback position and marks the entry as read if the completion percentage is reached.
  867. *
  868. * @param {Element} playerElement The media player element (audio or video).
  869. */
  870. function handlePlayerProgressionSaveAndMarkAsReadOnCompletion(playerElement) {
  871. if (!isPlayerPlaying(playerElement)) {
  872. return;
  873. }
  874. const currentPositionInSeconds = Math.floor(playerElement.currentTime);
  875. const lastKnownPositionInSeconds = parseInt(playerElement.dataset.lastPosition, 10);
  876. const markAsReadOnCompletion = parseFloat(playerElement.dataset.markReadOnCompletion);
  877. const recordInterval = 10;
  878. // We limit the number of update to only one by interval. Otherwise, we would have multiple update per seconds
  879. if (currentPositionInSeconds >= (lastKnownPositionInSeconds + recordInterval) ||
  880. currentPositionInSeconds <= (lastKnownPositionInSeconds - recordInterval)
  881. ) {
  882. playerElement.dataset.lastPosition = currentPositionInSeconds.toString();
  883. sendPOSTRequest(playerElement.dataset.saveUrl, { progression: currentPositionInSeconds });
  884. // Handle the mark as read on completion
  885. if (markAsReadOnCompletion >= 0 && playerElement.duration > 0) {
  886. const completion = currentPositionInSeconds / playerElement.duration;
  887. if (completion >= markAsReadOnCompletion) {
  888. handleEntryStatus("none", document.querySelector(":is(a, button)[data-toggle-status]"), true);
  889. }
  890. }
  891. }
  892. }
  893. /**
  894. * Handle media control actions like seeking and changing playback speed.
  895. *
  896. * This function is triggered by clicking on media control buttons.
  897. * It adjusts the playback position or speed of media elements with the same enclosure ID.
  898. *
  899. * @param {Element} mediaPlayerButtonElement
  900. */
  901. function handleMediaControlButtonClick(mediaPlayerButtonElement) {
  902. const actionType = mediaPlayerButtonElement.dataset.enclosureAction;
  903. const actionValue = parseFloat(mediaPlayerButtonElement.dataset.actionValue);
  904. const enclosureID = mediaPlayerButtonElement.dataset.enclosureId;
  905. const mediaElements = document.querySelectorAll(`audio[data-enclosure-id="${enclosureID}"],video[data-enclosure-id="${enclosureID}"]`);
  906. const speedIndicatorElements = document.querySelectorAll(`span.speed-indicator[data-enclosure-id="${enclosureID}"]`);
  907. mediaElements.forEach((mediaElement) => {
  908. switch (actionType) {
  909. case "seek":
  910. mediaElement.currentTime = Math.max(mediaElement.currentTime + actionValue, 0);
  911. break;
  912. case "speed":
  913. // 0.25 was chosen because it will allow to get back to 1x in two "faster" clicks.
  914. // A lower value would result in a playback rate of 0, effectively pausing playback.
  915. mediaElement.playbackRate = Math.max(0.25, mediaElement.playbackRate + actionValue);
  916. speedIndicatorElements.forEach((speedIndicatorElement) => {
  917. speedIndicatorElement.innerText = `${mediaElement.playbackRate.toFixed(2)}x`;
  918. });
  919. break;
  920. case "speed-reset":
  921. mediaElement.playbackRate = actionValue ;
  922. speedIndicatorElements.forEach((speedIndicatorElement) => {
  923. // Two digit precision to ensure we always have the same number of characters (4) to avoid controls moving when clicking buttons because of more or less characters.
  924. // The trick only works on rates less than 10, but it feels an acceptable trade-off considering the feature
  925. speedIndicatorElement.innerText = `${mediaElement.playbackRate.toFixed(2)}x`;
  926. });
  927. break;
  928. }
  929. });
  930. }
  931. /**
  932. * Initialize media player event handlers.
  933. */
  934. function initializeMediaPlayerHandlers() {
  935. document.querySelectorAll("button[data-enclosure-action]").forEach((element) => {
  936. element.addEventListener("click", () => handleMediaControlButtonClick(element));
  937. });
  938. // Set playback from the last position if available
  939. document.querySelectorAll("audio[data-last-position],video[data-last-position]").forEach((element) => {
  940. if (element.dataset.lastPosition) {
  941. element.currentTime = element.dataset.lastPosition;
  942. }
  943. element.ontimeupdate = () => handlePlayerProgressionSaveAndMarkAsReadOnCompletion(element);
  944. });
  945. // Set playback speed from the data attribute if available
  946. document.querySelectorAll("audio[data-playback-rate],video[data-playback-rate]").forEach((element) => {
  947. if (element.dataset.playbackRate) {
  948. element.playbackRate = element.dataset.playbackRate;
  949. if (element.dataset.enclosureId) {
  950. document.querySelectorAll(`span.speed-indicator[data-enclosure-id="${element.dataset.enclosureId}"]`).forEach((speedIndicatorElement) => {
  951. speedIndicatorElement.innerText = `${parseFloat(element.dataset.playbackRate).toFixed(2)}x`;
  952. });
  953. }
  954. }
  955. });
  956. }
  957. /**
  958. * Initialize the service worker and PWA installation prompt.
  959. */
  960. function initializeServiceWorker() {
  961. // Register service worker if supported
  962. if ("serviceWorker" in navigator) {
  963. const serviceWorkerURL = document.body.dataset.serviceWorkerUrl;
  964. if (serviceWorkerURL) {
  965. const ttpolicy = trustedTypes.createPolicy('url', {createScriptURL: src => src});
  966. navigator.serviceWorker.register(ttpolicy.createScriptURL(serviceWorkerURL), {
  967. type: "module"
  968. }).catch((error) => {
  969. console.error("Service Worker registration failed:", error);
  970. });
  971. }
  972. }
  973. // PWA installation prompt handling
  974. window.addEventListener("beforeinstallprompt", (event) => {
  975. let deferredPrompt = event;
  976. const promptHomeScreen = document.getElementById("prompt-home-screen");
  977. const btnAddToHomeScreen = document.getElementById("btn-add-to-home-screen");
  978. if (!promptHomeScreen || !btnAddToHomeScreen) return;
  979. promptHomeScreen.style.display = "block";
  980. btnAddToHomeScreen.addEventListener("click", (event) => {
  981. event.preventDefault();
  982. deferredPrompt.prompt();
  983. deferredPrompt.userChoice.then(() => {
  984. deferredPrompt = null;
  985. promptHomeScreen.style.display = "none";
  986. });
  987. });
  988. });
  989. }
  990. /**
  991. * Initialize WebAuthn handlers if supported.
  992. */
  993. function initializeWebAuthn() {
  994. if (typeof WebAuthnHandler !== 'function') return;
  995. if (!WebAuthnHandler.isWebAuthnSupported()) return;
  996. const webauthnHandler = new WebAuthnHandler();
  997. // Setup delete credentials handler
  998. onClick("#webauthn-delete", () => { webauthnHandler.removeAllCredentials(); });
  999. // Setup registration
  1000. const registerButton = document.getElementById("webauthn-register");
  1001. if (registerButton) {
  1002. registerButton.disabled = false;
  1003. onClick("#webauthn-register", () => {
  1004. webauthnHandler.register().catch((err) => WebAuthnHandler.showErrorMessage(err));
  1005. });
  1006. }
  1007. // Setup login
  1008. const loginButton = document.getElementById("webauthn-login");
  1009. const usernameField = document.getElementById("form-username");
  1010. if (loginButton && usernameField) {
  1011. const abortController = new AbortController();
  1012. loginButton.disabled = false;
  1013. onClick("#webauthn-login", () => {
  1014. abortController.abort();
  1015. webauthnHandler.login(usernameField.value).catch(err => WebAuthnHandler.showErrorMessage(err));
  1016. });
  1017. webauthnHandler.conditionalLogin(abortController).catch(err => WebAuthnHandler.showErrorMessage(err));
  1018. }
  1019. }
  1020. /**
  1021. * Initialize keyboard shortcuts for navigation and actions.
  1022. */
  1023. function initializeKeyboardShortcuts() {
  1024. if (document.querySelector("body[data-disable-keyboard-shortcuts=true]")) return;
  1025. const keyboardHandler = new KeyboardHandler();
  1026. // Navigation shortcuts
  1027. keyboardHandler.on("g u", () => goToPage("unread"));
  1028. keyboardHandler.on("g b", () => goToPage("starred"));
  1029. keyboardHandler.on("g h", () => goToPage("history"));
  1030. keyboardHandler.on("g f", goToFeedOrFeedsPage);
  1031. keyboardHandler.on("g c", () => goToPage("categories"));
  1032. keyboardHandler.on("g s", () => goToPage("settings"));
  1033. keyboardHandler.on("g g", () => goToPreviousPage(TOP));
  1034. keyboardHandler.on("G", () => goToNextPage(BOTTOM));
  1035. keyboardHandler.on("/", () => goToPage("search"));
  1036. // Item navigation
  1037. keyboardHandler.on("ArrowLeft", goToPreviousPage);
  1038. keyboardHandler.on("ArrowRight", goToNextPage);
  1039. keyboardHandler.on("k", goToPreviousPage);
  1040. keyboardHandler.on("p", goToPreviousPage);
  1041. keyboardHandler.on("j", goToNextPage);
  1042. keyboardHandler.on("n", goToNextPage);
  1043. keyboardHandler.on("h", () => goToPage("previous"));
  1044. keyboardHandler.on("l", () => goToPage("next"));
  1045. keyboardHandler.on("z t", scrollToCurrentItemAction);
  1046. // Item actions
  1047. keyboardHandler.on("o", openSelectedItemAction);
  1048. keyboardHandler.on("Enter", () => openSelectedItemAction());
  1049. keyboardHandler.on("v", () => openOriginalLinkAction(false));
  1050. keyboardHandler.on("V", () => openOriginalLinkAction(true));
  1051. keyboardHandler.on("c", () => openCommentLinkAction(false));
  1052. keyboardHandler.on("C", () => openCommentLinkAction(true));
  1053. // Entry management
  1054. keyboardHandler.on("m", () => handleEntryStatus("next"));
  1055. keyboardHandler.on("M", () => handleEntryStatus("previous"));
  1056. keyboardHandler.on("A", markPageAsReadAction);
  1057. keyboardHandler.on("s", () => handleSaveEntryAction());
  1058. keyboardHandler.on("d", handleFetchOriginalContentAction);
  1059. keyboardHandler.on("f", () => handleStarAction());
  1060. // Feed actions
  1061. keyboardHandler.on("F", goToFeedPage);
  1062. keyboardHandler.on("R", handleRefreshAllFeedsAction);
  1063. keyboardHandler.on("+", goToAddSubscriptionPage);
  1064. keyboardHandler.on("#", handleRemoveFeedAction);
  1065. // UI actions
  1066. keyboardHandler.on("?", showKeyboardShortcutsAction);
  1067. keyboardHandler.on("Escape", () => KeyboardModalHandler.close());
  1068. keyboardHandler.on("a", () => {
  1069. const enclosureElement = document.querySelector('.entry-enclosures');
  1070. if (enclosureElement) {
  1071. enclosureElement.toggleAttribute('open');
  1072. }
  1073. });
  1074. keyboardHandler.listen();
  1075. }
  1076. /**
  1077. * Initialize touch handler for mobile devices.
  1078. */
  1079. function initializeTouchHandler() {
  1080. if ( "ontouchstart" in window || navigator.maxTouchPoints > 0) {
  1081. const touchHandler = new TouchHandler();
  1082. touchHandler.listen();
  1083. }
  1084. }
  1085. /**
  1086. * Initialize click handlers for various UI elements.
  1087. */
  1088. function initializeClickHandlers() {
  1089. // Entry actions
  1090. onClick(":is(a, button)[data-save-entry]", (event) => handleSaveEntryAction(event.target));
  1091. onClick(":is(a, button)[data-toggle-starred]", (event) => handleStarAction(event.target));
  1092. onClick(":is(a, button)[data-toggle-status]", (event) => handleEntryStatus("next", event.target));
  1093. onClick(":is(a, button)[data-fetch-content-entry]", handleFetchOriginalContentAction);
  1094. onClick(":is(a, button)[data-share-status]", handleEntryShareAction);
  1095. // Page actions with confirmation
  1096. onClick(":is(a, button)[data-action=markPageAsRead]", (event) => handleConfirmationMessage(event.target, markPageAsReadAction));
  1097. // Generic confirmation handler
  1098. onClick(":is(a, button)[data-confirm]", (event) => {
  1099. handleConfirmationMessage(event.target, (url, redirectURL) => {
  1100. sendPOSTRequest(url).then((response) => {
  1101. if (redirectURL) {
  1102. window.location.href = redirectURL;
  1103. } else if (response?.redirected && response.url) {
  1104. window.location.href = response.url;
  1105. } else {
  1106. window.location.reload();
  1107. }
  1108. });
  1109. });
  1110. });
  1111. // Original link handlers (both click and middle-click)
  1112. const handleOriginalLink = (event) => handleEntryStatus("next", event.target, true);
  1113. onClick("a[data-original-link='true']", handleOriginalLink, true);
  1114. onAuxClick("a[data-original-link='true']", (event) => {
  1115. if (event.button === 1) {
  1116. handleOriginalLink(event);
  1117. }
  1118. }, true);
  1119. }
  1120. // Initialize application handlers
  1121. initializeMainMenuHandlers();
  1122. initializeFormHandlers();
  1123. initializeMediaPlayerHandlers();
  1124. initializeWebAuthn();
  1125. initializeKeyboardShortcuts();
  1126. initializeTouchHandler();
  1127. initializeClickHandlers();
  1128. initializeServiceWorker();
  1129. // Reload the page if it was restored from the back-forward cache and mark entries as read is enabled.
  1130. window.addEventListener("pageshow", (event) => {
  1131. if (event.persisted && document.body.dataset.markAsReadOnView === "true") {
  1132. location.reload();
  1133. }
  1134. });