app.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. // OnClick attaches a listener to the elements that match the selector.
  2. function onClick(selector, callback, noPreventDefault) {
  3. let elements = document.querySelectorAll(selector);
  4. elements.forEach((element) => {
  5. element.onclick = (event) => {
  6. if (!noPreventDefault) {
  7. event.preventDefault();
  8. }
  9. callback(event);
  10. };
  11. });
  12. }
  13. function onAuxClick(selector, callback, noPreventDefault) {
  14. let elements = document.querySelectorAll(selector);
  15. elements.forEach((element) => {
  16. element.onauxclick = (event) => {
  17. if (!noPreventDefault) {
  18. event.preventDefault();
  19. }
  20. callback(event);
  21. };
  22. });
  23. }
  24. // Show and hide the main menu on mobile devices.
  25. function toggleMainMenu() {
  26. let menu = document.querySelector(".header nav ul");
  27. let menuToggleButton = document.querySelector(".header button[aria-controls='header-menu']");
  28. if (menu.classList.contains("js-menu-show")) {
  29. menu.classList.remove("js-menu-show")
  30. menuToggleButton.setAttribute("aria-expanded", false)
  31. } else {
  32. menu.classList.add("js-menu-show")
  33. menuToggleButton.setAttribute("aria-expanded", true)
  34. }
  35. }
  36. // Handle click events for the main menu (<li> and <a>).
  37. function onClickMainMenuListItem(event) {
  38. let element = event.target;
  39. if (element.tagName === "A") {
  40. window.location.href = element.getAttribute("href");
  41. } else {
  42. window.location.href = element.querySelector("a").getAttribute("href");
  43. }
  44. }
  45. // Change the button label when the page is loading.
  46. function handleSubmitButtons() {
  47. let elements = document.querySelectorAll("form");
  48. elements.forEach((element) => {
  49. element.onsubmit = () => {
  50. let button = element.querySelector("button");
  51. if (button) {
  52. button.innerHTML = button.dataset.labelLoading;
  53. button.disabled = true;
  54. }
  55. };
  56. });
  57. }
  58. // Set cursor focus to the search input.
  59. function setFocusToSearchInput(event) {
  60. event.preventDefault();
  61. event.stopPropagation();
  62. const toggleSearchButton = document.querySelector(".search details")
  63. if (!toggleSearchButton.getAttribute("open")) {
  64. toggleSearchButton.setAttribute("open", "")
  65. const searchInputElement = document.getElementById("search-input");
  66. searchInputElement.focus();
  67. searchInputElement.value = "";
  68. }
  69. }
  70. // Show modal dialog with the list of keyboard shortcuts.
  71. function showKeyboardShortcuts() {
  72. let template = document.getElementById("keyboard-shortcuts");
  73. if (template !== null) {
  74. ModalHandler.open(template.content, "dialog-title");
  75. }
  76. }
  77. // Mark as read visible items of the current page.
  78. function markPageAsRead() {
  79. let items = DomHelper.getVisibleElements(".items .item");
  80. let entryIDs = [];
  81. items.forEach((element) => {
  82. element.classList.add("item-status-read");
  83. entryIDs.push(parseInt(element.dataset.id, 10));
  84. });
  85. if (entryIDs.length > 0) {
  86. updateEntriesStatus(entryIDs, "read", () => {
  87. // Make sure the Ajax request reach the server before we reload the page.
  88. let element = document.querySelector("a[data-action=markPageAsRead]");
  89. let showOnlyUnread = false;
  90. if (element) {
  91. showOnlyUnread = element.dataset.showOnlyUnread || false;
  92. }
  93. if (showOnlyUnread) {
  94. window.location.href = window.location.href;
  95. } else {
  96. goToPage("next", true);
  97. }
  98. });
  99. }
  100. }
  101. /**
  102. * Handle entry status changes from the list view and entry view.
  103. * Focus the next or the previous entry if it exists.
  104. * @param {string} item Item to focus: "previous" or "next".
  105. * @param {Element} element
  106. * @param {boolean} setToRead
  107. */
  108. function handleEntryStatus(item, element, setToRead) {
  109. let toasting = !element;
  110. let currentEntry = findEntry(element);
  111. if (currentEntry) {
  112. if (!setToRead || currentEntry.querySelector("a[data-toggle-status]").dataset.value == "unread") {
  113. toggleEntryStatus(currentEntry, toasting);
  114. }
  115. if (isListView() && currentEntry.classList.contains('current-item')) {
  116. switch (item) {
  117. case "previous":
  118. goToListItem(-1);
  119. break;
  120. case "next":
  121. goToListItem(1);
  122. break;
  123. }
  124. }
  125. }
  126. }
  127. // Change the entry status to the opposite value.
  128. function toggleEntryStatus(element, toasting) {
  129. let entryID = parseInt(element.dataset.id, 10);
  130. let link = element.querySelector("a[data-toggle-status]");
  131. let currentStatus = link.dataset.value;
  132. let newStatus = currentStatus === "read" ? "unread" : "read";
  133. link.querySelector("span").innerHTML = link.dataset.labelLoading;
  134. updateEntriesStatus([entryID], newStatus, () => {
  135. let iconElement, label;
  136. if (currentStatus === "read") {
  137. iconElement = document.querySelector("template#icon-read");
  138. label = link.dataset.labelRead;
  139. if (toasting) {
  140. showToast(link.dataset.toastUnread, iconElement);
  141. }
  142. } else {
  143. iconElement = document.querySelector("template#icon-unread");
  144. label = link.dataset.labelUnread;
  145. if (toasting) {
  146. showToast(link.dataset.toastRead, iconElement);
  147. }
  148. }
  149. link.innerHTML = iconElement.innerHTML + '<span class="icon-label">' + label + '</span>';
  150. link.dataset.value = newStatus;
  151. if (element.classList.contains("item-status-" + currentStatus)) {
  152. element.classList.remove("item-status-" + currentStatus);
  153. element.classList.add("item-status-" + newStatus);
  154. }
  155. });
  156. }
  157. // Mark a single entry as read.
  158. function markEntryAsRead(element) {
  159. if (element.classList.contains("item-status-unread")) {
  160. element.classList.remove("item-status-unread");
  161. element.classList.add("item-status-read");
  162. let entryID = parseInt(element.dataset.id, 10);
  163. updateEntriesStatus([entryID], "read");
  164. }
  165. }
  166. // Send the Ajax request to refresh all feeds in the background
  167. function handleRefreshAllFeeds() {
  168. let url = document.body.dataset.refreshAllFeedsUrl;
  169. if (url) {
  170. window.location.href = url;
  171. }
  172. }
  173. // Send the Ajax request to change entries statuses.
  174. function updateEntriesStatus(entryIDs, status, callback) {
  175. let url = document.body.dataset.entriesStatusUrl;
  176. let request = new RequestBuilder(url);
  177. request.withBody({entry_ids: entryIDs, status: status});
  178. request.withCallback((resp) => {
  179. resp.json().then(count => {
  180. if (callback) {
  181. callback(resp);
  182. }
  183. if (status === "read") {
  184. decrementUnreadCounter(count);
  185. } else {
  186. incrementUnreadCounter(count);
  187. }
  188. });
  189. });
  190. request.execute();
  191. }
  192. // Handle save entry from list view and entry view.
  193. function handleSaveEntry(element) {
  194. let toasting = !element;
  195. let currentEntry = findEntry(element);
  196. if (currentEntry) {
  197. saveEntry(currentEntry.querySelector("a[data-save-entry]"), toasting);
  198. }
  199. }
  200. // Send the Ajax request to save an entry.
  201. function saveEntry(element, toasting) {
  202. if (!element) {
  203. return;
  204. }
  205. if (element.dataset.completed) {
  206. return;
  207. }
  208. let previousInnerHTML = element.innerHTML;
  209. element.innerHTML = '<span class="icon-label">' + element.dataset.labelLoading + '</span>';
  210. let request = new RequestBuilder(element.dataset.saveUrl);
  211. request.withCallback(() => {
  212. element.innerHTML = previousInnerHTML;
  213. element.dataset.completed = true;
  214. if (toasting) {
  215. let iconElement = document.querySelector("template#icon-save");
  216. showToast(element.dataset.toastDone, iconElement);
  217. }
  218. });
  219. request.execute();
  220. }
  221. // Handle bookmark from the list view and entry view.
  222. function handleBookmark(element) {
  223. let toasting = !element;
  224. let currentEntry = findEntry(element);
  225. if (currentEntry) {
  226. toggleBookmark(currentEntry, toasting);
  227. }
  228. }
  229. // Send the Ajax request and change the icon when bookmarking an entry.
  230. function toggleBookmark(parentElement, toasting) {
  231. let element = parentElement.querySelector("a[data-toggle-bookmark]");
  232. if (!element) {
  233. return;
  234. }
  235. element.innerHTML = '<span class="icon-label">' + element.dataset.labelLoading + '</span>';
  236. let request = new RequestBuilder(element.dataset.bookmarkUrl);
  237. request.withCallback(() => {
  238. let currentStarStatus = element.dataset.value;
  239. let newStarStatus = currentStarStatus === "star" ? "unstar" : "star";
  240. let iconElement, label;
  241. if (currentStarStatus === "star") {
  242. iconElement = document.querySelector("template#icon-star");
  243. label = element.dataset.labelStar;
  244. if (toasting) {
  245. showToast(element.dataset.toastUnstar, iconElement);
  246. }
  247. } else {
  248. iconElement = document.querySelector("template#icon-unstar");
  249. label = element.dataset.labelUnstar;
  250. if (toasting) {
  251. showToast(element.dataset.toastStar, iconElement);
  252. }
  253. }
  254. element.innerHTML = iconElement.innerHTML + '<span class="icon-label">' + label + '</span>';
  255. element.dataset.value = newStarStatus;
  256. });
  257. request.execute();
  258. }
  259. // Send the Ajax request to download the original web page.
  260. function handleFetchOriginalContent() {
  261. if (isListView()) {
  262. return;
  263. }
  264. let element = document.querySelector("a[data-fetch-content-entry]");
  265. if (!element) {
  266. return;
  267. }
  268. let previousInnerHTML = element.innerHTML;
  269. element.innerHTML = '<span class="icon-label">' + element.dataset.labelLoading + '</span>';
  270. let request = new RequestBuilder(element.dataset.fetchContentUrl);
  271. request.withCallback((response) => {
  272. element.innerHTML = previousInnerHTML;
  273. response.json().then((data) => {
  274. if (data.hasOwnProperty("content") && data.hasOwnProperty("reading_time")) {
  275. document.querySelector(".entry-content").innerHTML = data.content;
  276. let entryReadingtimeElement = document.querySelector(".entry-reading-time");
  277. if (entryReadingtimeElement) {
  278. entryReadingtimeElement.innerHTML = data.reading_time;
  279. }
  280. }
  281. });
  282. });
  283. request.execute();
  284. }
  285. function openOriginalLink(openLinkInCurrentTab) {
  286. let entryLink = document.querySelector(".entry h1 a");
  287. if (entryLink !== null) {
  288. if (openLinkInCurrentTab) {
  289. window.location.href = entryLink.getAttribute("href");
  290. } else {
  291. DomHelper.openNewTab(entryLink.getAttribute("href"));
  292. }
  293. return;
  294. }
  295. let currentItemOriginalLink = document.querySelector(".current-item a[data-original-link]");
  296. if (currentItemOriginalLink !== null) {
  297. DomHelper.openNewTab(currentItemOriginalLink.getAttribute("href"));
  298. let currentItem = document.querySelector(".current-item");
  299. // If we are not on the list of starred items, move to the next item
  300. if (document.location.href != document.querySelector('a[data-page=starred]').href) {
  301. goToListItem(1);
  302. }
  303. markEntryAsRead(currentItem);
  304. }
  305. }
  306. function openCommentLink(openLinkInCurrentTab) {
  307. if (!isListView()) {
  308. let entryLink = document.querySelector("a[data-comments-link]");
  309. if (entryLink !== null) {
  310. if (openLinkInCurrentTab) {
  311. window.location.href = entryLink.getAttribute("href");
  312. } else {
  313. DomHelper.openNewTab(entryLink.getAttribute("href"));
  314. }
  315. return;
  316. }
  317. } else {
  318. let currentItemCommentsLink = document.querySelector(".current-item a[data-comments-link]");
  319. if (currentItemCommentsLink !== null) {
  320. DomHelper.openNewTab(currentItemCommentsLink.getAttribute("href"));
  321. }
  322. }
  323. }
  324. function openSelectedItem() {
  325. let currentItemLink = document.querySelector(".current-item .item-title a");
  326. if (currentItemLink !== null) {
  327. window.location.href = currentItemLink.getAttribute("href");
  328. }
  329. }
  330. function unsubscribeFromFeed() {
  331. let unsubscribeLinks = document.querySelectorAll("[data-action=remove-feed]");
  332. if (unsubscribeLinks.length === 1) {
  333. let unsubscribeLink = unsubscribeLinks[0];
  334. let request = new RequestBuilder(unsubscribeLink.dataset.url);
  335. request.withCallback(() => {
  336. if (unsubscribeLink.dataset.redirectUrl) {
  337. window.location.href = unsubscribeLink.dataset.redirectUrl;
  338. } else {
  339. window.location.reload();
  340. }
  341. });
  342. request.execute();
  343. }
  344. }
  345. /**
  346. * @param {string} page Page to redirect to.
  347. * @param {boolean} fallbackSelf Refresh actual page if the page is not found.
  348. */
  349. function goToPage(page, fallbackSelf) {
  350. let element = document.querySelector("a[data-page=" + page + "]");
  351. if (element) {
  352. document.location.href = element.href;
  353. } else if (fallbackSelf) {
  354. window.location.reload();
  355. }
  356. }
  357. function goToPrevious() {
  358. if (isListView()) {
  359. goToListItem(-1);
  360. } else {
  361. goToPage("previous");
  362. }
  363. }
  364. function goToNext() {
  365. if (isListView()) {
  366. goToListItem(1);
  367. } else {
  368. goToPage("next");
  369. }
  370. }
  371. function goToFeedOrFeeds() {
  372. if (isEntry()) {
  373. goToFeed();
  374. } else {
  375. goToPage('feeds');
  376. }
  377. }
  378. function goToFeed() {
  379. if (isEntry()) {
  380. let feedAnchor = document.querySelector("span.entry-website a");
  381. if (feedAnchor !== null) {
  382. window.location.href = feedAnchor.href;
  383. }
  384. } else {
  385. let currentItemFeed = document.querySelector(".current-item a[data-feed-link]");
  386. if (currentItemFeed !== null) {
  387. window.location.href = currentItemFeed.getAttribute("href");
  388. }
  389. }
  390. }
  391. /**
  392. * @param {number} offset How many items to jump for focus.
  393. */
  394. function goToListItem(offset) {
  395. let items = DomHelper.getVisibleElements(".items .item");
  396. if (items.length === 0) {
  397. return;
  398. }
  399. if (document.querySelector(".current-item") === null) {
  400. items[0].classList.add("current-item");
  401. items[0].querySelector('.item-header a').focus();
  402. return;
  403. }
  404. for (let i = 0; i < items.length; i++) {
  405. if (items[i].classList.contains("current-item")) {
  406. items[i].classList.remove("current-item");
  407. let item = items[(i + offset + items.length) % items.length];
  408. item.classList.add("current-item");
  409. DomHelper.scrollPageTo(item);
  410. item.querySelector('.item-header a').focus();
  411. break;
  412. }
  413. }
  414. }
  415. function scrollToCurrentItem() {
  416. let currentItem = document.querySelector(".current-item");
  417. if (currentItem !== null) {
  418. DomHelper.scrollPageTo(currentItem, true);
  419. }
  420. }
  421. function decrementUnreadCounter(n) {
  422. updateUnreadCounterValue((current) => {
  423. return current - n;
  424. });
  425. }
  426. function incrementUnreadCounter(n) {
  427. updateUnreadCounterValue((current) => {
  428. return current + n;
  429. });
  430. }
  431. function updateUnreadCounterValue(callback) {
  432. let counterElements = document.querySelectorAll("span.unread-counter");
  433. counterElements.forEach((element) => {
  434. let oldValue = parseInt(element.textContent, 10);
  435. element.innerHTML = callback(oldValue);
  436. });
  437. if (window.location.href.endsWith('/unread')) {
  438. let oldValue = parseInt(document.title.split('(')[1], 10);
  439. let newValue = callback(oldValue);
  440. document.title = document.title.replace(
  441. /(.*?)\(\d+\)(.*?)/,
  442. function (match, prefix, suffix, offset, string) {
  443. return prefix + '(' + newValue + ')' + suffix;
  444. }
  445. );
  446. }
  447. }
  448. function isEntry() {
  449. return document.querySelector("section.entry") !== null;
  450. }
  451. function isListView() {
  452. return document.querySelector(".items") !== null;
  453. }
  454. function findEntry(element) {
  455. if (isListView()) {
  456. if (element) {
  457. return DomHelper.findParent(element, "item");
  458. } else {
  459. return document.querySelector(".current-item");
  460. }
  461. } else {
  462. return document.querySelector(".entry");
  463. }
  464. }
  465. function handleConfirmationMessage(linkElement, callback) {
  466. if (linkElement.tagName != 'A') {
  467. linkElement = linkElement.parentNode;
  468. }
  469. linkElement.style.display = "none";
  470. let containerElement = linkElement.parentNode;
  471. let questionElement = document.createElement("span");
  472. function createLoadingElement() {
  473. let loadingElement = document.createElement("span");
  474. loadingElement.className = "loading";
  475. loadingElement.appendChild(document.createTextNode(linkElement.dataset.labelLoading));
  476. questionElement.remove();
  477. containerElement.appendChild(loadingElement);
  478. }
  479. let yesElement = document.createElement("a");
  480. yesElement.href = "#";
  481. yesElement.appendChild(document.createTextNode(linkElement.dataset.labelYes));
  482. yesElement.onclick = (event) => {
  483. event.preventDefault();
  484. createLoadingElement();
  485. callback(linkElement.dataset.url, linkElement.dataset.redirectUrl);
  486. };
  487. let noElement = document.createElement("a");
  488. noElement.href = "#";
  489. noElement.appendChild(document.createTextNode(linkElement.dataset.labelNo));
  490. noElement.onclick = (event) => {
  491. event.preventDefault();
  492. const noActionUrl = linkElement.dataset.noActionUrl;
  493. if (noActionUrl) {
  494. createLoadingElement();
  495. callback(noActionUrl, linkElement.dataset.redirectUrl);
  496. } else {
  497. linkElement.style.display = "inline";
  498. questionElement.remove();
  499. }
  500. };
  501. questionElement.className = "confirm";
  502. questionElement.appendChild(document.createTextNode(linkElement.dataset.labelQuestion + " "));
  503. questionElement.appendChild(yesElement);
  504. questionElement.appendChild(document.createTextNode(", "));
  505. questionElement.appendChild(noElement);
  506. containerElement.appendChild(questionElement);
  507. }
  508. function showToast(label, iconElement) {
  509. if (!label || !iconElement) {
  510. return;
  511. }
  512. const toastMsgElement = document.getElementById("toast-msg");
  513. if (toastMsgElement) {
  514. toastMsgElement.innerHTML = iconElement.innerHTML + '<span class="icon-label">' + label + '</span>';
  515. const toastElementWrapper = document.getElementById("toast-wrapper");
  516. if (toastElementWrapper) {
  517. toastElementWrapper.classList.remove('toast-animate');
  518. setTimeout(function () {
  519. toastElementWrapper.classList.add('toast-animate');
  520. }, 100);
  521. }
  522. }
  523. }
  524. /** Navigate to the new subscription page. */
  525. function goToAddSubscription() {
  526. window.location.href = document.body.dataset.addSubscriptionUrl;
  527. }
  528. /**
  529. * save player position to allow to resume playback later
  530. * @param {Element} playerElement
  531. */
  532. function handlePlayerProgressionSave(playerElement) {
  533. const currentPositionInSeconds = Math.floor(playerElement.currentTime); // we do not need a precise value
  534. const lastKnownPositionInSeconds = parseInt(playerElement.dataset.lastPosition, 10);
  535. const recordInterval = 10;
  536. // we limit the number of update to only one by interval. Otherwise, we would have multiple update per seconds
  537. if (currentPositionInSeconds >= (lastKnownPositionInSeconds + recordInterval) ||
  538. currentPositionInSeconds <= (lastKnownPositionInSeconds - recordInterval)
  539. ) {
  540. playerElement.dataset.lastPosition = currentPositionInSeconds.toString();
  541. let request = new RequestBuilder(playerElement.dataset.saveUrl);
  542. request.withBody({progression: currentPositionInSeconds});
  543. request.execute();
  544. }
  545. }
  546. /**
  547. * handle new share entires and already shared entries
  548. */
  549. function handleShare() {
  550. let link = document.querySelector('a[data-share-status]');
  551. let title = document.querySelector("body > main > section > header > h1 > a");
  552. if (link.dataset.shareStatus === "shared") {
  553. checkShareAPI(title, link.href);
  554. }
  555. if (link.dataset.shareStatus === "share") {
  556. let request = new RequestBuilder(link.href);
  557. request.withCallback((r) => {
  558. checkShareAPI(title, r.url);
  559. });
  560. request.withHttpMethod("GET");
  561. request.execute();
  562. }
  563. }
  564. /**
  565. * wrapper for Web Share API
  566. */
  567. function checkShareAPI(title, url) {
  568. if (!navigator.canShare) {
  569. console.error("Your browser doesn't support the Web Share API.");
  570. window.location = url;
  571. return;
  572. }
  573. try {
  574. navigator.share({
  575. title: title,
  576. url: url
  577. });
  578. window.location.reload();
  579. } catch (err) {
  580. console.error(err);
  581. window.location.reload();
  582. }
  583. }
  584. function getCsrfToken() {
  585. let element = document.querySelector("body[data-csrf-token]");
  586. if (element !== null) {
  587. return element.dataset.csrfToken;
  588. }
  589. return "";
  590. }