app.js 28 KB

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