app.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  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. }
  349. } else {
  350. const currentItemCommentsLink = document.querySelector(".current-item :is(a, button)[data-comments-link]");
  351. if (currentItemCommentsLink !== null) {
  352. DomHelper.openNewTab(currentItemCommentsLink.getAttribute("href"));
  353. }
  354. }
  355. }
  356. function openSelectedItem() {
  357. const currentItemLink = document.querySelector(".current-item .item-title a");
  358. if (currentItemLink !== null) {
  359. window.location.href = currentItemLink.getAttribute("href");
  360. }
  361. }
  362. function unsubscribeFromFeed() {
  363. const unsubscribeLinks = document.querySelectorAll("[data-action=remove-feed]");
  364. if (unsubscribeLinks.length === 1) {
  365. const unsubscribeLink = unsubscribeLinks[0];
  366. const request = new RequestBuilder(unsubscribeLink.dataset.url);
  367. request.withCallback(() => {
  368. if (unsubscribeLink.dataset.redirectUrl) {
  369. window.location.href = unsubscribeLink.dataset.redirectUrl;
  370. } else {
  371. window.location.reload();
  372. }
  373. });
  374. request.execute();
  375. }
  376. }
  377. /**
  378. * @param {string} page Page to redirect to.
  379. * @param {boolean} fallbackSelf Refresh actual page if the page is not found.
  380. */
  381. function goToPage(page, fallbackSelf) {
  382. const element = document.querySelector(":is(a, button)[data-page=" + page + "]");
  383. if (element) {
  384. document.location.href = element.href;
  385. } else if (fallbackSelf) {
  386. window.location.reload();
  387. }
  388. }
  389. /**
  390. *
  391. * @param {(number|event)} offset - many items to jump for focus.
  392. */
  393. function goToPrevious(offset) {
  394. if (offset instanceof KeyboardEvent) {
  395. offset = -1;
  396. }
  397. if (isListView()) {
  398. goToListItem(offset);
  399. } else {
  400. goToPage("previous");
  401. }
  402. }
  403. /**
  404. *
  405. * @param {(number|event)} offset - How many items to jump for focus.
  406. */
  407. function goToNext(offset) {
  408. if (offset instanceof KeyboardEvent) {
  409. offset = 1;
  410. }
  411. if (isListView()) {
  412. goToListItem(offset);
  413. } else {
  414. goToPage("next");
  415. }
  416. }
  417. function goToFeedOrFeeds() {
  418. if (isEntry()) {
  419. goToFeed();
  420. } else {
  421. goToPage('feeds');
  422. }
  423. }
  424. function goToFeed() {
  425. if (isEntry()) {
  426. const feedAnchor = document.querySelector("span.entry-website a");
  427. if (feedAnchor !== null) {
  428. window.location.href = feedAnchor.href;
  429. }
  430. } else {
  431. const currentItemFeed = document.querySelector(".current-item :is(a, button)[data-feed-link]");
  432. if (currentItemFeed !== null) {
  433. window.location.href = currentItemFeed.getAttribute("href");
  434. }
  435. }
  436. }
  437. // Sentinel values for specific list navigation
  438. const TOP = 9999;
  439. const BOTTOM = -9999;
  440. /**
  441. * @param {number} offset How many items to jump for focus.
  442. */
  443. function goToListItem(offset) {
  444. const items = DomHelper.getVisibleElements(".items .item");
  445. if (items.length === 0) {
  446. return;
  447. }
  448. if (document.querySelector(".current-item") === null) {
  449. items[0].classList.add("current-item");
  450. items[0].focus();
  451. return;
  452. }
  453. for (let i = 0; i < items.length; i++) {
  454. if (items[i].classList.contains("current-item")) {
  455. items[i].classList.remove("current-item");
  456. // By default adjust selection by offset
  457. let itemOffset = (i + offset + items.length) % items.length;
  458. // Allow jumping to top or bottom
  459. if (offset === TOP) {
  460. itemOffset = 0;
  461. } else if (offset === BOTTOM) {
  462. itemOffset = items.length - 1;
  463. }
  464. const item = items[itemOffset];
  465. item.classList.add("current-item");
  466. DomHelper.scrollPageTo(item);
  467. item.focus();
  468. break;
  469. }
  470. }
  471. }
  472. function scrollToCurrentItem() {
  473. const currentItem = document.querySelector(".current-item");
  474. if (currentItem !== null) {
  475. DomHelper.scrollPageTo(currentItem, true);
  476. }
  477. }
  478. function decrementUnreadCounter(n) {
  479. updateUnreadCounterValue((current) => {
  480. return current - n;
  481. });
  482. }
  483. function incrementUnreadCounter(n) {
  484. updateUnreadCounterValue((current) => {
  485. return current + n;
  486. });
  487. }
  488. function updateUnreadCounterValue(callback) {
  489. document.querySelectorAll("span.unread-counter").forEach((element) => {
  490. const oldValue = parseInt(element.textContent, 10);
  491. element.textContent = callback(oldValue);
  492. });
  493. if (window.location.href.endsWith('/unread')) {
  494. const oldValue = parseInt(document.title.split('(')[1], 10);
  495. const newValue = callback(oldValue);
  496. document.title = document.title.replace(
  497. /(.*?)\(\d+\)(.*?)/,
  498. function (match, prefix, suffix, offset, string) {
  499. return prefix + '(' + newValue + ')' + suffix;
  500. }
  501. );
  502. }
  503. }
  504. function isEntry() {
  505. return document.querySelector("section.entry") !== null;
  506. }
  507. function isListView() {
  508. return document.querySelector(".items") !== null;
  509. }
  510. function findEntry(element) {
  511. if (isListView()) {
  512. if (element) {
  513. return element.closest(".item");
  514. }
  515. return document.querySelector(".current-item");
  516. }
  517. return document.querySelector(".entry");
  518. }
  519. function handleConfirmationMessage(linkElement, callback) {
  520. if (linkElement.tagName !== 'A' && linkElement.tagName !== "BUTTON") {
  521. linkElement = linkElement.parentNode;
  522. }
  523. linkElement.style.display = "none";
  524. const containerElement = linkElement.parentNode;
  525. const questionElement = document.createElement("span");
  526. function createLoadingElement() {
  527. const loadingElement = document.createElement("span");
  528. loadingElement.className = "loading";
  529. loadingElement.appendChild(document.createTextNode(linkElement.dataset.labelLoading));
  530. questionElement.remove();
  531. containerElement.appendChild(loadingElement);
  532. }
  533. const yesElement = document.createElement("button");
  534. yesElement.appendChild(document.createTextNode(linkElement.dataset.labelYes));
  535. yesElement.onclick = (event) => {
  536. event.preventDefault();
  537. createLoadingElement();
  538. callback(linkElement.dataset.url, linkElement.dataset.redirectUrl);
  539. };
  540. const noElement = document.createElement("button");
  541. noElement.appendChild(document.createTextNode(linkElement.dataset.labelNo));
  542. noElement.onclick = (event) => {
  543. event.preventDefault();
  544. const noActionUrl = linkElement.dataset.noActionUrl;
  545. if (noActionUrl) {
  546. createLoadingElement();
  547. callback(noActionUrl, linkElement.dataset.redirectUrl);
  548. } else {
  549. linkElement.style.display = "inline";
  550. questionElement.remove();
  551. }
  552. };
  553. questionElement.className = "confirm";
  554. questionElement.appendChild(document.createTextNode(linkElement.dataset.labelQuestion + " "));
  555. questionElement.appendChild(yesElement);
  556. questionElement.appendChild(document.createTextNode(", "));
  557. questionElement.appendChild(noElement);
  558. containerElement.appendChild(questionElement);
  559. }
  560. function showToast(label, iconElement) {
  561. if (!label || !iconElement) {
  562. return;
  563. }
  564. const toastMsgElement = document.getElementById("toast-msg");
  565. if (toastMsgElement) {
  566. toastMsgElement.replaceChildren(iconElement.content.cloneNode(true));
  567. appendIconLabel(toastMsgElement, label);
  568. const toastElementWrapper = document.getElementById("toast-wrapper");
  569. if (toastElementWrapper) {
  570. toastElementWrapper.classList.remove('toast-animate');
  571. setTimeout(() => {
  572. toastElementWrapper.classList.add('toast-animate');
  573. }, 100);
  574. }
  575. }
  576. }
  577. /** Navigate to the new subscription page. */
  578. function goToAddSubscription() {
  579. window.location.href = document.body.dataset.addSubscriptionUrl;
  580. }
  581. /**
  582. * save player position to allow to resume playback later
  583. * @param {Element} playerElement
  584. */
  585. function handlePlayerProgressionSaveAndMarkAsReadOnCompletion(playerElement) {
  586. if (!isPlayerPlaying(playerElement)) {
  587. return; //If the player is not playing, we do not want to save the progression and mark as read on completion
  588. }
  589. const currentPositionInSeconds = Math.floor(playerElement.currentTime); // we do not need a precise value
  590. const lastKnownPositionInSeconds = parseInt(playerElement.dataset.lastPosition, 10);
  591. const markAsReadOnCompletion = parseFloat(playerElement.dataset.markReadOnCompletion); //completion percentage to mark as read
  592. const recordInterval = 10;
  593. // we limit the number of update to only one by interval. Otherwise, we would have multiple update per seconds
  594. if (currentPositionInSeconds >= (lastKnownPositionInSeconds + recordInterval) ||
  595. currentPositionInSeconds <= (lastKnownPositionInSeconds - recordInterval)
  596. ) {
  597. playerElement.dataset.lastPosition = currentPositionInSeconds.toString();
  598. const request = new RequestBuilder(playerElement.dataset.saveUrl);
  599. request.withBody({ progression: currentPositionInSeconds });
  600. request.execute();
  601. // Handle the mark as read on completion
  602. if (markAsReadOnCompletion >= 0 && playerElement.duration > 0) {
  603. const completion = currentPositionInSeconds / playerElement.duration;
  604. if (completion >= markAsReadOnCompletion) {
  605. handleEntryStatus("none", document.querySelector(":is(a, button)[data-toggle-status]"), true);
  606. }
  607. }
  608. }
  609. }
  610. /**
  611. * Check if the player is actually playing a media
  612. * @param element the player element itself
  613. * @returns {boolean}
  614. */
  615. function isPlayerPlaying(element) {
  616. return element &&
  617. element.currentTime > 0 &&
  618. !element.paused &&
  619. !element.ended &&
  620. element.readyState > 2; //https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/readyState
  621. }
  622. /**
  623. * handle new share entires and already shared entries
  624. */
  625. function handleShare() {
  626. const link = document.querySelector(':is(a, button)[data-share-status]');
  627. const title = document.querySelector("body > main > section > header > h1 > a");
  628. if (link.dataset.shareStatus === "shared") {
  629. checkShareAPI(title, link.href);
  630. }
  631. if (link.dataset.shareStatus === "share") {
  632. const request = new RequestBuilder(link.href);
  633. request.withCallback((r) => {
  634. checkShareAPI(title, r.url);
  635. });
  636. request.withHttpMethod("GET");
  637. request.execute();
  638. }
  639. }
  640. /**
  641. * wrapper for Web Share API
  642. */
  643. function checkShareAPI(title, url) {
  644. if (!navigator.canShare) {
  645. console.error("Your browser doesn't support the Web Share API.");
  646. window.location = url;
  647. return;
  648. }
  649. try {
  650. navigator.share({
  651. title: title,
  652. url: url
  653. });
  654. } catch (err) {
  655. console.error(err);
  656. }
  657. window.location.reload();
  658. }
  659. function getCsrfToken() {
  660. const element = document.querySelector("body[data-csrf-token]");
  661. if (element !== null) {
  662. return element.dataset.csrfToken;
  663. }
  664. return "";
  665. }
  666. /**
  667. * Handle all clicks on media player controls button on enclosures.
  668. * Will change the current speed and position of the player accordingly.
  669. * Will not save anything, all is done client-side, however, changing the position
  670. * will trigger the handlePlayerProgressionSave and save the new position backends side.
  671. * @param {Element} button
  672. */
  673. function handleMediaControl(button) {
  674. const action = button.dataset.enclosureAction;
  675. const value = parseFloat(button.dataset.actionValue);
  676. const targetEnclosureId = button.dataset.enclosureId;
  677. const enclosures = document.querySelectorAll(`audio[data-enclosure-id="${targetEnclosureId}"],video[data-enclosure-id="${targetEnclosureId}"]`);
  678. const speedIndicator = document.querySelectorAll(`span.speed-indicator[data-enclosure-id="${targetEnclosureId}"]`);
  679. enclosures.forEach((enclosure) => {
  680. switch (action) {
  681. case "seek":
  682. enclosure.currentTime = Math.max(enclosure.currentTime + value, 0);
  683. break;
  684. case "speed":
  685. // I set a floor speed of 0.25 to avoid too slow speed where it gives the impression it stopped.
  686. // 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.
  687. enclosure.playbackRate = Math.max(0.25, enclosure.playbackRate + value);
  688. speedIndicator.forEach((speedI) => {
  689. // 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.
  690. // The trick only work on rate less than 10, but it feels an acceptable tread of considering the feature
  691. speedI.innerText = `${enclosure.playbackRate.toFixed(2)}x`;
  692. });
  693. break;
  694. case "speed-reset":
  695. enclosure.playbackRate = value ;
  696. speedIndicator.forEach((speedI) => {
  697. // 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.
  698. // The trick only work on rate less than 10, but it feels an acceptable tread of considering the feature
  699. speedI.innerText = `${enclosure.playbackRate.toFixed(2)}x`;
  700. });
  701. break;
  702. }
  703. });
  704. }