app.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  1. // Sentinel values for specific list navigation
  2. const TOP = 9999;
  3. const BOTTOM = -9999;
  4. /**
  5. * Get the CSRF token from the HTML document.
  6. *
  7. * @returns {string} The CSRF token.
  8. */
  9. function getCsrfToken() {
  10. return document.body.dataset.csrfToken || "";
  11. }
  12. /**
  13. * Open a new tab with the given URL.
  14. *
  15. * @param {string} url
  16. */
  17. function openNewTab(url) {
  18. const win = window.open("");
  19. win.opener = null;
  20. win.location = url;
  21. win.focus();
  22. }
  23. /**
  24. * Scroll the page to the given element.
  25. *
  26. * @param {Element} element
  27. * @param {boolean} evenIfOnScreen
  28. */
  29. function scrollPageTo(element, evenIfOnScreen) {
  30. const windowScrollPosition = window.scrollY;
  31. const windowHeight = document.documentElement.clientHeight;
  32. const viewportPosition = windowScrollPosition + windowHeight;
  33. const itemBottomPosition = element.offsetTop + element.offsetHeight;
  34. if (evenIfOnScreen || viewportPosition - itemBottomPosition < 0 || viewportPosition - element.offsetTop > windowHeight) {
  35. window.scrollTo(0, element.offsetTop - 10);
  36. }
  37. }
  38. /**
  39. * Attach a click event listener to elements matching the selector.
  40. *
  41. * @param {string} selector
  42. * @param {function} callback
  43. * @param {boolean} noPreventDefault
  44. */
  45. function onClick(selector, callback, noPreventDefault) {
  46. document.querySelectorAll(selector).forEach((element) => {
  47. element.onclick = (event) => {
  48. if (!noPreventDefault) {
  49. event.preventDefault();
  50. }
  51. callback(event);
  52. };
  53. });
  54. }
  55. /**
  56. * Attach an auxiliary click event listener to elements matching the selector.
  57. *
  58. * @param {string} selector
  59. * @param {function} callback
  60. * @param {boolean} noPreventDefault
  61. */
  62. function onAuxClick(selector, callback, noPreventDefault) {
  63. document.querySelectorAll(selector).forEach((element) => {
  64. element.onauxclick = (event) => {
  65. if (!noPreventDefault) {
  66. event.preventDefault();
  67. }
  68. callback(event);
  69. };
  70. });
  71. }
  72. /**
  73. * Filter visible elements based on the selector.
  74. *
  75. * @param {string} selector
  76. * @returns {Array<Element>}
  77. */
  78. function getVisibleElements(selector) {
  79. const elements = document.querySelectorAll(selector);
  80. return [...elements].filter((element) => element.offsetParent !== null);
  81. }
  82. /**
  83. * Get all visible entries on the current page.
  84. *
  85. * @return {Array<Element>}
  86. */
  87. function getVisibleEntries() {
  88. return getVisibleElements(".items .item");
  89. }
  90. /**
  91. * Check if the current view is a list view.
  92. *
  93. * @returns {boolean}
  94. */
  95. function isListView() {
  96. return document.querySelector(".items") !== null;
  97. }
  98. /**
  99. * Check if the current view is an entry view.
  100. *
  101. * @return {boolean}
  102. */
  103. function isEntryView() {
  104. return document.querySelector("section.entry") !== null;
  105. }
  106. /**
  107. * Find the entry element for the given element.
  108. *
  109. * @returns {Element|null}
  110. */
  111. function findEntry(element) {
  112. if (isListView()) {
  113. if (element) {
  114. return element.closest(".item");
  115. }
  116. return document.querySelector(".current-item");
  117. }
  118. return document.querySelector(".entry");
  119. }
  120. /**
  121. * Navigate to a specific page.
  122. *
  123. * @param {string} page - The page to navigate to.
  124. * @param {boolean} reloadOnFail - If true, reload the current page if the target page is not found.
  125. */
  126. function goToPage(page, reloadOnFail = false) {
  127. const element = document.querySelector(":is(a, button)[data-page=" + page + "]");
  128. if (element) {
  129. document.location.href = element.href;
  130. } else if (reloadOnFail) {
  131. window.location.reload();
  132. }
  133. }
  134. /**
  135. * Navigate to the previous page.
  136. *
  137. * If the offset is a KeyboardEvent, it will navigate to the previous item in the list.
  138. * If the offset is a number, it will jump that many items in the list.
  139. * If the offset is TOP, it will jump to the first item in the list.
  140. * If the offset is BOTTOM, it will jump to the last item in the list.
  141. * If the current view is an entry view, it will redirect to the previous page.
  142. *
  143. * @param {number|KeyboardEvent} offset - How many items to jump for focus.
  144. */
  145. function goToPreviousPage(offset) {
  146. if (offset instanceof KeyboardEvent) offset = -1;
  147. if (isListView()) {
  148. goToListItem(offset);
  149. } else {
  150. goToPage("previous");
  151. }
  152. }
  153. /**
  154. * Navigate to the next page.
  155. *
  156. * If the offset is a KeyboardEvent, it will navigate to the next item in the list.
  157. * If the offset is a number, it will jump that many items in the list.
  158. * If the offset is TOP, it will jump to the first item in the list.
  159. * If the offset is BOTTOM, it will jump to the last item in the list.
  160. * If the current view is an entry view, it will redirect to the next page.
  161. *
  162. * @param {number|KeyboardEvent} offset - How many items to jump for focus.
  163. */
  164. function goToNextPage(offset) {
  165. if (offset instanceof KeyboardEvent) offset = 1;
  166. if (isListView()) {
  167. goToListItem(offset);
  168. } else {
  169. goToPage("next");
  170. }
  171. }
  172. /**
  173. * Navigate to the individual feed or feeds page.
  174. *
  175. * If the current view is an entry view, it will redirect to the feed link of the entry.
  176. * If the current view is a list view, it will redirect to the feeds page.
  177. */
  178. function goToFeedOrFeedsPage() {
  179. if (isEntryView()) {
  180. goToFeedPage();
  181. } else {
  182. goToPage("feeds");
  183. }
  184. }
  185. /**
  186. * Navigate to the feed page of the current entry.
  187. *
  188. * If the current view is an entry view, it will redirect to the feed link of the entry.
  189. * If the current view is a list view, it will redirect to the feed link of the currently selected item.
  190. * If no feed link is available, it will do nothing.
  191. */
  192. function goToFeedPage() {
  193. if (isEntryView()) {
  194. const feedAnchor = document.querySelector("span.entry-website a");
  195. if (feedAnchor !== null) {
  196. window.location.href = feedAnchor.href;
  197. }
  198. } else {
  199. const currentItemFeed = document.querySelector(".current-item :is(a, button)[data-feed-link]");
  200. if (currentItemFeed !== null) {
  201. window.location.href = currentItemFeed.getAttribute("href");
  202. }
  203. }
  204. }
  205. /**
  206. * Navigate to the add subscription page.
  207. *
  208. * @returns {void}
  209. */
  210. function goToAddSubscriptionPage() {
  211. window.location.href = document.body.dataset.addSubscriptionUrl;
  212. }
  213. /**
  214. * Navigate to the next or previous item in the list.
  215. *
  216. * If the offset is TOP, it will jump to the first item in the list.
  217. * If the offset is BOTTOM, it will jump to the last item in the list.
  218. * If the offset is a number, it will jump that many items in the list.
  219. * If the current view is an entry view, it will redirect to the next or previous page.
  220. *
  221. * @param {number} offset - How many items to jump for focus.
  222. * @return {void}
  223. */
  224. function goToListItem(offset) {
  225. const items = getVisibleEntries();
  226. if (items.length === 0) {
  227. return;
  228. }
  229. if (document.querySelector(".current-item") === null) {
  230. items[0].classList.add("current-item");
  231. items[0].focus();
  232. return;
  233. }
  234. for (let i = 0; i < items.length; i++) {
  235. if (items[i].classList.contains("current-item")) {
  236. items[i].classList.remove("current-item");
  237. // By default adjust selection by offset
  238. let itemOffset = (i + offset + items.length) % items.length;
  239. // Allow jumping to top or bottom
  240. if (offset === TOP) {
  241. itemOffset = 0;
  242. } else if (offset === BOTTOM) {
  243. itemOffset = items.length - 1;
  244. }
  245. const item = items[itemOffset];
  246. item.classList.add("current-item");
  247. scrollPageTo(item);
  248. item.focus();
  249. break;
  250. }
  251. }
  252. }
  253. /**
  254. * Handle the share action for the entry.
  255. *
  256. * If the share status is "shared", it will trigger the Web Share API.
  257. * If the share status is "share", it will send an Ajax request to fetch the share URL and then trigger the Web Share API.
  258. * If the Web Share API is not supported, it will redirect to the entry URL.
  259. */
  260. async function handleShare() {
  261. const link = document.querySelector(':is(a, button)[data-share-status]');
  262. const title = document.querySelector(".entry-header > h1 > a");
  263. if (link.dataset.shareStatus === "shared") {
  264. await triggerWebShare(title, link.href);
  265. }
  266. else if (link.dataset.shareStatus === "share") {
  267. const request = new RequestBuilder(link.href);
  268. request.withCallback((r) => {
  269. // Ensure title is not null before passing to triggerWebShare
  270. triggerWebShare(title, r.url);
  271. });
  272. request.withHttpMethod("GET");
  273. request.execute();
  274. }
  275. }
  276. /**
  277. * Trigger the Web Share API to share the entry.
  278. *
  279. * If the Web Share API is not supported, it will redirect to the entry URL.
  280. *
  281. * @param {Element} title - The title element of the entry.
  282. * @param {string} url - The URL of the entry to share.
  283. */
  284. async function triggerWebShare(title, url) {
  285. if (!navigator.canShare) {
  286. console.error("Your browser doesn't support the Web Share API.");
  287. window.location = url;
  288. return;
  289. }
  290. try {
  291. await navigator.share({
  292. title: title ? title.textContent : url,
  293. url: url
  294. });
  295. } catch (err) {
  296. console.error(err);
  297. }
  298. window.location.reload();
  299. }
  300. // make logo element as button on mobile layout
  301. function checkMenuToggleModeByLayout() {
  302. const logoElement = document.querySelector(".logo");
  303. if (!logoElement) return;
  304. const homePageLinkElement = document.querySelector(".logo > a");
  305. if (document.documentElement.clientWidth < 620) {
  306. const navMenuElement = document.getElementById("header-menu");
  307. const navMenuElementIsExpanded = navMenuElement.classList.contains("js-menu-show");
  308. const logoToggleButtonLabel = logoElement.getAttribute("data-toggle-button-label");
  309. logoElement.setAttribute("role", "button");
  310. logoElement.setAttribute("tabindex", "0");
  311. logoElement.setAttribute("aria-label", logoToggleButtonLabel);
  312. logoElement.setAttribute("aria-expanded", navMenuElementIsExpanded?"true":"false");
  313. homePageLinkElement.setAttribute("tabindex", "-1");
  314. } else {
  315. logoElement.removeAttribute("role");
  316. logoElement.removeAttribute("tabindex");
  317. logoElement.removeAttribute("aria-expanded");
  318. logoElement.removeAttribute("aria-label");
  319. homePageLinkElement.removeAttribute("tabindex");
  320. }
  321. }
  322. function fixVoiceOverDetailsSummaryBug() {
  323. document.querySelectorAll("details").forEach((details) => {
  324. const summaryElement = details.querySelector("summary");
  325. summaryElement.setAttribute("role", "button");
  326. summaryElement.setAttribute("aria-expanded", details.open? "true": "false");
  327. details.addEventListener("toggle", () => {
  328. summaryElement.setAttribute("aria-expanded", details.open? "true": "false");
  329. });
  330. });
  331. }
  332. // Show and hide the main menu on mobile devices.
  333. function toggleMainMenu(event) {
  334. if (event.type === "keydown" && !(event.key === "Enter" || event.key === " ")) {
  335. return;
  336. }
  337. if (event.currentTarget.getAttribute("role")) {
  338. event.preventDefault();
  339. }
  340. const menu = document.querySelector(".header nav ul");
  341. const menuToggleButton = document.querySelector(".logo");
  342. if (menu.classList.contains("js-menu-show")) {
  343. menuToggleButton.setAttribute("aria-expanded", "false");
  344. } else {
  345. menuToggleButton.setAttribute("aria-expanded", "true");
  346. }
  347. menu.classList.toggle("js-menu-show");
  348. }
  349. // Handle click events for the main menu (<li> and <a>).
  350. function onClickMainMenuListItem(event) {
  351. const element = event.target;
  352. if (element.tagName === "A") {
  353. window.location.href = element.getAttribute("href");
  354. } else {
  355. const linkElement = element.querySelector("a") || element.closest("a");
  356. window.location.href = linkElement.getAttribute("href");
  357. }
  358. }
  359. /**
  360. * This function changes the button label to the loading state and disables the button.
  361. *
  362. * @returns {void}
  363. */
  364. function disableSubmitButtonsOnFormSubmit() {
  365. document.querySelectorAll("form").forEach((element) => {
  366. element.onsubmit = () => {
  367. const buttons = element.querySelectorAll("button[type=submit]");
  368. buttons.forEach((button) => {
  369. if (button.dataset.labelLoading) {
  370. button.textContent = button.dataset.labelLoading;
  371. }
  372. button.disabled = true;
  373. });
  374. };
  375. });
  376. }
  377. // Show modal dialog with the list of keyboard shortcuts.
  378. function showKeyboardShortcuts() {
  379. const template = document.getElementById("keyboard-shortcuts");
  380. ModalHandler.open(template.content, "dialog-title");
  381. }
  382. // Mark as read visible items of the current page.
  383. function markPageAsRead() {
  384. const items = getVisibleEntries();
  385. const entryIDs = [];
  386. items.forEach((element) => {
  387. element.classList.add("item-status-read");
  388. entryIDs.push(parseInt(element.dataset.id, 10));
  389. });
  390. if (entryIDs.length > 0) {
  391. updateEntriesStatus(entryIDs, "read", () => {
  392. // Make sure the Ajax request reach the server before we reload the page.
  393. const element = document.querySelector(":is(a, button)[data-action=markPageAsRead]");
  394. let showOnlyUnread = false;
  395. if (element) {
  396. showOnlyUnread = element.dataset.showOnlyUnread || false;
  397. }
  398. if (showOnlyUnread) {
  399. window.location.href = window.location.href;
  400. } else {
  401. goToPage("next", true);
  402. }
  403. });
  404. }
  405. }
  406. /**
  407. * Handle entry status changes from the list view and entry view.
  408. * Focus the next or the previous entry if it exists.
  409. *
  410. * @param {string} navigationDirection Navigation direction: "previous" or "next".
  411. * @param {Element} element Element that triggered the action.
  412. * @param {boolean} setToRead If true, set the entry to read instead of toggling the status.
  413. * @returns {void}
  414. */
  415. function handleEntryStatus(navigationDirection, element, setToRead) {
  416. const toasting = !element;
  417. const currentEntry = findEntry(element);
  418. if (currentEntry) {
  419. if (!setToRead || currentEntry.querySelector(":is(a, button)[data-toggle-status]").dataset.value === "unread") {
  420. toggleEntryStatus(currentEntry, toasting);
  421. }
  422. if (isListView() && currentEntry.classList.contains('current-item')) {
  423. switch (navigationDirection) {
  424. case "previous":
  425. goToListItem(-1);
  426. break;
  427. case "next":
  428. goToListItem(1);
  429. break;
  430. }
  431. }
  432. }
  433. }
  434. // Add an icon-label span element.
  435. function appendIconLabel(element, labelTextContent) {
  436. const span = document.createElement('span');
  437. span.classList.add('icon-label');
  438. span.textContent = labelTextContent;
  439. element.appendChild(span);
  440. }
  441. // Change the entry status to the opposite value.
  442. function toggleEntryStatus(element, toasting) {
  443. const entryID = parseInt(element.dataset.id, 10);
  444. const link = element.querySelector(":is(a, button)[data-toggle-status]");
  445. if (!link) {
  446. return;
  447. }
  448. const currentStatus = link.dataset.value;
  449. const newStatus = currentStatus === "read" ? "unread" : "read";
  450. link.querySelector("span").textContent = link.dataset.labelLoading;
  451. updateEntriesStatus([entryID], newStatus, () => {
  452. let iconElement, label;
  453. if (currentStatus === "read") {
  454. iconElement = document.querySelector("template#icon-read");
  455. label = link.dataset.labelRead;
  456. if (toasting) {
  457. showToast(link.dataset.toastUnread, iconElement);
  458. }
  459. } else {
  460. iconElement = document.querySelector("template#icon-unread");
  461. label = link.dataset.labelUnread;
  462. if (toasting) {
  463. showToast(link.dataset.toastRead, iconElement);
  464. }
  465. }
  466. link.replaceChildren(iconElement.content.cloneNode(true));
  467. appendIconLabel(link, label);
  468. link.dataset.value = newStatus;
  469. if (element.classList.contains("item-status-" + currentStatus)) {
  470. element.classList.remove("item-status-" + currentStatus);
  471. element.classList.add("item-status-" + newStatus);
  472. }
  473. if (isListView() && getVisibleEntries().length === 0) {
  474. window.location.reload();
  475. }
  476. });
  477. }
  478. // Mark a single entry as read.
  479. function markEntryAsRead(element) {
  480. if (element.classList.contains("item-status-unread")) {
  481. element.classList.remove("item-status-unread");
  482. element.classList.add("item-status-read");
  483. const entryID = parseInt(element.dataset.id, 10);
  484. updateEntriesStatus([entryID], "read");
  485. }
  486. }
  487. // Send the Ajax request to refresh all feeds in the background
  488. function handleRefreshAllFeeds() {
  489. const url = document.body.dataset.refreshAllFeedsUrl;
  490. if (url) {
  491. window.location.href = url;
  492. }
  493. }
  494. // Send the Ajax request to change entries statuses.
  495. function updateEntriesStatus(entryIDs, status, callback) {
  496. const url = document.body.dataset.entriesStatusUrl;
  497. const request = new RequestBuilder(url);
  498. request.withBody({ entry_ids: entryIDs, status: status });
  499. request.withCallback((resp) => {
  500. resp.json().then(count => {
  501. if (callback) {
  502. callback(resp);
  503. }
  504. if (status === "read") {
  505. decrementUnreadCounter(count);
  506. } else {
  507. incrementUnreadCounter(count);
  508. }
  509. });
  510. });
  511. request.execute();
  512. }
  513. // Handle save entry from list view and entry view.
  514. function handleSaveEntry(element) {
  515. const toasting = !element;
  516. const currentEntry = findEntry(element);
  517. if (currentEntry) {
  518. saveEntry(currentEntry.querySelector(":is(a, button)[data-save-entry]"), toasting);
  519. }
  520. }
  521. // Send the Ajax request to save an entry.
  522. function saveEntry(element, toasting) {
  523. if (!element || element.dataset.completed) {
  524. return;
  525. }
  526. element.textContent = "";
  527. appendIconLabel(element, element.dataset.labelLoading);
  528. const request = new RequestBuilder(element.dataset.saveUrl);
  529. request.withCallback(() => {
  530. element.textContent = "";
  531. appendIconLabel(element, element.dataset.labelDone);
  532. element.dataset.completed = "true";
  533. if (toasting) {
  534. const iconElement = document.querySelector("template#icon-save");
  535. showToast(element.dataset.toastDone, iconElement);
  536. }
  537. });
  538. request.execute();
  539. }
  540. // Handle bookmark from the list view and entry view.
  541. function handleBookmark(element) {
  542. const toasting = !element;
  543. const currentEntry = findEntry(element);
  544. if (currentEntry) {
  545. toggleBookmark(currentEntry, toasting);
  546. }
  547. }
  548. // Send the Ajax request and change the icon when bookmarking an entry.
  549. function toggleBookmark(parentElement, toasting) {
  550. const buttonElement = parentElement.querySelector(":is(a, button)[data-toggle-bookmark]");
  551. if (!buttonElement) {
  552. return;
  553. }
  554. buttonElement.textContent = "";
  555. appendIconLabel(buttonElement, buttonElement.dataset.labelLoading);
  556. const request = new RequestBuilder(buttonElement.dataset.bookmarkUrl);
  557. request.withCallback(() => {
  558. const currentStarStatus = buttonElement.dataset.value;
  559. const newStarStatus = currentStarStatus === "star" ? "unstar" : "star";
  560. let iconElement, label;
  561. if (currentStarStatus === "star") {
  562. iconElement = document.querySelector("template#icon-star");
  563. label = buttonElement.dataset.labelStar;
  564. if (toasting) {
  565. showToast(buttonElement.dataset.toastUnstar, iconElement);
  566. }
  567. } else {
  568. iconElement = document.querySelector("template#icon-unstar");
  569. label = buttonElement.dataset.labelUnstar;
  570. if (toasting) {
  571. showToast(buttonElement.dataset.toastStar, iconElement);
  572. }
  573. }
  574. buttonElement.replaceChildren(iconElement.content.cloneNode(true));
  575. appendIconLabel(buttonElement, label);
  576. buttonElement.dataset.value = newStarStatus;
  577. });
  578. request.execute();
  579. }
  580. // Send the Ajax request to download the original web page.
  581. function handleFetchOriginalContent() {
  582. if (isListView()) {
  583. return;
  584. }
  585. const buttonElement = document.querySelector(":is(a, button)[data-fetch-content-entry]");
  586. if (!buttonElement) {
  587. return;
  588. }
  589. const previousElement = buttonElement.cloneNode(true);
  590. buttonElement.textContent = "";
  591. appendIconLabel(buttonElement, buttonElement.dataset.labelLoading);
  592. const request = new RequestBuilder(buttonElement.dataset.fetchContentUrl);
  593. request.withCallback((response) => {
  594. buttonElement.textContent = '';
  595. buttonElement.appendChild(previousElement);
  596. response.json().then((data) => {
  597. if (data.hasOwnProperty("content") && data.hasOwnProperty("reading_time")) {
  598. document.querySelector(".entry-content").innerHTML = ttpolicy.createHTML(data.content);
  599. const entryReadingtimeElement = document.querySelector(".entry-reading-time");
  600. if (entryReadingtimeElement) {
  601. entryReadingtimeElement.textContent = data.reading_time;
  602. }
  603. }
  604. });
  605. });
  606. request.execute();
  607. }
  608. function openOriginalLink(openLinkInCurrentTab) {
  609. const entryLink = document.querySelector(".entry h1 a");
  610. if (entryLink !== null) {
  611. if (openLinkInCurrentTab) {
  612. window.location.href = entryLink.getAttribute("href");
  613. } else {
  614. openNewTab(entryLink.getAttribute("href"));
  615. }
  616. return;
  617. }
  618. const currentItemOriginalLink = document.querySelector(".current-item :is(a, button)[data-original-link]");
  619. if (currentItemOriginalLink !== null) {
  620. openNewTab(currentItemOriginalLink.getAttribute("href"));
  621. const currentItem = document.querySelector(".current-item");
  622. // If we are not on the list of starred items, move to the next item
  623. if (document.location.href !== document.querySelector(':is(a, button)[data-page=starred]').href) {
  624. goToListItem(1);
  625. }
  626. markEntryAsRead(currentItem);
  627. }
  628. }
  629. function openCommentLink(openLinkInCurrentTab) {
  630. if (!isListView()) {
  631. const entryLink = document.querySelector(":is(a, button)[data-comments-link]");
  632. if (entryLink !== null) {
  633. if (openLinkInCurrentTab) {
  634. window.location.href = entryLink.getAttribute("href");
  635. } else {
  636. openNewTab(entryLink.getAttribute("href"));
  637. }
  638. }
  639. } else {
  640. const currentItemCommentsLink = document.querySelector(".current-item :is(a, button)[data-comments-link]");
  641. if (currentItemCommentsLink !== null) {
  642. openNewTab(currentItemCommentsLink.getAttribute("href"));
  643. }
  644. }
  645. }
  646. function openSelectedItem() {
  647. const currentItemLink = document.querySelector(".current-item .item-title a");
  648. if (currentItemLink !== null) {
  649. window.location.href = currentItemLink.getAttribute("href");
  650. }
  651. }
  652. function unsubscribeFromFeed() {
  653. const unsubscribeLinks = document.querySelectorAll("[data-action=remove-feed]");
  654. if (unsubscribeLinks.length === 1) {
  655. const unsubscribeLink = unsubscribeLinks[0];
  656. const request = new RequestBuilder(unsubscribeLink.dataset.url);
  657. request.withCallback(() => {
  658. if (unsubscribeLink.dataset.redirectUrl) {
  659. window.location.href = unsubscribeLink.dataset.redirectUrl;
  660. } else {
  661. window.location.reload();
  662. }
  663. });
  664. request.execute();
  665. }
  666. }
  667. function scrollToCurrentItem() {
  668. const currentItem = document.querySelector(".current-item");
  669. if (currentItem !== null) {
  670. scrollPageTo(currentItem, true);
  671. }
  672. }
  673. function decrementUnreadCounter(n) {
  674. updateUnreadCounterValue((current) => {
  675. return current - n;
  676. });
  677. }
  678. function incrementUnreadCounter(n) {
  679. updateUnreadCounterValue((current) => {
  680. return current + n;
  681. });
  682. }
  683. function updateUnreadCounterValue(callback) {
  684. document.querySelectorAll("span.unread-counter").forEach((element) => {
  685. const oldValue = parseInt(element.textContent, 10);
  686. element.textContent = callback(oldValue);
  687. });
  688. if (window.location.href.endsWith('/unread')) {
  689. const oldValue = parseInt(document.title.split('(')[1], 10);
  690. const newValue = callback(oldValue);
  691. document.title = document.title.replace(
  692. /(.*?)\(\d+\)(.*?)/,
  693. function (match, prefix, suffix, offset, string) {
  694. return prefix + '(' + newValue + ')' + suffix;
  695. }
  696. );
  697. }
  698. }
  699. function handleConfirmationMessage(linkElement, callback) {
  700. if (linkElement.tagName !== 'A' && linkElement.tagName !== "BUTTON") {
  701. linkElement = linkElement.parentNode;
  702. }
  703. linkElement.style.display = "none";
  704. const containerElement = linkElement.parentNode;
  705. const questionElement = document.createElement("span");
  706. function createLoadingElement() {
  707. const loadingElement = document.createElement("span");
  708. loadingElement.className = "loading";
  709. loadingElement.appendChild(document.createTextNode(linkElement.dataset.labelLoading));
  710. questionElement.remove();
  711. containerElement.appendChild(loadingElement);
  712. }
  713. const yesElement = document.createElement("button");
  714. yesElement.appendChild(document.createTextNode(linkElement.dataset.labelYes));
  715. yesElement.onclick = (event) => {
  716. event.preventDefault();
  717. createLoadingElement();
  718. callback(linkElement.dataset.url, linkElement.dataset.redirectUrl);
  719. };
  720. const noElement = document.createElement("button");
  721. noElement.appendChild(document.createTextNode(linkElement.dataset.labelNo));
  722. noElement.onclick = (event) => {
  723. event.preventDefault();
  724. const noActionUrl = linkElement.dataset.noActionUrl;
  725. if (noActionUrl) {
  726. createLoadingElement();
  727. callback(noActionUrl, linkElement.dataset.redirectUrl);
  728. } else {
  729. linkElement.style.display = "inline";
  730. questionElement.remove();
  731. }
  732. };
  733. questionElement.className = "confirm";
  734. questionElement.appendChild(document.createTextNode(linkElement.dataset.labelQuestion + " "));
  735. questionElement.appendChild(yesElement);
  736. questionElement.appendChild(document.createTextNode(", "));
  737. questionElement.appendChild(noElement);
  738. containerElement.appendChild(questionElement);
  739. }
  740. function showToast(label, iconElement) {
  741. if (!label || !iconElement) {
  742. return;
  743. }
  744. const toastMsgElement = document.getElementById("toast-msg");
  745. toastMsgElement.replaceChildren(iconElement.content.cloneNode(true));
  746. appendIconLabel(toastMsgElement, label);
  747. const toastElementWrapper = document.getElementById("toast-wrapper");
  748. toastElementWrapper.classList.remove('toast-animate');
  749. setTimeout(() => {
  750. toastElementWrapper.classList.add('toast-animate');
  751. }, 100);
  752. }
  753. /**
  754. * save player position to allow to resume playback later
  755. * @param {Element} playerElement
  756. */
  757. function handlePlayerProgressionSaveAndMarkAsReadOnCompletion(playerElement) {
  758. if (!isPlayerPlaying(playerElement)) {
  759. return; //If the player is not playing, we do not want to save the progression and mark as read on completion
  760. }
  761. const currentPositionInSeconds = Math.floor(playerElement.currentTime); // we do not need a precise value
  762. const lastKnownPositionInSeconds = parseInt(playerElement.dataset.lastPosition, 10);
  763. const markAsReadOnCompletion = parseFloat(playerElement.dataset.markReadOnCompletion); //completion percentage to mark as read
  764. const recordInterval = 10;
  765. // we limit the number of update to only one by interval. Otherwise, we would have multiple update per seconds
  766. if (currentPositionInSeconds >= (lastKnownPositionInSeconds + recordInterval) ||
  767. currentPositionInSeconds <= (lastKnownPositionInSeconds - recordInterval)
  768. ) {
  769. playerElement.dataset.lastPosition = currentPositionInSeconds.toString();
  770. const request = new RequestBuilder(playerElement.dataset.saveUrl);
  771. request.withBody({ progression: currentPositionInSeconds });
  772. request.execute();
  773. // Handle the mark as read on completion
  774. if (markAsReadOnCompletion >= 0 && playerElement.duration > 0) {
  775. const completion = currentPositionInSeconds / playerElement.duration;
  776. if (completion >= markAsReadOnCompletion) {
  777. handleEntryStatus("none", document.querySelector(":is(a, button)[data-toggle-status]"), true);
  778. }
  779. }
  780. }
  781. }
  782. /**
  783. * Check if the player is actually playing a media
  784. * @param element the player element itself
  785. * @returns {boolean}
  786. */
  787. function isPlayerPlaying(element) {
  788. return element &&
  789. element.currentTime > 0 &&
  790. !element.paused &&
  791. !element.ended &&
  792. element.readyState > 2; //https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/readyState
  793. }
  794. /**
  795. * Handle all clicks on media player controls button on enclosures.
  796. * Will change the current speed and position of the player accordingly.
  797. * Will not save anything, all is done client-side, however, changing the position
  798. * will trigger the handlePlayerProgressionSave and save the new position backends side.
  799. * @param {Element} button
  800. */
  801. function handleMediaControl(button) {
  802. const action = button.dataset.enclosureAction;
  803. const value = parseFloat(button.dataset.actionValue);
  804. const targetEnclosureId = button.dataset.enclosureId;
  805. const enclosures = document.querySelectorAll(`audio[data-enclosure-id="${targetEnclosureId}"],video[data-enclosure-id="${targetEnclosureId}"]`);
  806. const speedIndicator = document.querySelectorAll(`span.speed-indicator[data-enclosure-id="${targetEnclosureId}"]`);
  807. enclosures.forEach((enclosure) => {
  808. switch (action) {
  809. case "seek":
  810. enclosure.currentTime = Math.max(enclosure.currentTime + value, 0);
  811. break;
  812. case "speed":
  813. // I set a floor speed of 0.25 to avoid too slow speed where it gives the impression it stopped.
  814. // 0.25 was chosen because it will allow to get back to 1x in two "faster" click, and lower value with same property would be 0.
  815. enclosure.playbackRate = Math.max(0.25, enclosure.playbackRate + value);
  816. speedIndicator.forEach((speedI) => {
  817. // 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.
  818. // The trick only work on rate less than 10, but it feels an acceptable tread of considering the feature
  819. speedI.innerText = `${enclosure.playbackRate.toFixed(2)}x`;
  820. });
  821. break;
  822. case "speed-reset":
  823. enclosure.playbackRate = value ;
  824. speedIndicator.forEach((speedI) => {
  825. // 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.
  826. // The trick only work on rate less than 10, but it feels an acceptable tread of considering the feature
  827. speedI.innerText = `${enclosure.playbackRate.toFixed(2)}x`;
  828. });
  829. break;
  830. }
  831. });
  832. }