app.js 45 KB

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