app.js 43 KB

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