app.js 27 KB

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