app.js 41 KB

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