app.js 28 KB

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