app.js 28 KB

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