app.js 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  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 handleBookmark(element) {
  557. const toasting = !element;
  558. const currentEntry = findEntry(element);
  559. if (currentEntry) {
  560. toggleBookmark(currentEntry, toasting);
  561. }
  562. }
  563. /**
  564. * Toggle the bookmark status of an entry.
  565. *
  566. * @param {Element} parentElement - The parent element containing the bookmark button.
  567. * @param {boolean} toasting - Whether to show a toast notification.
  568. * @returns {void}
  569. */
  570. function toggleBookmark(parentElement, toasting) {
  571. const buttonElement = parentElement.querySelector(":is(a, button)[data-toggle-bookmark]");
  572. if (!buttonElement) return;
  573. insertIconLabelElement(buttonElement, buttonElement.dataset.labelLoading);
  574. sendPOSTRequest(buttonElement.dataset.bookmarkUrl).then(() => {
  575. const currentStarStatus = buttonElement.dataset.value;
  576. const newStarStatus = currentStarStatus === "star" ? "unstar" : "star";
  577. const isStarred = currentStarStatus === "star";
  578. const iconElement = document.querySelector(isStarred ? "template#icon-star" : "template#icon-unstar");
  579. const label = isStarred ? buttonElement.dataset.labelStar : buttonElement.dataset.labelUnstar;
  580. if (toasting) {
  581. const toastKey = isStarred ? "toastUnstar" : "toastStar";
  582. showToast(buttonElement.dataset[toastKey], iconElement);
  583. }
  584. buttonElement.replaceChildren(iconElement.content.cloneNode(true));
  585. insertIconLabelElement(buttonElement, label);
  586. buttonElement.dataset.value = newStarStatus;
  587. });
  588. }
  589. /**
  590. * Handle fetching the original content of an entry.
  591. *
  592. * @returns {void}
  593. */
  594. function handleFetchOriginalContent() {
  595. if (isListView()) return;
  596. const buttonElement = document.querySelector(":is(a, button)[data-fetch-content-entry]");
  597. if (!buttonElement) return;
  598. const previousElement = buttonElement.cloneNode(true);
  599. insertIconLabelElement(buttonElement, buttonElement.dataset.labelLoading);
  600. sendPOSTRequest(buttonElement.dataset.fetchContentUrl).then((response) => {
  601. buttonElement.textContent = '';
  602. buttonElement.appendChild(previousElement);
  603. response.json().then((data) => {
  604. if (data.content && data.reading_time) {
  605. document.querySelector(".entry-content").innerHTML = ttpolicy.createHTML(data.content);
  606. const entryReadingtimeElement = document.querySelector(".entry-reading-time");
  607. if (entryReadingtimeElement) {
  608. entryReadingtimeElement.textContent = data.reading_time;
  609. }
  610. }
  611. });
  612. });
  613. }
  614. /**
  615. * Open the original link of an entry.
  616. *
  617. * @param {boolean} openLinkInCurrentTab - Whether to open the link in the current tab.
  618. * @returns {void}
  619. */
  620. function openOriginalLink(openLinkInCurrentTab) {
  621. if (isEntryView()) {
  622. openOriginalLinkFromEntryView(openLinkInCurrentTab);
  623. } else if (isListView()) {
  624. openOriginalLinkFromListView();
  625. }
  626. }
  627. /**
  628. * Open the original link from entry view.
  629. *
  630. * @param {boolean} openLinkInCurrentTab - Whether to open the link in the current tab.
  631. * @returns {void}
  632. */
  633. function openOriginalLinkFromEntryView(openLinkInCurrentTab) {
  634. const entryLink = document.querySelector(".entry h1 a");
  635. if (!entryLink) return;
  636. const url = entryLink.getAttribute("href");
  637. if (openLinkInCurrentTab) {
  638. window.location.href = url;
  639. } else {
  640. openNewTab(url);
  641. }
  642. }
  643. /**
  644. * Open the original link from list view.
  645. *
  646. * @returns {void}
  647. */
  648. function openOriginalLinkFromListView() {
  649. const currentItem = document.querySelector(".current-item");
  650. const originalLink = currentItem?.querySelector(":is(a, button)[data-original-link]");
  651. if (!currentItem || !originalLink) return;
  652. // Open the link
  653. openNewTab(originalLink.getAttribute("href"));
  654. // Don't navigate or mark as read on starred page
  655. const isStarredPage = document.location.href === document.querySelector(':is(a, button)[data-page=starred]').href;
  656. if (isStarredPage) return;
  657. // Navigate to next item
  658. goToListItem(1);
  659. // Mark as read if currently unread
  660. if (currentItem.classList.contains("item-status-unread")) {
  661. currentItem.classList.remove("item-status-unread");
  662. currentItem.classList.add("item-status-read");
  663. const entryID = parseInt(currentItem.dataset.id, 10);
  664. updateEntriesStatus([entryID], "read");
  665. }
  666. }
  667. /**
  668. * Open the comments link of an entry.
  669. *
  670. * @param {boolean} openLinkInCurrentTab - Whether to open the link in the current tab.
  671. * @returns {void}
  672. */
  673. function openCommentLink(openLinkInCurrentTab) {
  674. const entryLink = document.querySelector(isListView() ? ".current-item :is(a, button)[data-comments-link]" : ":is(a, button)[data-comments-link]");
  675. if (entryLink) {
  676. if (openLinkInCurrentTab) {
  677. window.location.href = entryLink.getAttribute("href");
  678. } else {
  679. openNewTab(entryLink.getAttribute("href"));
  680. }
  681. }
  682. }
  683. /**
  684. * Open the selected item in the current view.
  685. *
  686. * If the current view is a list view, it will navigate to the link of the currently selected item.
  687. * If the current view is an entry view, it will navigate to the link of the entry.
  688. */
  689. function openSelectedItem() {
  690. const currentItemLink = document.querySelector(".current-item .item-title a");
  691. if (currentItemLink) {
  692. window.location.href = currentItemLink.getAttribute("href");
  693. }
  694. }
  695. /**
  696. * Unsubscribe from the feed of the currently selected item.
  697. */
  698. function unsubscribeFromFeed() {
  699. const unsubscribeLink = document.querySelector("[data-action=remove-feed]");
  700. if (unsubscribeLink) {
  701. sendPOSTRequest(unsubscribeLink.dataset.url).then(() => {
  702. window.location.href = unsubscribeLink.dataset.redirectUrl || window.location.href;
  703. });
  704. }
  705. }
  706. /**
  707. * Scroll the page to the currently selected item.
  708. */
  709. function scrollToCurrentItem() {
  710. const currentItem = document.querySelector(".current-item");
  711. if (currentItem) {
  712. scrollPageTo(currentItem, true);
  713. }
  714. }
  715. /**
  716. * Update the unread counter value.
  717. *
  718. * @param {number} delta - The amount to change the counter by.
  719. */
  720. function updateUnreadCounterValue(delta) {
  721. document.querySelectorAll("span.unread-counter").forEach((element) => {
  722. const oldValue = parseInt(element.textContent, 10);
  723. element.textContent = oldValue + delta;
  724. });
  725. if (window.location.href.endsWith('/unread')) {
  726. const oldValue = parseInt(document.title.split('(')[1], 10);
  727. const newValue = oldValue + delta;
  728. document.title = document.title.replace(/(.*?)\(\d+\)(.*?)/, `$1(${newValue})$2`);
  729. }
  730. }
  731. /**
  732. * Handle confirmation messages for actions that require user confirmation.
  733. *
  734. * This function modifies the link element to show a confirmation question with "Yes" and "No" buttons.
  735. * If the user clicks "Yes", it calls the provided callback with the URL and redirect URL.
  736. * If the user clicks "No", it either redirects to a no-action URL or restores the link element.
  737. *
  738. * @param {Element} linkElement - The link or button element that triggered the confirmation.
  739. * @param {function} callback - The callback function to execute if the user confirms the action.
  740. * @returns {void}
  741. */
  742. function handleConfirmationMessage(linkElement, callback) {
  743. if (linkElement.tagName !== 'A' && linkElement.tagName !== "BUTTON") {
  744. linkElement = linkElement.parentNode;
  745. }
  746. linkElement.style.display = "none";
  747. const containerElement = linkElement.parentNode;
  748. const questionElement = document.createElement("span");
  749. function createLoadingElement() {
  750. const loadingElement = document.createElement("span");
  751. loadingElement.className = "loading";
  752. loadingElement.appendChild(document.createTextNode(linkElement.dataset.labelLoading));
  753. questionElement.remove();
  754. containerElement.appendChild(loadingElement);
  755. }
  756. const yesElement = document.createElement("button");
  757. yesElement.appendChild(document.createTextNode(linkElement.dataset.labelYes));
  758. yesElement.onclick = (event) => {
  759. event.preventDefault();
  760. createLoadingElement();
  761. callback(linkElement.dataset.url, linkElement.dataset.redirectUrl);
  762. };
  763. const noElement = document.createElement("button");
  764. noElement.appendChild(document.createTextNode(linkElement.dataset.labelNo));
  765. noElement.onclick = (event) => {
  766. event.preventDefault();
  767. const noActionUrl = linkElement.dataset.noActionUrl;
  768. if (noActionUrl) {
  769. createLoadingElement();
  770. callback(noActionUrl, linkElement.dataset.redirectUrl);
  771. } else {
  772. linkElement.style.display = "inline";
  773. questionElement.remove();
  774. }
  775. };
  776. questionElement.className = "confirm";
  777. questionElement.appendChild(document.createTextNode(linkElement.dataset.labelQuestion + " "));
  778. questionElement.appendChild(yesElement);
  779. questionElement.appendChild(document.createTextNode(", "));
  780. questionElement.appendChild(noElement);
  781. containerElement.appendChild(questionElement);
  782. }
  783. /**
  784. * Show a toast notification.
  785. *
  786. * @param {string} toastMessage - The label to display in the toast.
  787. * @param {Element} iconElement - The icon element to display in the toast.
  788. * @returns {void}
  789. */
  790. function showToast(toastMessage, iconElement) {
  791. if (!toastMessage || !iconElement) {
  792. return;
  793. }
  794. const toastMsgElement = document.getElementById("toast-msg");
  795. toastMsgElement.replaceChildren(iconElement.content.cloneNode(true));
  796. insertIconLabelElement(toastMsgElement, toastMessage);
  797. const toastElementWrapper = document.getElementById("toast-wrapper");
  798. toastElementWrapper.classList.remove('toast-animate');
  799. setTimeout(() => toastElementWrapper.classList.add('toast-animate'), 100);
  800. }
  801. /**
  802. * Check if the player is actually playing a media
  803. *
  804. * @param mediaElement the player element itself
  805. * @returns {boolean}
  806. */
  807. function isPlayerPlaying(mediaElement) {
  808. return mediaElement &&
  809. mediaElement.currentTime > 0 &&
  810. !mediaElement.paused &&
  811. !mediaElement.ended &&
  812. mediaElement.readyState > 2; // https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/readyState
  813. }
  814. /**
  815. * Handle player progression save and mark as read on completion.
  816. *
  817. * This function is triggered on the `timeupdate` event of the media player.
  818. * It saves the current playback position and marks the entry as read if the completion percentage is reached.
  819. *
  820. * @param {Element} playerElement The media player element (audio or video).
  821. */
  822. function handlePlayerProgressionSaveAndMarkAsReadOnCompletion(playerElement) {
  823. if (!isPlayerPlaying(playerElement)) {
  824. return;
  825. }
  826. const currentPositionInSeconds = Math.floor(playerElement.currentTime);
  827. const lastKnownPositionInSeconds = parseInt(playerElement.dataset.lastPosition, 10);
  828. const markAsReadOnCompletion = parseFloat(playerElement.dataset.markReadOnCompletion);
  829. const recordInterval = 10;
  830. // We limit the number of update to only one by interval. Otherwise, we would have multiple update per seconds
  831. if (currentPositionInSeconds >= (lastKnownPositionInSeconds + recordInterval) ||
  832. currentPositionInSeconds <= (lastKnownPositionInSeconds - recordInterval)
  833. ) {
  834. playerElement.dataset.lastPosition = currentPositionInSeconds.toString();
  835. sendPOSTRequest(playerElement.dataset.saveUrl, { progression: currentPositionInSeconds });
  836. // Handle the mark as read on completion
  837. if (markAsReadOnCompletion >= 0 && playerElement.duration > 0) {
  838. const completion = currentPositionInSeconds / playerElement.duration;
  839. if (completion >= markAsReadOnCompletion) {
  840. handleEntryStatus("none", document.querySelector(":is(a, button)[data-toggle-status]"), true);
  841. }
  842. }
  843. }
  844. }
  845. /**
  846. * Handle media control actions like seeking and changing playback speed.
  847. *
  848. * This function is triggered by clicking on media control buttons.
  849. * It adjusts the playback position or speed of media elements with the same enclosure ID.
  850. *
  851. * @param {Element} mediaPlayerButtonElement
  852. */
  853. function handleMediaControlButtonClick(mediaPlayerButtonElement) {
  854. const actionType = mediaPlayerButtonElement.dataset.enclosureAction;
  855. const actionValue = parseFloat(mediaPlayerButtonElement.dataset.actionValue);
  856. const enclosureID = mediaPlayerButtonElement.dataset.enclosureId;
  857. const mediaElements = document.querySelectorAll(`audio[data-enclosure-id="${enclosureID}"],video[data-enclosure-id="${enclosureID}"]`);
  858. const speedIndicatorElements = document.querySelectorAll(`span.speed-indicator[data-enclosure-id="${enclosureID}"]`);
  859. mediaElements.forEach((mediaElement) => {
  860. switch (actionType) {
  861. case "seek":
  862. mediaElement.currentTime = Math.max(mediaElement.currentTime + actionValue, 0);
  863. break;
  864. case "speed":
  865. // 0.25 was chosen because it will allow to get back to 1x in two "faster" clicks.
  866. // A lower value would result in a playback rate of 0, effectively pausing playback.
  867. mediaElement.playbackRate = Math.max(0.25, mediaElement.playbackRate + actionValue);
  868. speedIndicatorElements.forEach((speedIndicatorElement) => {
  869. speedIndicatorElement.innerText = `${mediaElement.playbackRate.toFixed(2)}x`;
  870. });
  871. break;
  872. case "speed-reset":
  873. mediaElement.playbackRate = actionValue ;
  874. speedIndicatorElements.forEach((speedIndicatorElement) => {
  875. // 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.
  876. // The trick only works on rates less than 10, but it feels an acceptable trade-off considering the feature
  877. speedIndicatorElement.innerText = `${mediaElement.playbackRate.toFixed(2)}x`;
  878. });
  879. break;
  880. }
  881. });
  882. }
  883. /**
  884. * Initialize media player event handlers.
  885. */
  886. function initializeMediaPlayerHandlers() {
  887. document.querySelectorAll("button[data-enclosure-action]").forEach((element) => {
  888. element.addEventListener("click", () => handleMediaControlButtonClick(element));
  889. });
  890. // Set playback from the last position if available
  891. document.querySelectorAll("audio[data-last-position],video[data-last-position]").forEach((element) => {
  892. if (element.dataset.lastPosition) {
  893. element.currentTime = element.dataset.lastPosition;
  894. }
  895. element.ontimeupdate = () => handlePlayerProgressionSaveAndMarkAsReadOnCompletion(element);
  896. });
  897. // Set playback speed from the data attribute if available
  898. document.querySelectorAll("audio[data-playback-rate],video[data-playback-rate]").forEach((element) => {
  899. if (element.dataset.playbackRate) {
  900. element.playbackRate = element.dataset.playbackRate;
  901. if (element.dataset.enclosureId) {
  902. document.querySelectorAll(`span.speed-indicator[data-enclosure-id="${element.dataset.enclosureId}"]`).forEach((speedIndicatorElement) => {
  903. speedIndicatorElement.innerText = `${parseFloat(element.dataset.playbackRate).toFixed(2)}x`;
  904. });
  905. }
  906. }
  907. });
  908. }
  909. /**
  910. * Initialize the service worker and PWA installation prompt.
  911. */
  912. function initializeServiceWorker() {
  913. // Register service worker if supported
  914. if ("serviceWorker" in navigator) {
  915. const serviceWorkerURL = document.body.dataset.serviceWorkerUrl;
  916. if (serviceWorkerURL) {
  917. navigator.serviceWorker.register(ttpolicy.createScriptURL(serviceWorkerURL), {
  918. type: "module"
  919. }).catch((error) => {
  920. console.error("Service Worker registration failed:", error);
  921. });
  922. }
  923. }
  924. // PWA installation prompt handling
  925. window.addEventListener("beforeinstallprompt", (event) => {
  926. let deferredPrompt = event;
  927. const promptHomeScreen = document.getElementById("prompt-home-screen");
  928. const btnAddToHomeScreen = document.getElementById("btn-add-to-home-screen");
  929. if (!promptHomeScreen || !btnAddToHomeScreen) return;
  930. promptHomeScreen.style.display = "block";
  931. btnAddToHomeScreen.addEventListener("click", (event) => {
  932. event.preventDefault();
  933. deferredPrompt.prompt();
  934. deferredPrompt.userChoice.then(() => {
  935. deferredPrompt = null;
  936. promptHomeScreen.style.display = "none";
  937. });
  938. });
  939. });
  940. }
  941. /**
  942. * Initialize WebAuthn handlers if supported.
  943. */
  944. function initializeWebAuthn() {
  945. if (!WebAuthnHandler.isWebAuthnSupported()) return;
  946. const webauthnHandler = new WebAuthnHandler();
  947. // Setup delete credentials handler
  948. onClick("#webauthn-delete", () => { webauthnHandler.removeAllCredentials(); });
  949. // Setup registration
  950. const registerButton = document.getElementById("webauthn-register");
  951. if (registerButton) {
  952. registerButton.disabled = false;
  953. onClick("#webauthn-register", () => {
  954. webauthnHandler.register().catch((err) => WebAuthnHandler.showErrorMessage(err));
  955. });
  956. }
  957. // Setup login
  958. const loginButton = document.getElementById("webauthn-login");
  959. const usernameField = document.getElementById("form-username");
  960. if (loginButton && usernameField) {
  961. const abortController = new AbortController();
  962. loginButton.disabled = false;
  963. onClick("#webauthn-login", () => {
  964. abortController.abort();
  965. webauthnHandler.login(usernameField.value).catch(err => WebAuthnHandler.showErrorMessage(err));
  966. });
  967. webauthnHandler.conditionalLogin(abortController).catch(err => WebAuthnHandler.showErrorMessage(err));
  968. }
  969. }
  970. /**
  971. * Initialize keyboard shortcuts for navigation and actions.
  972. */
  973. function initializeKeyboardShortcuts() {
  974. if (document.querySelector("body[data-disable-keyboard-shortcuts=true]")) return;
  975. const keyboardHandler = new KeyboardHandler();
  976. // Navigation shortcuts
  977. keyboardHandler.on("g u", () => goToPage("unread"));
  978. keyboardHandler.on("g b", () => goToPage("starred"));
  979. keyboardHandler.on("g h", () => goToPage("history"));
  980. keyboardHandler.on("g f", goToFeedOrFeedsPage);
  981. keyboardHandler.on("g c", () => goToPage("categories"));
  982. keyboardHandler.on("g s", () => goToPage("settings"));
  983. keyboardHandler.on("g g", () => goToPreviousPage(TOP));
  984. keyboardHandler.on("G", () => goToNextPage(BOTTOM));
  985. keyboardHandler.on("/", () => goToPage("search"));
  986. // Item navigation
  987. keyboardHandler.on("ArrowLeft", goToPreviousPage);
  988. keyboardHandler.on("ArrowRight", goToNextPage);
  989. keyboardHandler.on("k", goToPreviousPage);
  990. keyboardHandler.on("p", goToPreviousPage);
  991. keyboardHandler.on("j", goToNextPage);
  992. keyboardHandler.on("n", goToNextPage);
  993. keyboardHandler.on("h", () => goToPage("previous"));
  994. keyboardHandler.on("l", () => goToPage("next"));
  995. keyboardHandler.on("z t", scrollToCurrentItem);
  996. // Item actions
  997. keyboardHandler.on("o", openSelectedItem);
  998. keyboardHandler.on("Enter", () => openSelectedItem());
  999. keyboardHandler.on("v", () => openOriginalLink(false));
  1000. keyboardHandler.on("V", () => openOriginalLink(true));
  1001. keyboardHandler.on("c", () => openCommentLink(false));
  1002. keyboardHandler.on("C", () => openCommentLink(true));
  1003. // Entry management
  1004. keyboardHandler.on("m", () => handleEntryStatus("next"));
  1005. keyboardHandler.on("M", () => handleEntryStatus("previous"));
  1006. keyboardHandler.on("A", markPageAsRead);
  1007. keyboardHandler.on("s", () => handleSaveEntryAction());
  1008. keyboardHandler.on("d", handleFetchOriginalContent);
  1009. keyboardHandler.on("f", () => handleBookmark());
  1010. // Feed actions
  1011. keyboardHandler.on("F", goToFeedPage);
  1012. keyboardHandler.on("R", handleRefreshAllFeedsAction);
  1013. keyboardHandler.on("+", goToAddSubscriptionPage);
  1014. keyboardHandler.on("#", unsubscribeFromFeed);
  1015. // UI actions
  1016. keyboardHandler.on("?", showKeyboardShortcuts);
  1017. keyboardHandler.on("Escape", () => ModalHandler.close());
  1018. keyboardHandler.on("a", () => {
  1019. const enclosureElement = document.querySelector('.entry-enclosures');
  1020. if (enclosureElement) {
  1021. enclosureElement.toggleAttribute('open');
  1022. }
  1023. });
  1024. keyboardHandler.listen();
  1025. }
  1026. /**
  1027. * Initialize touch handler for mobile devices.
  1028. */
  1029. function initializeTouchHandler() {
  1030. const touchHandler = new TouchHandler();
  1031. touchHandler.listen();
  1032. }
  1033. /**
  1034. * Initialize click handlers for various UI elements.
  1035. */
  1036. function initializeClickHandlers() {
  1037. // Entry actions
  1038. onClick(":is(a, button)[data-save-entry]", (event) => handleSaveEntryAction(event.target));
  1039. onClick(":is(a, button)[data-toggle-bookmark]", (event) => handleBookmark(event.target));
  1040. onClick(":is(a, button)[data-toggle-status]", (event) => handleEntryStatus("next", event.target));
  1041. onClick(":is(a, button)[data-fetch-content-entry]", handleFetchOriginalContent);
  1042. onClick(":is(a, button)[data-share-status]", handleEntryShareAction);
  1043. // Page actions with confirmation
  1044. onClick(":is(a, button)[data-action=markPageAsRead]", (event) =>
  1045. handleConfirmationMessage(event.target, markPageAsRead));
  1046. // Generic confirmation handler
  1047. onClick(":is(a, button)[data-confirm]", (event) => {
  1048. handleConfirmationMessage(event.target, (url, redirectURL) => {
  1049. sendPOSTRequest(url).then((response) => {
  1050. if (redirectURL) {
  1051. window.location.href = redirectURL;
  1052. } else if (response?.redirected && response.url) {
  1053. window.location.href = response.url;
  1054. } else {
  1055. window.location.reload();
  1056. }
  1057. });
  1058. });
  1059. });
  1060. // Original link handlers (both click and middle-click)
  1061. const handleOriginalLink = (event) => handleEntryStatus("next", event.target, true);
  1062. onClick("a[data-original-link='true']", handleOriginalLink, true);
  1063. onAuxClick("a[data-original-link='true']", (event) => {
  1064. if (event.button === 1) {
  1065. handleOriginalLink(event);
  1066. }
  1067. }, true);
  1068. }
  1069. // Initialize application handlers
  1070. initializeMainMenuHandlers();
  1071. initializeFormHandlers();
  1072. initializeMediaPlayerHandlers();
  1073. initializeWebAuthn();
  1074. initializeKeyboardShortcuts();
  1075. initializeTouchHandler();
  1076. initializeClickHandlers();
  1077. initializeServiceWorker();