main.js 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252
  1. // @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-3.0
  2. 'use strict';
  3. // <Polyfills>
  4. if (!document.scrollingElement) document.scrollingElement = document.documentElement;
  5. if (!NodeList.prototype.forEach) NodeList.prototype.forEach = Array.prototype.forEach;
  6. if (!Element.prototype.matches) {
  7. Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.webkitMatchesSelector;
  8. }
  9. if (!Element.prototype.closest) {
  10. Element.prototype.closest = function (s) {
  11. let el = this;
  12. do {
  13. if (el.matches(s)) return el;
  14. el = el.parentElement;
  15. } while (el);
  16. return null;
  17. };
  18. }
  19. if (!Element.prototype.remove) Element.prototype.remove = function () { if (this.parentNode) this.parentNode.removeChild(this); };
  20. // </Polyfills>
  21. // <Utils>
  22. function xmlHttpRequestJson(req) {
  23. let json = req.response;
  24. if (req.responseType !== 'json') { // IE11
  25. try {
  26. json = JSON.parse(req.responseText);
  27. } catch (ex) {
  28. json = null;
  29. }
  30. }
  31. return json;
  32. }
  33. // </Utils>
  34. // <Global context>
  35. /* eslint-disable no-var */
  36. var context;
  37. var prevTitle;
  38. /* eslint-enable no-var */
  39. (function parseJsonVars() {
  40. const jsonVars = document.getElementById('jsonVars');
  41. const json = JSON.parse(jsonVars.innerHTML);
  42. jsonVars.outerHTML = '';
  43. context = json.context;
  44. context.ajax_loading = false;
  45. context.i18n = json.i18n;
  46. context.shortcuts = json.shortcuts;
  47. context.urls = json.urls;
  48. context.icons = json.icons;
  49. context.icons.read = decodeURIComponent(context.icons.read);
  50. context.icons.unread = decodeURIComponent(context.icons.unread);
  51. context.extensions = json.extensions;
  52. }());
  53. const freshrssGlobalContextLoadedEvent = new Event('freshrss:globalContextLoaded');
  54. document.dispatchEvent(freshrssGlobalContextLoadedEvent);
  55. // </Global context>
  56. function badAjax(reload) {
  57. openNotification(context.i18n.notif_request_failed, 'bad');
  58. if (reload) {
  59. setTimeout(function () { location.reload(); }, 2000);
  60. }
  61. return true;
  62. }
  63. function needsScroll(elem) {
  64. const winBottom = document.scrollingElement.scrollTop + document.scrollingElement.clientHeight;
  65. const elemTop = elem.offsetParent.offsetTop + elem.offsetTop;
  66. const elemBottom = elemTop + elem.offsetHeight;
  67. if (elemTop < document.scrollingElement.scrollTop || elemBottom > winBottom) {
  68. return elemTop - (document.scrollingElement.clientHeight / 2);
  69. }
  70. return 0;
  71. }
  72. function str2int(str) {
  73. if (!str) {
  74. return 0;
  75. }
  76. return parseInt(str.replace(/\D/g, ''), 10) || 0;
  77. }
  78. function numberFormat(nStr) {
  79. if (nStr < 0) {
  80. return 0;
  81. }
  82. // http://www.mredkj.com/javascript/numberFormat.html
  83. const x = String(nStr).split('.');
  84. const x2 = x.length > 1 ? '.' + x[1] : '';
  85. const rgx = /(\d+)(\d{3})/;
  86. let x1 = x[0];
  87. while (rgx.test(x1)) {
  88. x1 = x1.replace(rgx, '$1 $2');
  89. }
  90. return x1 + x2;
  91. }
  92. function incLabel(p, inc, spaceAfter) {
  93. const i = str2int(p) + inc;
  94. return i > 0 ? ((spaceAfter ? '' : ' ') + '(' + numberFormat(i) + ')' + (spaceAfter ? ' ' : '')) : '';
  95. }
  96. function incUnreadsFeed(article, feed_id, nb) {
  97. // Update unread: feed
  98. let elem = document.getElementById(feed_id);
  99. let feed_unreads = elem ? str2int(elem.getAttribute('data-unread')) : 0;
  100. const feed_priority = elem ? str2int(elem.getAttribute('data-priority')) : 0;
  101. if (elem) {
  102. elem.setAttribute('data-unread', feed_unreads + nb);
  103. elem = elem.querySelector('.item-title');
  104. if (elem) {
  105. elem.setAttribute('data-unread', numberFormat(feed_unreads + nb));
  106. }
  107. }
  108. // Update unread: category
  109. elem = document.getElementById(feed_id);
  110. elem = elem ? elem.closest('.category') : null;
  111. if (elem) {
  112. feed_unreads = str2int(elem.getAttribute('data-unread'));
  113. elem.setAttribute('data-unread', feed_unreads + nb);
  114. elem = elem.querySelector('.title');
  115. if (elem) {
  116. elem.setAttribute('data-unread', numberFormat(feed_unreads + nb));
  117. }
  118. }
  119. // Update unread: all
  120. if (feed_priority > 0) {
  121. elem = document.querySelector('#aside_feed .all .title');
  122. if (elem) {
  123. feed_unreads = elem ? str2int(elem.getAttribute('data-unread')) : 0;
  124. elem.setAttribute('data-unread', numberFormat(feed_unreads + nb));
  125. }
  126. }
  127. // Update unread: important
  128. if (feed_priority >= 20) {
  129. elem = document.querySelector('#aside_feed .important .title');
  130. if (elem) {
  131. feed_unreads = elem ? str2int(elem.getAttribute('data-unread')) : 0;
  132. elem.setAttribute('data-unread', numberFormat(feed_unreads + nb));
  133. }
  134. }
  135. // Update unread: favourites
  136. if (article && article.closest('div').classList.contains('favorite')) {
  137. elem = document.querySelector('#aside_feed .favorites .title');
  138. if (elem) {
  139. feed_unreads = elem ? str2int(elem.getAttribute('data-unread')) : 0;
  140. elem.setAttribute('data-unread', numberFormat(feed_unreads + nb));
  141. }
  142. }
  143. // Update unread: title
  144. let isCurrentView = false;
  145. const currentTitle = prevTitle || document.title;
  146. const newTitle = currentTitle.replace(/^((?:\([\s0-9]+\) )?)/, function (m, p1) {
  147. const feed = document.getElementById(feed_id);
  148. if (article || (feed && feed.closest('.active'))) {
  149. isCurrentView = true;
  150. return incLabel(p1, nb, true);
  151. } else if (document.querySelector('.all.active')) {
  152. isCurrentView = feed_priority > 0;
  153. return incLabel(p1, feed_priority > 0 ? nb : 0, true);
  154. } else {
  155. return p1;
  156. }
  157. });
  158. if (prevTitle) {
  159. prevTitle = newTitle;
  160. } else {
  161. document.title = newTitle;
  162. }
  163. return isCurrentView;
  164. }
  165. function incUnreadsTag(tag_id, nb) {
  166. let t = document.getElementById(tag_id);
  167. if (t) {
  168. const unreads = str2int(t.getAttribute('data-unread'));
  169. t.setAttribute('data-unread', unreads + nb);
  170. t.querySelector('.item-title').setAttribute('data-unread', numberFormat(unreads + nb));
  171. }
  172. t = document.querySelector('.category.tags .title');
  173. if (t) {
  174. const unreads = str2int(t.getAttribute('data-unread'));
  175. t.setAttribute('data-unread', numberFormat(unreads + nb));
  176. }
  177. }
  178. function removeArticle(div) {
  179. if (!div || div.classList.contains('not_read') || (context.auto_mark_article && div.classList.contains('active'))) {
  180. return;
  181. }
  182. let scrollTop = box_to_follow.scrollTop;
  183. let dirty = false;
  184. const p = div.previousElementSibling;
  185. const n = div.nextElementSibling;
  186. if (p && p.classList.contains('day') && n && n.classList.contains('day')) {
  187. scrollTop -= p.offsetHeight;
  188. dirty = true;
  189. p.remove();
  190. }
  191. if (div.offsetHeight > 0 && div.offsetParent.offsetTop + div.offsetTop + div.offsetHeight < scrollTop) {
  192. scrollTop -= div.offsetHeight;
  193. dirty = true;
  194. }
  195. div.remove();
  196. if (dirty) {
  197. box_to_follow.scrollTop = scrollTop;
  198. }
  199. }
  200. const pending_entries = {};
  201. let mark_read_queue = [];
  202. async function send_mark_read_queue(queue, asRead, callback) {
  203. if (!queue || queue.length === 0) {
  204. if (callback) {
  205. callback();
  206. }
  207. return;
  208. }
  209. let json;
  210. try {
  211. const resp = await fetch('.?c=entry&a=read' + (asRead ? '' : '&is_read=0'), {
  212. method: 'POST',
  213. headers: {
  214. 'Content-Type': 'application/json; charset=UTF-8'
  215. },
  216. body: JSON.stringify({
  217. ajax: true,
  218. _csrf: context.csrf,
  219. id: queue,
  220. }),
  221. keepalive: true
  222. });
  223. if (!resp.ok) {
  224. for (let i = queue.length - 1; i >= 0; i--) {
  225. const div = document.getElementById('flux_' + queue[i]);
  226. div.querySelectorAll('a.read > .icon').forEach(icon => {
  227. icon.outerHTML = div.classList.contains('not_read') ? context.icons.unread : context.icons.read;
  228. });
  229. delete pending_entries['flux_' + queue[i]];
  230. }
  231. badAjax(resp.status == 403);
  232. return;
  233. }
  234. json = await resp.json();
  235. } catch (e) {
  236. console.error(e.message);
  237. badAjax();
  238. return;
  239. }
  240. for (let i = queue.length - 1; i >= 0; i--) {
  241. const div = document.getElementById('flux_' + queue[i]);
  242. const myIcons = context.icons;
  243. let inc = 0;
  244. if (div.classList.contains('not_read')) {
  245. div.classList.remove('not_read');
  246. div.querySelectorAll('a.read').forEach(function (a) {
  247. a.href = a.href.replace('&is_read=0', '') + '&is_read=1';
  248. });
  249. div.querySelectorAll('a.read > .icon').forEach(function (img) { img.outerHTML = myIcons.read; });
  250. inc--;
  251. if (context.auto_remove_article) {
  252. removeArticle(div);
  253. }
  254. } else {
  255. div.classList.add('not_read');
  256. div.classList.add('keep_unread'); // Split for IE11
  257. div.querySelectorAll('a.read').forEach(function (a) {
  258. a.href = a.href.replace('&is_read=1', '');
  259. });
  260. div.querySelectorAll('a.read > .icon').forEach(function (img) { img.outerHTML = myIcons.unread; });
  261. inc++;
  262. }
  263. const feed_link = div.querySelector('.website > a, a.website');
  264. if (feed_link) {
  265. const feed_url = feed_link.href;
  266. const feed_id = feed_url.substr(feed_url.lastIndexOf('f_'));
  267. incUnreadsFeed(div, feed_id, inc);
  268. }
  269. delete pending_entries['flux_' + queue[i]];
  270. }
  271. faviconNbUnread();
  272. if (json.tags) {
  273. const tagIds = Object.keys(json.tags);
  274. for (let i = tagIds.length - 1; i >= 0; i--) {
  275. const tagId = tagIds[i];
  276. incUnreadsTag(tagId, (asRead ? -1 : 1) * json.tags[tagId].length);
  277. }
  278. }
  279. toggle_bigMarkAsRead_button();
  280. onScroll();
  281. if (callback) {
  282. callback();
  283. }
  284. }
  285. let send_mark_read_queue_timeout = 0;
  286. function send_mark_queue_tick(callback) {
  287. send_mark_read_queue_timeout = 0;
  288. const queue = mark_read_queue.slice(0);
  289. mark_read_queue = [];
  290. send_mark_read_queue(queue, true, callback);
  291. }
  292. const delayedFunction = send_mark_queue_tick;
  293. function delayedClick(a) {
  294. if (a) {
  295. delayedFunction(function () { a.click(); });
  296. }
  297. }
  298. function mark_read(div, only_not_read, asBatch) {
  299. if (!div || !div.id || context.anonymous ||
  300. (only_not_read && !div.classList.contains('not_read'))) {
  301. return false;
  302. }
  303. if (pending_entries[div.id]) {
  304. return false;
  305. }
  306. pending_entries[div.id] = true;
  307. div.querySelectorAll('a.read > .icon').forEach(icon => {
  308. icon.src = context.icons.spinner;
  309. icon.alt = '⏳';
  310. icon.classList.add('spinner');
  311. });
  312. const asRead = div.classList.contains('not_read');
  313. const entryId = div.id.replace(/^flux_/, '');
  314. if (asRead && asBatch) {
  315. mark_read_queue.push(entryId);
  316. if (send_mark_read_queue_timeout == 0) {
  317. send_mark_read_queue_timeout = setTimeout(function () { send_mark_queue_tick(null); }, 1000);
  318. }
  319. } else {
  320. const queue = [entryId];
  321. send_mark_read_queue(queue, asRead);
  322. }
  323. }
  324. function mark_previous_read(div) {
  325. while (div) {
  326. mark_read(div, true, true);
  327. div = div.previousElementSibling;
  328. }
  329. }
  330. function mark_favorite(div) {
  331. if (!div) {
  332. return false;
  333. }
  334. const a = div.querySelector('a.bookmark');
  335. const url = a ? a.href : '';
  336. if (!url) {
  337. return false;
  338. }
  339. if (pending_entries[div.id]) {
  340. return false;
  341. }
  342. pending_entries[div.id] = true;
  343. let originalIcon;
  344. div.querySelectorAll('a.bookmark > .icon').forEach(icon => {
  345. originalIcon = {
  346. src: icon.getAttribute('src'),
  347. alt: icon.getAttribute('alt')
  348. };
  349. icon.src = context.icons.spinner;
  350. icon.alt = '⏳';
  351. icon.classList.add('spinner');
  352. });
  353. const req = new XMLHttpRequest();
  354. req.open('POST', url, true);
  355. req.responseType = 'json';
  356. req.onerror = function (e) {
  357. div.querySelectorAll('a.bookmark > .icon').forEach(icon => {
  358. icon.src = originalIcon.src;
  359. icon.alt = originalIcon.alt;
  360. });
  361. delete pending_entries[div.id];
  362. badAjax(this.status == 403);
  363. };
  364. req.onload = function (e) {
  365. if (this.status != 200) {
  366. return req.onerror(e);
  367. }
  368. const json = xmlHttpRequestJson(this);
  369. if (!json) {
  370. return req.onerror(e);
  371. }
  372. let inc = 0;
  373. if (div.classList.contains('favorite')) {
  374. div.classList.remove('favorite');
  375. inc--;
  376. } else {
  377. div.classList.add('favorite');
  378. inc++;
  379. }
  380. div.querySelectorAll('a.bookmark').forEach(function (a) { a.href = json.url; });
  381. div.querySelectorAll('a.bookmark > .icon').forEach(function (img) { img.outerHTML = json.icon; });
  382. const favourites = document.querySelector('#aside_feed .favorites .title');
  383. if (favourites) {
  384. favourites.textContent = favourites.textContent.replace(/((?: \([\s0-9]+\))?\s*)$/, function (m, p1) {
  385. return incLabel(p1, inc, false);
  386. });
  387. }
  388. if (div.classList.contains('not_read')) {
  389. const elem = document.querySelector('#aside_feed .favorites .title');
  390. const feed_unreads = elem ? str2int(elem.getAttribute('data-unread')) : 0;
  391. if (elem) {
  392. elem.setAttribute('data-unread', numberFormat(feed_unreads + inc));
  393. }
  394. }
  395. delete pending_entries[div.id];
  396. };
  397. req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
  398. req.send(JSON.stringify({
  399. ajax: true,
  400. _csrf: context.csrf,
  401. }));
  402. }
  403. const freshrssOpenArticleEvent = document.createEvent('Event');
  404. freshrssOpenArticleEvent.initEvent('freshrss:openArticle', true, true);
  405. function loadLazyImages(rootElement) {
  406. rootElement.querySelectorAll('img[data-original], iframe[data-original], video[data-original], track[data-original]').forEach(function (el) {
  407. if (el.tagName === 'VIDEO') {
  408. el.poster = el.getAttribute('data-original');
  409. } else {
  410. el.src = el.getAttribute('data-original');
  411. }
  412. el.removeAttribute('data-original');
  413. });
  414. }
  415. function toggleContent(new_active, old_active, skipping) {
  416. // If skipping, move current without activating or marking as read
  417. if (!new_active) {
  418. return;
  419. }
  420. if (context.does_lazyload && !skipping) {
  421. loadLazyImages(new_active);
  422. }
  423. if (old_active !== new_active) {
  424. if (!skipping) {
  425. new_active.classList.add('active');
  426. }
  427. new_active.classList.add('current');
  428. if (old_active) {
  429. old_active.classList.remove('active');
  430. old_active.classList.remove('current'); // Split for IE11
  431. if (context.auto_remove_article) {
  432. removeArticle(old_active);
  433. }
  434. }
  435. } else {
  436. new_active.classList.toggle('active');
  437. }
  438. const relative_move = context.current_view === 'global';
  439. const box_to_move = relative_move ? document.getElementById('panel') : document.scrollingElement;
  440. if (context.sticky_post) { // Stick the article to the top when opened
  441. const prev_article = new_active.previousElementSibling;
  442. const nav_menu = document.querySelector('.nav_menu');
  443. let nav_menu_height = 0;
  444. if (nav_menu && (getComputedStyle(nav_menu).position === 'fixed' || getComputedStyle(nav_menu).position === 'sticky')) {
  445. nav_menu_height = nav_menu.offsetHeight;
  446. }
  447. let new_pos = new_active.offsetParent.offsetTop + new_active.offsetTop - nav_menu_height;
  448. if (prev_article && prev_article.offsetParent && new_active.offsetTop - prev_article.offsetTop <= 150) {
  449. new_pos = prev_article.offsetParent.offsetTop + prev_article.offsetTop - nav_menu_height;
  450. if (relative_move) {
  451. new_pos -= box_to_move.offsetTop;
  452. }
  453. }
  454. if (skipping) {
  455. // when skipping, this feels more natural if it’s not so near the top
  456. new_pos -= document.body.clientHeight / 4;
  457. }
  458. box_to_move.scrollTop = new_pos;
  459. }
  460. if (new_active.classList.contains('active') && !skipping) {
  461. if (context.auto_mark_article) {
  462. mark_read(new_active, true, true);
  463. }
  464. new_active.dispatchEvent(freshrssOpenArticleEvent);
  465. }
  466. onScroll();
  467. }
  468. function prev_entry(skipping) {
  469. const old_active = document.querySelector('.flux.current');
  470. let new_active = old_active;
  471. if (new_active) {
  472. do new_active = new_active.previousElementSibling;
  473. while (new_active && !new_active.classList.contains('flux'));
  474. if (!new_active) {
  475. prev_feed();
  476. }
  477. } else {
  478. new_active = document.querySelector('.flux');
  479. }
  480. if (context.auto_mark_focus && !new_active.classList.contains('keep_unread')) {
  481. mark_read(new_active, true, true);
  482. }
  483. toggleContent(new_active, old_active, skipping);
  484. }
  485. function next_entry(skipping) {
  486. const old_active = document.querySelector('.flux.current');
  487. let new_active = old_active;
  488. if (new_active) {
  489. do new_active = new_active.nextElementSibling;
  490. while (new_active && !new_active.classList.contains('flux'));
  491. if (!new_active) {
  492. next_feed();
  493. }
  494. } else {
  495. new_active = document.querySelector('.flux');
  496. }
  497. if (context.auto_mark_focus && !new_active.classList.contains('keep_unread')) {
  498. mark_read(new_active, true, true);
  499. }
  500. toggleContent(new_active, old_active, skipping);
  501. }
  502. function next_unread_entry(skipping) {
  503. const old_active = document.querySelector('.flux.current');
  504. let new_active = old_active;
  505. if (new_active) {
  506. do new_active = new_active.nextElementSibling;
  507. while (new_active && !new_active.classList.contains('not_read'));
  508. if (!new_active) {
  509. next_feed();
  510. }
  511. } else {
  512. new_active = document.querySelector('.not_read');
  513. }
  514. if (context.auto_mark_focus && !new_active.classList.contains('keep_unread')) {
  515. mark_read(new_active, true, true);
  516. }
  517. toggleContent(new_active, old_active, skipping);
  518. }
  519. function prev_feed() {
  520. let found = false;
  521. let adjacent = null;
  522. const feeds = document.querySelectorAll('#aside_feed .feed');
  523. for (let i = feeds.length - 1; i >= 0; i--) {
  524. const feed = feeds[i];
  525. if (feed.classList.contains('active')) {
  526. found = true;
  527. continue;
  528. }
  529. if (!found) {
  530. continue;
  531. }
  532. if (getComputedStyle(feed).display === 'none') {
  533. continue;
  534. }
  535. if (feed.dataset.unread != 0) {
  536. delayedClick(feed.querySelector('a.item-title'));
  537. return;
  538. } else if (adjacent === null) {
  539. adjacent = feed;
  540. }
  541. }
  542. if (found && adjacent) {
  543. delayedClick(adjacent.querySelector('a.item-title'));
  544. } else {
  545. last_feed();
  546. }
  547. }
  548. function next_feed() {
  549. let found = false;
  550. let adjacent = null;
  551. const feeds = document.querySelectorAll('#aside_feed .feed');
  552. for (let i = 0; i < feeds.length; i++) {
  553. const feed = feeds[i];
  554. if (feed.classList.contains('active')) {
  555. found = true;
  556. continue;
  557. }
  558. if (!found) {
  559. continue;
  560. }
  561. if (getComputedStyle(feed).display === 'none') {
  562. continue;
  563. }
  564. if (feed.dataset.unread != 0) {
  565. delayedClick(feed.querySelector('a.item-title'));
  566. return;
  567. } else if (adjacent === null) {
  568. adjacent = feed;
  569. }
  570. }
  571. if (found && adjacent) {
  572. delayedClick(adjacent.querySelector('a.item-title'));
  573. } else {
  574. first_feed();
  575. }
  576. }
  577. function first_feed() {
  578. const a = document.querySelector('#aside_feed .category.active .feed:not([data-unread="0"]) a.item-title');
  579. delayedClick(a);
  580. }
  581. function last_feed() {
  582. const links = document.querySelectorAll('#aside_feed .category.active .feed:not([data-unread="0"]) a.item-title');
  583. if (links && links.length > 0) {
  584. delayedClick(links[links.length - 1]);
  585. }
  586. }
  587. function prev_category() {
  588. const active_cat = document.querySelector('#aside_feed .category.active');
  589. if (active_cat) {
  590. let cat = active_cat;
  591. do cat = cat.previousElementSibling;
  592. while (cat && getComputedStyle(cat).display === 'none');
  593. if (cat) {
  594. delayedClick(cat.querySelector('a.tree-folder-title'));
  595. }
  596. } else {
  597. last_category();
  598. }
  599. }
  600. function next_category() {
  601. const active_cat = document.querySelector('#aside_feed .category.active');
  602. if (active_cat) {
  603. let cat = active_cat;
  604. do cat = cat.nextElementSibling;
  605. while (cat && getComputedStyle(cat).display === 'none');
  606. if (cat) {
  607. delayedClick(cat.querySelector('a.tree-folder-title'));
  608. }
  609. } else {
  610. first_category();
  611. }
  612. }
  613. function next_unread_category() {
  614. const active_cat = document.querySelector('#aside_feed .category.active');
  615. if (active_cat) {
  616. let cat = active_cat;
  617. do cat = cat.nextElementSibling;
  618. while (cat && cat.getAttribute('data-unread') <= 0);
  619. if (cat) {
  620. delayedClick(cat.querySelector('a.tree-folder-title'));
  621. }
  622. } else {
  623. first_category();
  624. }
  625. }
  626. function first_category() {
  627. const a = document.querySelector('#aside_feed .category:not([data-unread="0"]) a.tree-folder-title');
  628. delayedClick(a);
  629. }
  630. function last_category() {
  631. const links = document.querySelectorAll('#aside_feed .category:not([data-unread="0"]) a.tree-folder-title');
  632. if (links && links.length > 0) {
  633. delayedClick(links[links.length - 1]);
  634. }
  635. }
  636. function collapse_entry() {
  637. const flux_current = document.querySelector('.flux.current');
  638. toggleContent(flux_current, flux_current, false);
  639. }
  640. function toggle_media() {
  641. const media = document.querySelector('.flux.current video,.flux.current audio');
  642. if (media === null) {
  643. return;
  644. }
  645. if (media.paused) {
  646. media.play();
  647. } else {
  648. media.pause();
  649. }
  650. }
  651. function user_filter(key) {
  652. const filter = document.getElementById('dropdown-query');
  653. const filters = filter.parentElement.querySelectorAll('.dropdown-menu > .query > a');
  654. if (typeof key === 'undefined') {
  655. if (!filters.length) {
  656. return;
  657. }
  658. // Display the filter div
  659. location.hash = filter.id;
  660. // Force scrolling to the filter div
  661. const scroll = needsScroll(document.querySelector('.header'));
  662. if (scroll !== 0) {
  663. document.scrollingElement.scrollTop = scroll;
  664. }
  665. // Force the key value if there is only one action, so we can trigger it automatically
  666. if (filters.length === 1) {
  667. key = 1;
  668. } else {
  669. return;
  670. }
  671. }
  672. // Trigger selected share action
  673. key = parseInt(key);
  674. if (key <= filters.length) {
  675. filters[key - 1].click();
  676. }
  677. }
  678. function show_labels_menu(el) {
  679. const div = el.parentElement;
  680. const dropdownMenu = div.querySelector('.dropdown-menu');
  681. if (!dropdownMenu || forceReloadLabelsList) {
  682. if (dropdownMenu) {
  683. dropdownMenu.nextElementSibling.remove();
  684. dropdownMenu.remove();
  685. }
  686. const templateId = 'labels_article_template';
  687. const template = document.getElementById(templateId).innerHTML;
  688. div.insertAdjacentHTML('beforeend', template);
  689. loadDynamicTags(div.closest('.dynamictags'));
  690. }
  691. return true;
  692. }
  693. function show_share_menu(el) {
  694. const div = el.parentElement;
  695. const dropdownMenu = div.querySelector('.dropdown-menu');
  696. if (!dropdownMenu) {
  697. const itemId = el.closest('.flux').dataset.entry;
  698. const templateId = 'share_article_template';
  699. const id = itemId;
  700. const flux_header_el = el.closest('.flux');
  701. const title_el = flux_header_el.querySelector('.item.titleAuthorSummaryDate .item-element.title');
  702. const websiteName = ' - ' + flux_header_el.querySelector('.flux_header').dataset.websiteName;
  703. const articleAuthors = flux_header_el.querySelector('.flux_header').dataset.articleAuthors;
  704. let articleAuthorsText = '';
  705. if (articleAuthors.trim().length > 0) {
  706. articleAuthorsText = ' (' + articleAuthors + ')';
  707. }
  708. const link = title_el.href;
  709. const title = title_el.textContent;
  710. const titleText = title;
  711. const template = document.getElementById(templateId).innerHTML
  712. .replace(/--entryId--/g, id)
  713. .replace(/--link--/g, link)
  714. .replace(/--titleText--/g, titleText)
  715. .replace(/--websiteName--/g, websiteName)
  716. .replace(/--articleAuthors--/g, articleAuthorsText);
  717. div.insertAdjacentHTML('beforeend', template);
  718. }
  719. return true;
  720. }
  721. function mylabels(key) {
  722. const mylabelsDropdown = document.querySelector('.flux.current.active .dropdown-target[id^="dropdown-labels"]');
  723. if (!mylabelsDropdown) {
  724. return;
  725. }
  726. if (typeof key === 'undefined') {
  727. show_labels_menu(mylabelsDropdown);
  728. }
  729. // Display the mylabels div
  730. location.hash = mylabelsDropdown.id;
  731. // Force scrolling to the mylabels div
  732. const scrollTop = needsScroll(mylabelsDropdown.closest('.horizontal-list'));
  733. if (scrollTop !== 0) {
  734. if (mylabelsDropdown.closest('.horizontal-list.flux_header')) {
  735. mylabelsDropdown.nextElementSibling.nextElementSibling.scrollIntoView({ behavior: "smooth", block: "start" });
  736. } else {
  737. mylabelsDropdown.nextElementSibling.nextElementSibling.scrollIntoView({ behavior: "smooth", block: "end" });
  738. }
  739. }
  740. key = parseInt(key);
  741. if (key === 0) {
  742. mylabelsDropdown.parentElement.querySelector('.dropdown-menu .item .newTag').focus();
  743. } else {
  744. const mylabelsCheckboxes = mylabelsDropdown.parentElement.querySelectorAll('.dropdown-menu .item .checkboxTag');
  745. if (key <= mylabelsCheckboxes.length) {
  746. mylabelsCheckboxes[key].click();
  747. }
  748. }
  749. }
  750. function auto_share(key) {
  751. const share = document.querySelector('.flux.current.active .dropdown-target[id^="dropdown-share"]');
  752. if (!share) {
  753. return;
  754. }
  755. const shares = share.parentElement.querySelectorAll('.dropdown-menu .item [data-type]');
  756. if (typeof key === 'undefined') {
  757. show_share_menu(share);
  758. // Display the share div
  759. location.hash = share.id;
  760. // Force scrolling to the share div
  761. const scrollTop = needsScroll(share.closest('.horizontal-list'));
  762. if (scrollTop !== 0) {
  763. if (share.closest('.horizontal-list.flux_header')) {
  764. share.nextElementSibling.nextElementSibling.scrollIntoView({ behavior: "smooth", block: "start" });
  765. } else {
  766. share.nextElementSibling.nextElementSibling.scrollIntoView({ behavior: "smooth", block: "end" });
  767. }
  768. }
  769. // Force the key value if there is only one action, so we can trigger it automatically
  770. if (shares.length === 1) {
  771. key = 1;
  772. } else {
  773. return;
  774. }
  775. }
  776. // Trigger selected share action and hide the share div
  777. key = parseInt(key);
  778. if (key <= shares.length) {
  779. shares[key - 1].click();
  780. share.parentElement.querySelector('.dropdown-menu + a.dropdown-close').click();
  781. }
  782. }
  783. let box_to_follow;
  784. function onScroll() {
  785. if (!box_to_follow) {
  786. return;
  787. }
  788. if (context.auto_mark_scroll) {
  789. const hidden_px = -5; // negative = pixels over the edge
  790. const minTop = hidden_px + box_to_follow.scrollTop;
  791. document.querySelectorAll('.not_read:not(.keep_unread)').forEach(function (div) {
  792. if (div.offsetHeight > 0 &&
  793. div.offsetParent.offsetTop + div.offsetTop + div.offsetHeight < minTop) {
  794. mark_read(div, true, true);
  795. }
  796. });
  797. }
  798. let streamFooter;
  799. if (context.auto_load_more && (streamFooter = document.getElementById('stream-footer'))) {
  800. if (box_to_follow.offsetHeight > 0 &&
  801. box_to_follow.scrollTop + box_to_follow.offsetHeight + (window.innerHeight / 2) >= streamFooter.offsetTop) {
  802. // Too close to the last pre-loaded article
  803. load_more_posts();
  804. } else {
  805. const after = document.querySelectorAll('.flux.current ~ .flux').length;
  806. if (after > 0 && after <= 5) {
  807. // Too few pre-loaded articles
  808. load_more_posts();
  809. }
  810. }
  811. }
  812. }
  813. let lastScroll = 0; // Throttle
  814. let timerId = 0;
  815. function debouncedOnScroll() {
  816. clearTimeout(timerId);
  817. if (lastScroll + 500 < Date.now()) {
  818. lastScroll = Date.now();
  819. onScroll();
  820. } else {
  821. timerId = setTimeout(onScroll, 500);
  822. }
  823. }
  824. function init_posts() {
  825. if (context.auto_load_more || context.auto_mark_scroll || context.auto_remove_article) {
  826. box_to_follow = context.current_view === 'global' ? document.getElementById('panel') : document.scrollingElement;
  827. (box_to_follow === document.scrollingElement ? window : box_to_follow).onscroll = debouncedOnScroll;
  828. window.addEventListener('resize', debouncedOnScroll);
  829. onScroll();
  830. }
  831. if (!navigator.share && document.styleSheets.length > 0) {
  832. // https://developer.mozilla.org/en-US/docs/Web/API/Navigator/share
  833. // do not show the menu entry if browser does not support navigator.share
  834. document.styleSheets[0].insertRule(
  835. 'button.as-link[data-type="web-sharing-api"] {display: none !important;}',
  836. document.styleSheets[0].cssRules.length
  837. );
  838. }
  839. }
  840. function rememberOpenCategory(category_id, isOpen) {
  841. if (context.display_categories === 'remember') {
  842. const open_categories = JSON.parse(localStorage.getItem('FreshRSS_open_categories') || '{}');
  843. if (isOpen) {
  844. open_categories[category_id] = true;
  845. } else {
  846. delete open_categories[category_id];
  847. }
  848. localStorage.setItem('FreshRSS_open_categories', JSON.stringify(open_categories));
  849. }
  850. }
  851. function openCategory(category_id) {
  852. const category_element = document.getElementById(category_id);
  853. if (!category_element) return;
  854. category_element.querySelector('.tree-folder-items').classList.add('active');
  855. const img = category_element.querySelector('button.dropdown-toggle img');
  856. if (!img) return;
  857. img.src = img.src.replace('/icons/down.', '/icons/up.');
  858. img.alt = '🔼';
  859. }
  860. function loadJs(name) {
  861. if (!document.getElementById(name)) {
  862. const script = document.createElement('script');
  863. script.setAttribute('id', name);
  864. script.setAttribute('src', '../scripts/' + name + '?' + context.mtime[name]);
  865. script.setAttribute('defer', 'defer');
  866. script.setAttribute('async', 'async');
  867. document.head.appendChild(script);
  868. }
  869. }
  870. function init_column_categories() {
  871. if (context.current_view !== 'normal' && context.current_view !== 'reader') {
  872. return;
  873. }
  874. // Restore sidebar scroll position
  875. document.getElementById('sidebar').scrollTop = +sessionStorage.getItem('FreshRSS_sidebar_scrollTop');
  876. // Restore open categories
  877. if (context.display_categories === 'remember') {
  878. const open_categories = JSON.parse(localStorage.getItem('FreshRSS_open_categories') || '{}');
  879. Object.keys(open_categories).forEach(function (category_id) {
  880. openCategory(category_id);
  881. });
  882. }
  883. document.getElementById('aside_feed').onclick = function (ev) {
  884. let a = ev.target.closest('.tree-folder > .tree-folder-title > button.dropdown-toggle');
  885. if (a) {
  886. const icon = a.querySelector('.icon');
  887. const category_id = a.closest('.category').id;
  888. if (icon.alt === '🔽' || icon.innerHTML === '🔽') {
  889. if (icon.src) {
  890. icon.src = icon.src.replace('/icons/down.', '/icons/up.');
  891. icon.alt = '🔼';
  892. } else {
  893. icon.innerHTML = '🔼';
  894. }
  895. rememberOpenCategory(category_id, true);
  896. } else {
  897. if (icon.src) {
  898. icon.src = icon.src.replace('/icons/up.', '/icons/down.');
  899. icon.alt = '🔽';
  900. } else {
  901. icon.innerHTML = '🔽';
  902. }
  903. rememberOpenCategory(category_id, false);
  904. }
  905. const ul = a.closest('li').querySelector('.tree-folder-items');
  906. let nbVisibleItems = 0;
  907. for (let i = ul.children.length - 1; i >= 0; i--) {
  908. if (ul.children[i].offsetHeight) {
  909. nbVisibleItems++;
  910. }
  911. }
  912. ul.classList.toggle('active');
  913. // CSS transition does not work on max-height:auto
  914. ul.style.maxHeight = ul.classList.contains('active') ? (nbVisibleItems * 4) + 'em' : 0;
  915. return false;
  916. }
  917. a = ev.target.closest('.tree-folder-items > .feed .dropdown-toggle');
  918. if (a) {
  919. const div = a.parentElement;
  920. const dropdownMenu = div.querySelector('.dropdown-menu');
  921. if (!dropdownMenu) {
  922. loadJs('extra.js');
  923. loadJs('feed.js');
  924. const itemId = a.closest('.item').id;
  925. const templateId = itemId.substring(0, 2) === 't_' ? 'tag_config_template' : 'feed_config_template';
  926. const id = itemId.substr(2);
  927. const feed_web = a.getAttribute('data-fweb') || '';
  928. const template = document.getElementById(templateId)
  929. .innerHTML.replace(/------/g, id).replace('http://example.net/', feed_web);
  930. div.insertAdjacentHTML('beforeend', template);
  931. if (feed_web == '') {
  932. const website = div.querySelector('.item.link.website');
  933. if (website) {
  934. website.remove();
  935. }
  936. }
  937. const b = div.querySelector('button.confirm');
  938. if (b) {
  939. b.disabled = false;
  940. }
  941. }
  942. return true;
  943. }
  944. return true;
  945. };
  946. }
  947. function init_shortcuts() {
  948. Object.keys(context.shortcuts).forEach(function (k) {
  949. context.shortcuts[k] = (context.shortcuts[k] || '').toUpperCase();
  950. });
  951. document.addEventListener('keydown', ev => {
  952. if (ev.ctrlKey || ev.metaKey || (ev.altKey && ev.shiftKey) || ev.target.closest('input, select, textarea')) {
  953. return;
  954. }
  955. const s = context.shortcuts;
  956. let k = (ev.key.trim() || ev.code || 'Space').toUpperCase();
  957. // IE11
  958. if (k === 'SPACEBAR') k = 'SPACE';
  959. else if (k === 'DEL') k = 'DELETE';
  960. else if (k === 'ESC') k = 'ESCAPE';
  961. if (location.hash.match(/^#dropdown-/)) {
  962. const n = parseInt(k);
  963. if (Number.isInteger(n)) {
  964. switch (location.hash.substring(0, 15)) {
  965. case '#dropdown-query':
  966. user_filter(n);
  967. break;
  968. case '#dropdown-share':
  969. auto_share(n);
  970. break;
  971. case '#dropdown-label':
  972. mylabels(n);
  973. break;
  974. default:
  975. return;
  976. }
  977. ev.preventDefault();
  978. return;
  979. }
  980. }
  981. if (k === s.actualize) {
  982. const btn = document.getElementById('actualize');
  983. if (btn) {
  984. btn.click();
  985. }
  986. ev.preventDefault();
  987. return;
  988. }
  989. if (k === s.next_entry) {
  990. if (ev.altKey) {
  991. next_category();
  992. } else if (ev.shiftKey) {
  993. next_feed();
  994. } else {
  995. next_entry(false);
  996. }
  997. ev.preventDefault();
  998. return;
  999. }
  1000. if (k === s.next_unread_entry) {
  1001. if (ev.altKey) {
  1002. next_unread_category();
  1003. } else if (ev.shiftKey) {
  1004. next_feed();
  1005. } else {
  1006. next_unread_entry(false);
  1007. }
  1008. ev.preventDefault();
  1009. return;
  1010. }
  1011. if (k === s.prev_entry) {
  1012. if (ev.altKey) {
  1013. prev_category();
  1014. } else if (ev.shiftKey) {
  1015. prev_feed();
  1016. } else {
  1017. prev_entry(false);
  1018. }
  1019. ev.preventDefault();
  1020. return;
  1021. }
  1022. if (k === s.mark_read) {
  1023. if (ev.altKey) {
  1024. mark_previous_read(document.querySelector('.flux.current'));
  1025. } else if (ev.shiftKey) {
  1026. document.querySelector('.nav_menu .read_all').click();
  1027. } else { // Toggle the read state
  1028. mark_read(document.querySelector('.flux.current'), false, false);
  1029. }
  1030. ev.preventDefault();
  1031. return;
  1032. }
  1033. if (k === s.first_entry) {
  1034. if (ev.altKey) {
  1035. first_category();
  1036. } else if (ev.shiftKey) {
  1037. first_feed();
  1038. } else {
  1039. const old_active = document.querySelector('.flux.current');
  1040. const first = document.querySelector('.flux');
  1041. if (first.classList.contains('flux')) {
  1042. toggleContent(first, old_active, false);
  1043. }
  1044. }
  1045. ev.preventDefault();
  1046. return;
  1047. }
  1048. if (k === s.last_entry) {
  1049. if (ev.altKey) {
  1050. last_category();
  1051. } else if (ev.shiftKey) {
  1052. last_feed();
  1053. } else {
  1054. const old_active = document.querySelector('.flux.current');
  1055. const last = document.querySelector('.flux:last-of-type');
  1056. if (last.classList.contains('flux')) {
  1057. toggleContent(last, old_active, false);
  1058. }
  1059. }
  1060. ev.preventDefault();
  1061. return;
  1062. }
  1063. if (ev.key === '?') {
  1064. window.location.href = context.urls.shortcuts;
  1065. return;
  1066. }
  1067. if (ev.altKey || ev.shiftKey) {
  1068. return;
  1069. }
  1070. if (k === s.mark_favorite) { // Toggle the favorite state
  1071. mark_favorite(document.querySelector('.flux.current'));
  1072. ev.preventDefault();
  1073. return;
  1074. }
  1075. if (k === s.go_website) {
  1076. if (context.auto_mark_site) {
  1077. mark_read(document.querySelector('.flux.current'), true, false);
  1078. }
  1079. const link_go_website = document.querySelector('.flux.current a.go_website');
  1080. if (link_go_website) {
  1081. window.open(link_go_website.href, '_blank', 'noopener');
  1082. ev.preventDefault();
  1083. }
  1084. return;
  1085. }
  1086. const hash = location.hash.substr(1);
  1087. if (k === s.skip_next_entry) { next_entry(true); ev.preventDefault(); return; }
  1088. if (k === s.skip_prev_entry) { prev_entry(true); ev.preventDefault(); return; }
  1089. if (k === s.collapse_entry) { collapse_entry(); ev.preventDefault(); return; }
  1090. if (k === s.mylabels) { mylabels(); ev.preventDefault(); return; }
  1091. if (k === s.auto_share) { auto_share(); ev.preventDefault(); return; }
  1092. if (k === s.user_filter) { user_filter(); ev.preventDefault(); return; }
  1093. if (k === s.load_more) { load_more_posts(); ev.preventDefault(); return; }
  1094. /* globals close_slider_listener */
  1095. if (k === s.close_menus && (
  1096. (hash === 'slider' && close_slider_listener()) ||
  1097. hash.startsWith('dropdown')
  1098. )) { location.hash = ''; ev.preventDefault(); return; }
  1099. if (k === s.help) { window.open(context.urls.help); ev.preventDefault(); return; }
  1100. if (k === s.focus_search) { document.getElementById('search').focus(); ev.preventDefault(); return; }
  1101. if (k === s.normal_view) { delayedClick(document.querySelector('#nav_menu_views .view-normal')); ev.preventDefault(); return; }
  1102. if (k === s.reading_view) { delayedClick(document.querySelector('#nav_menu_views .view-reader')); ev.preventDefault(); return; }
  1103. if (k === s.global_view) { delayedClick(document.querySelector('#nav_menu_views .view-global')); ev.preventDefault(); return; }
  1104. if (k === s.toggle_media) { toggle_media(); ev.preventDefault(); }
  1105. });
  1106. }
  1107. function init_stream(stream) {
  1108. stream.onclick = function (ev) {
  1109. let el = ev.target.closest('.flux a.read');
  1110. if (el) {
  1111. mark_read(el.closest('.flux'), false, false);
  1112. return false;
  1113. }
  1114. el = ev.target.closest('.flux a.bookmark');
  1115. if (el) {
  1116. mark_favorite(el.closest('.flux'));
  1117. return false;
  1118. }
  1119. el = ev.target.closest('.item a.title');
  1120. if (el) { // Allow default control/command-click behaviour such as open in background-tab
  1121. return ev.ctrlKey || ev.metaKey;
  1122. }
  1123. el = ev.target.closest('.flux .content .text a');
  1124. if (el) {
  1125. if (!el.closest('div').classList.contains('author')) {
  1126. el.target = '_blank';
  1127. el.rel = 'noreferrer';
  1128. }
  1129. return true;
  1130. }
  1131. el = ev.target.closest('.item.labels a.dropdown-toggle');
  1132. if (el) {
  1133. return show_labels_menu(el);
  1134. }
  1135. el = ev.target.closest('.item.share a.dropdown-toggle');
  1136. if (el) {
  1137. return show_share_menu(el);
  1138. }
  1139. el = ev.target.closest('.item.share > button[data-type="print"]');
  1140. if (el) { // Print
  1141. const html = document.documentElement;
  1142. const head = document.head.cloneNode(true);
  1143. head.querySelectorAll('script').forEach(js => js.remove());
  1144. const flux_content = el.closest('.flux_content');
  1145. let content_el = null;
  1146. if (flux_content) {
  1147. content_el = el.closest('.flux_content').querySelector('.content').cloneNode(true);
  1148. }
  1149. if (content_el === null) {
  1150. content_el = el.closest('.flux').querySelector('.flux_content .content').cloneNode(true);
  1151. }
  1152. content_el.querySelectorAll('a').forEach(link => {
  1153. // Avoid leaking the instance URL in PDFs
  1154. if (link.href.startsWith(location.origin)) {
  1155. link.removeAttribute('href');
  1156. }
  1157. });
  1158. content_el.querySelectorAll('details').forEach(el => el.setAttribute('open', 'open'));
  1159. const articleTitle = content_el.querySelector('.title a').innerText;
  1160. prevTitle = document.title;
  1161. // Chrome uses the parent's title to get the PDF save filename
  1162. document.title = articleTitle;
  1163. // Firefox uses the iframe's title to get the PDF save filename
  1164. // Note: Firefox Mobile saves PDFs with a filename that looks like: `temp[19 random digits].PDF` regardless of title
  1165. head.querySelector('title').innerText = articleTitle;
  1166. loadLazyImages(content_el);
  1167. const print_frame = document.createElement('iframe');
  1168. print_frame.style.display = 'none';
  1169. print_frame.srcdoc = `
  1170. <!DOCTYPE html>
  1171. <html class="${html.getAttribute('class')}">
  1172. <head>
  1173. ${head.innerHTML}
  1174. </head>
  1175. <body>
  1176. ${content_el.outerHTML}
  1177. </body>
  1178. </html>
  1179. `;
  1180. document.body.prepend(print_frame);
  1181. function afterPrint() {
  1182. print_frame.remove();
  1183. document.title = prevTitle;
  1184. prevTitle = '';
  1185. window.removeEventListener('focus', afterPrint);
  1186. }
  1187. print_frame.onload = () => {
  1188. const tmp_window = print_frame.contentWindow;
  1189. // Needed for Chrome
  1190. tmp_window.matchMedia('print').onchange = (e) => {
  1191. // UA check is needed to not trigger on Chrome Mobile
  1192. if (!e.matches && !navigator.userAgent.includes('Mobi')) {
  1193. afterPrint();
  1194. }
  1195. };
  1196. tmp_window.print();
  1197. };
  1198. // Needed for Firefox and Chrome Mobile
  1199. window.addEventListener('focus', afterPrint);
  1200. return false;
  1201. }
  1202. el = ev.target.closest('.item.share > button[data-type="clipboard"]');
  1203. if (el) { // Clipboard
  1204. if (navigator.clipboard) {
  1205. navigator.clipboard.writeText(el.dataset.url)
  1206. .then(() => {
  1207. toggleClass(el, 'ok');
  1208. })
  1209. .catch(e => {
  1210. console.log(e);
  1211. toggleClass(el, 'error');
  1212. });
  1213. } else {
  1214. // fallback, if navigator.clipboard is not available f.e. if access is not via https or localhost
  1215. const inputElement = document.createElement('input');
  1216. inputElement.value = el.dataset.url;
  1217. document.body.appendChild(inputElement);
  1218. inputElement.select();
  1219. if (document.execCommand && document.execCommand('copy')) {
  1220. toggleClass(el, 'ok');
  1221. } else {
  1222. console.log('document.execCommand("copy") failed');
  1223. toggleClass(el, 'error');
  1224. }
  1225. inputElement.remove();
  1226. }
  1227. return false;
  1228. }
  1229. el = ev.target.closest('.item.share > button[data-type="web-sharing-api"]');
  1230. if (el && navigator.share) { // https://developer.mozilla.org/en-US/docs/Web/API/Navigator/share
  1231. const shareData = {
  1232. url: el.dataset.url,
  1233. title: decodeURI(el.dataset.title),
  1234. };
  1235. navigator.share(shareData);
  1236. return false;
  1237. }
  1238. el = ev.target.closest('.item.share > a[data-type="email-webmail-firefox-fix"]');
  1239. if (el) {
  1240. window.open(el.href);
  1241. return false;
  1242. }
  1243. el = ev.target.closest('.item.share > a[href="POST"]');
  1244. if (el) { // Share by POST
  1245. const f = el.parentElement.querySelector('form');
  1246. f.disabled = false;
  1247. f.submit();
  1248. return false;
  1249. }
  1250. el = ev.target.closest('.flux_header, .flux_content');
  1251. if (el) { // flux_toggle
  1252. if (ev.target.closest('.reader, .content, .item.website, .item.link, .dropdown')) {
  1253. return true;
  1254. }
  1255. if ((!context.sides_close_article && ev.target.matches('.flux_content')) || ev.target.closest('footer')) {
  1256. // setting for not-closing after clicking outside article area
  1257. return false;
  1258. }
  1259. const old_active = document.querySelector('.flux.current');
  1260. const new_active = el.parentNode;
  1261. if (ev.target.tagName.toUpperCase() === 'A') { // Leave real links alone (but does not catch img in a link)
  1262. if (context.auto_mark_article) {
  1263. mark_read(new_active, true, false);
  1264. }
  1265. return true;
  1266. }
  1267. toggleContent(new_active, old_active, false);
  1268. return false;
  1269. }
  1270. };
  1271. stream.onmouseup = function (ev) { // Mouseup enables us to catch middle click, and control+click in IE/Edge
  1272. if (ev.altKey || ev.metaKey || ev.shiftKey) {
  1273. return;
  1274. }
  1275. let el = ev.target.closest('.item a.title');
  1276. if (el) {
  1277. if (ev.which == 1) {
  1278. if (ev.ctrlKey) { // Control+click
  1279. if (context.auto_mark_site) {
  1280. mark_read(el.closest('.flux'), true, false);
  1281. }
  1282. } else {
  1283. el.parentElement.click(); // Normal click, just toggle article.
  1284. }
  1285. } else if (ev.which == 2 && !ev.ctrlKey) { // Simple middle click: same behaviour as CTRL+click
  1286. if (context.auto_mark_article) {
  1287. const new_active = el.closest('.flux');
  1288. mark_read(new_active, true, false);
  1289. }
  1290. }
  1291. return;
  1292. }
  1293. if (context.auto_mark_site) {
  1294. // catch mouseup instead of click so we can have the correct behaviour
  1295. // with middle button click (scroll button).
  1296. el = ev.target.closest('.flux .link > a');
  1297. if (el) {
  1298. if (ev.which == 3) {
  1299. return;
  1300. }
  1301. mark_read(el.closest('.flux'), true, false);
  1302. }
  1303. }
  1304. };
  1305. stream.onchange = function (ev) {
  1306. const checkboxTag = ev.target.closest('.checkboxTag');
  1307. if (checkboxTag) { // Dynamic tags
  1308. ev.stopPropagation();
  1309. const tagId = checkboxTag.name.replace(/^t_/, '');
  1310. const tagName = checkboxTag.nextElementSibling ? checkboxTag.nextElementSibling.childNodes[0].value : '';
  1311. if ((tagId == 0 && tagName.length > 0) || tagId != 0) {
  1312. const isChecked = checkboxTag.checked;
  1313. const entry = checkboxTag.closest('div.flux');
  1314. const entryId = entry.id.replace(/^flux_/, '');
  1315. checkboxTag.disabled = true;
  1316. const req = new XMLHttpRequest();
  1317. req.open('POST', './?c=tag&a=tagEntry&ajax=1', true);
  1318. req.responseType = 'json';
  1319. req.onerror = function (e) {
  1320. checkboxTag.checked = !isChecked;
  1321. badAjax(this.status == 403);
  1322. };
  1323. req.onload = function (e) {
  1324. if (this.status != 200) {
  1325. return req.onerror(e);
  1326. }
  1327. if (entry.classList.contains('not_read')) {
  1328. incUnreadsTag('t_' + tagId, isChecked ? 1 : -1);
  1329. }
  1330. };
  1331. req.onloadend = function (e) {
  1332. checkboxTag.disabled = false;
  1333. if (tagId == 0) {
  1334. // new tag is added
  1335. forceReloadLabelsList = true;
  1336. loadDynamicTags(checkboxTag.closest('div.dropdown'));
  1337. } else {
  1338. // a tag was (un)checked
  1339. const dropdownmenu_current = ev.target.closest('.dropdown-menu');
  1340. const flux = ev.target.closest('.flux');
  1341. const dropdownmenu_all = flux.querySelectorAll('.dynamictags .dropdown-menu');
  1342. if (dropdownmenu_all.length > 1) {
  1343. // delete all other tag dropdown menus except the current one
  1344. dropdownmenu_all.forEach(
  1345. function (currentValue) {
  1346. if (currentValue !== dropdownmenu_current) {
  1347. currentValue.nextElementSibling.remove();
  1348. currentValue.parentNode.removeChild(currentValue);
  1349. }
  1350. }
  1351. );
  1352. }
  1353. }
  1354. };
  1355. req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
  1356. req.send(JSON.stringify({
  1357. _csrf: context.csrf,
  1358. id_tag: tagId,
  1359. name_tag: tagId == 0 ? tagName : '',
  1360. id_entry: entryId,
  1361. checked: isChecked,
  1362. ajax: 1,
  1363. }));
  1364. }
  1365. }
  1366. };
  1367. }
  1368. function toggleClass(el, cssclass) {
  1369. el.classList.remove(cssclass);
  1370. el.dataset.foo = el.offsetWidth; // it does nothing, but it is needed. See https://github.com/FreshRSS/FreshRSS/pull/5295
  1371. el.classList.add(cssclass);
  1372. }
  1373. function init_nav_entries() {
  1374. const nav_entries = document.getElementById('nav_entries');
  1375. if (nav_entries) {
  1376. nav_entries.querySelector('.previous_entry').onclick = function (e) {
  1377. prev_entry(false);
  1378. return false;
  1379. };
  1380. nav_entries.querySelector('.next_entry').onclick = function (e) {
  1381. next_entry(false);
  1382. return false;
  1383. };
  1384. nav_entries.querySelector('.up').onclick = function (e) {
  1385. const active_item = (document.querySelector('.flux.current') || document.querySelector('.flux'));
  1386. const windowTop = document.scrollingElement.scrollTop;
  1387. const item_top = active_item.offsetParent.offsetTop + active_item.offsetTop;
  1388. const nav_menu = document.querySelector('.nav_menu');
  1389. let nav_menu_height = 0;
  1390. if (getComputedStyle(nav_menu).position === 'fixed' || getComputedStyle(nav_menu).position === 'sticky') {
  1391. nav_menu_height = nav_menu.offsetHeight;
  1392. }
  1393. document.scrollingElement.scrollTop = windowTop > item_top ? item_top - nav_menu_height : 0 - nav_menu_height;
  1394. return false;
  1395. };
  1396. }
  1397. }
  1398. // forceReloadLabelsList default is false, so that the list does need a reload after opening it a second time.
  1399. // will be set to true, if a new tag is added. Then the labels list will be reloaded each opening.
  1400. // purpose of this flag: minimize the network traffic.
  1401. let forceReloadLabelsList = false;
  1402. function loadDynamicTags(div) {
  1403. div.querySelectorAll('li.item').forEach(function (li) { li.remove(); });
  1404. const entryId = div.closest('div.flux').id.replace(/^flux_/, '');
  1405. const req = new XMLHttpRequest();
  1406. req.open('GET', './?c=tag&a=getTagsForEntry&id_entry=' + entryId, true);
  1407. req.responseType = 'json';
  1408. req.onerror = function (e) {
  1409. div.querySelectorAll('li.item').forEach(function (li) { li.remove(); });
  1410. };
  1411. req.onload = function (e) {
  1412. if (this.status != 200) {
  1413. return req.onerror(e);
  1414. }
  1415. const json = xmlHttpRequestJson(this);
  1416. if (!json) {
  1417. return req.onerror(e);
  1418. }
  1419. if (!context.anonymous) {
  1420. const li_item0 = document.createElement('li');
  1421. li_item0.setAttribute('class', 'item addItem');
  1422. const label = document.createElement('label');
  1423. label.setAttribute('class', 'noHover');
  1424. const input_checkboxTag = document.createElement('input');
  1425. input_checkboxTag.setAttribute('class', 'checkboxTag checkboxNewTag');
  1426. input_checkboxTag.setAttribute('name', 't_0');
  1427. input_checkboxTag.setAttribute('type', 'checkbox');
  1428. const input_newTag = document.createElement('input');
  1429. input_newTag.setAttribute('type', 'text');
  1430. input_newTag.setAttribute('name', 'newTag');
  1431. input_newTag.setAttribute('class', 'newTag');
  1432. input_newTag.setAttribute('list', 'datalist-labels');
  1433. input_newTag.addEventListener('keydown', function (ev) { if (ev.key.toUpperCase() == 'ENTER') { this.parentNode.previousSibling.click(); } });
  1434. const button_btn = document.createElement('button');
  1435. button_btn.setAttribute('type', 'button');
  1436. button_btn.setAttribute('class', 'btn');
  1437. button_btn.addEventListener('click', function () { this.parentNode.parentNode.click(); });
  1438. const text_plus = document.createTextNode('+');
  1439. const div_stick = document.createElement('div');
  1440. div_stick.setAttribute('class', 'stick');
  1441. button_btn.appendChild(text_plus);
  1442. div_stick.appendChild(input_newTag);
  1443. div_stick.appendChild(button_btn);
  1444. label.appendChild(input_checkboxTag);
  1445. label.appendChild(div_stick);
  1446. li_item0.appendChild(label);
  1447. div.querySelector('.dropdown-menu-scrollable').appendChild(li_item0);
  1448. }
  1449. let html = '';
  1450. let datalist = '';
  1451. if (json && json.length) {
  1452. let nbLabelsChecked = 0;
  1453. for (let i = 0; i < json.length; i++) {
  1454. const tag = json[i];
  1455. if (context.anonymous && !tag.checked) {
  1456. // In anomymous mode, show only the used tags
  1457. continue;
  1458. }
  1459. if (tag.checked) {
  1460. nbLabelsChecked++;
  1461. }
  1462. html += '<li class="item"><label><input ' +
  1463. (context.anonymous ? '' : 'class="checkboxTag" ') +
  1464. 'name="t_' + tag.id + '"type="checkbox" ' +
  1465. (context.anonymous ? 'disabled="disabled" ' : '') +
  1466. (tag.checked ? 'checked="checked" ' : '') + '/>' + tag.name + '</label></li>';
  1467. datalist += '<option value="' + tag.name + '"></option>';
  1468. }
  1469. if (context.anonymous && nbLabelsChecked === 0) {
  1470. html += '<li class="item"><span class="emptyLabels">' + context.i18n.labels_empty + '</span></li>';
  1471. }
  1472. }
  1473. div.querySelector('.dropdown-menu-scrollable').insertAdjacentHTML('beforeend', html);
  1474. const datalistLabels = document.getElementById('datalist-labels');
  1475. datalistLabels.innerHTML = ''; // clear before add the (updated) labels list
  1476. datalistLabels.insertAdjacentHTML('beforeend', datalist);
  1477. };
  1478. req.send();
  1479. }
  1480. // <actualize>
  1481. let feeds_processed = 0;
  1482. let categories_processed = 0;
  1483. let to_process = 0;
  1484. function refreshFeed(feeds, feeds_count) {
  1485. const feed = feeds.pop();
  1486. if (!feed) {
  1487. return;
  1488. }
  1489. const req = new XMLHttpRequest();
  1490. req.open('POST', feed.url, true);
  1491. req.onloadend = function (e) {
  1492. feeds_processed++;
  1493. if (this.status != 200) {
  1494. badAjax(false);
  1495. } else {
  1496. const div = document.getElementById('actualizeProgress');
  1497. div.querySelector('.progress').innerHTML = (categories_processed + feeds_processed) + ' / ' + to_process;
  1498. div.querySelector('.title').innerHTML = feed.title;
  1499. }
  1500. if (feeds_processed === feeds_count) {
  1501. // Empty request to commit new articles
  1502. const req2 = new XMLHttpRequest();
  1503. req2.open('POST', './?c=feed&a=actualize&id=-1&ajax=1', true);
  1504. req2.onloadend = function (e) {
  1505. delayedFunction(function () { location.reload(); });
  1506. };
  1507. req2.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
  1508. req2.send(JSON.stringify({
  1509. _csrf: context.csrf,
  1510. noCommit: 0,
  1511. }));
  1512. } else {
  1513. refreshFeed(feeds, feeds_count);
  1514. }
  1515. };
  1516. req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
  1517. req.send(JSON.stringify({
  1518. _csrf: context.csrf,
  1519. noCommit: 1,
  1520. }));
  1521. }
  1522. function refreshFeeds(json) {
  1523. feeds_processed = 0;
  1524. if (!json.feeds || json.feeds.length === 0) {
  1525. // Empty request to commit new articles
  1526. const req2 = new XMLHttpRequest();
  1527. req2.open('POST', './?c=feed&a=actualize&id=-1&ajax=1', true);
  1528. req2.onloadend = function (e) {
  1529. context.ajax_loading = false;
  1530. };
  1531. req2.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
  1532. req2.send(JSON.stringify({
  1533. _csrf: context.csrf,
  1534. noCommit: 0,
  1535. }));
  1536. } else {
  1537. const feeds_count = json.feeds.length;
  1538. for (let i = context.nb_parallel_refresh; i > 0; i--) {
  1539. refreshFeed(json.feeds, feeds_count);
  1540. }
  1541. }
  1542. }
  1543. function refreshDynamicOpml(categories, categories_count, next) {
  1544. const category = categories.pop();
  1545. if (!category) {
  1546. return;
  1547. }
  1548. const req = new XMLHttpRequest();
  1549. req.open('POST', category.url, true);
  1550. req.onloadend = function (e) {
  1551. categories_processed++;
  1552. if (this.status != 200) {
  1553. badAjax(false);
  1554. } else {
  1555. const div = document.getElementById('actualizeProgress');
  1556. div.querySelector('.progress').innerHTML = (categories_processed + feeds_processed) + ' / ' + to_process;
  1557. div.querySelector('.title').innerHTML = category.title;
  1558. }
  1559. if (categories_processed === categories_count) {
  1560. if (next) { next(); }
  1561. } else {
  1562. refreshDynamicOpml(categories, categories_count, next);
  1563. }
  1564. };
  1565. req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
  1566. req.send(JSON.stringify({
  1567. _csrf: context.csrf,
  1568. noCommit: 1,
  1569. }));
  1570. }
  1571. function refreshDynamicOpmls(json, next) {
  1572. categories_processed = 0;
  1573. if (json.categories && json.categories.length > 0) {
  1574. const categories_count = json.categories.length;
  1575. for (let i = context.nb_parallel_refresh; i > 0; i--) {
  1576. refreshDynamicOpml(json.categories, categories_count, next);
  1577. }
  1578. } else {
  1579. if (next) { next(); }
  1580. }
  1581. }
  1582. function init_actualize() {
  1583. let auto = false;
  1584. let nbCategoriesFirstRound = 0;
  1585. let skipCategories = false;
  1586. const actualize = document.getElementById('actualize');
  1587. if (!actualize) {
  1588. return;
  1589. }
  1590. actualize.onclick = function () {
  1591. if (context.ajax_loading) {
  1592. return false;
  1593. }
  1594. context.ajax_loading = true;
  1595. const req = new XMLHttpRequest();
  1596. req.open('POST', './?c=javascript&a=actualize', true);
  1597. req.responseType = 'json';
  1598. req.onload = function (e) {
  1599. if (this.status != 200) {
  1600. return badAjax(false);
  1601. }
  1602. const json = xmlHttpRequestJson(this);
  1603. if (!json) {
  1604. return badAjax(false);
  1605. }
  1606. if (auto && json.categories.length < 1 && json.feeds.length < 1) {
  1607. auto = false;
  1608. context.ajax_loading = false;
  1609. return false;
  1610. }
  1611. to_process = json.categories.length + json.feeds.length + nbCategoriesFirstRound;
  1612. if (json.categories.length + json.feeds.length > 0 && !document.getElementById('actualizeProgress')) {
  1613. document.body.insertAdjacentHTML('beforeend', '<div id="actualizeProgress" class="notification good">' +
  1614. json.feedback_actualize + '<br /><span class="title">/</span><br /><span class="progress">0 / ' +
  1615. to_process + '</span></div>');
  1616. } else {
  1617. openNotification(json.feedback_no_refresh, 'good');
  1618. }
  1619. if (json.categories.length > 0 && !skipCategories) {
  1620. skipCategories = true; // To avoid risk of infinite loop
  1621. nbCategoriesFirstRound = json.categories.length;
  1622. // If some dynamic OPML categories are refreshed, need to reload the list of feeds before updating them
  1623. refreshDynamicOpmls(json, () => {
  1624. context.ajax_loading = false;
  1625. actualize.click();
  1626. });
  1627. } else {
  1628. refreshFeeds(json);
  1629. }
  1630. };
  1631. req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
  1632. req.send(JSON.stringify({
  1633. _csrf: context.csrf,
  1634. }));
  1635. return false;
  1636. };
  1637. if (context.auto_actualize_feeds) {
  1638. auto = true;
  1639. actualize.click();
  1640. }
  1641. }
  1642. // </actualize>
  1643. // <notification>
  1644. let notification = null;
  1645. let notification_interval = null;
  1646. let notification_working = false;
  1647. function openNotification(msg, status) {
  1648. if (notification_working === true) {
  1649. return false;
  1650. }
  1651. notification_working = true;
  1652. notification.querySelector('.msg').innerHTML = msg;
  1653. notification.className = 'notification';
  1654. notification.classList.add(status);
  1655. if (status == 'good') {
  1656. notification_interval = setTimeout(closeNotification, 4000);
  1657. } else {
  1658. // no status or f.e. status = 'bad', give some more time to read
  1659. notification_interval = setTimeout(closeNotification, 8000);
  1660. }
  1661. }
  1662. function closeNotification() {
  1663. notification.classList.add('closed');
  1664. clearInterval(notification_interval);
  1665. notification_working = false;
  1666. }
  1667. function init_notifications() {
  1668. notification = document.getElementById('notification');
  1669. notification.querySelector('.close').addEventListener('click', function (ev) {
  1670. closeNotification();
  1671. ev.preventDefault();
  1672. return false;
  1673. });
  1674. notification.addEventListener('mouseenter', function () {
  1675. clearInterval(notification_interval);
  1676. });
  1677. notification.addEventListener('mouseleave', function () {
  1678. notification_interval = setTimeout(closeNotification, 3000);
  1679. });
  1680. if (notification.querySelector('.msg').innerHTML.length > 0) {
  1681. notification_working = true;
  1682. if (notification.classList.contains('good')) {
  1683. notification_interval = setTimeout(closeNotification, 4000);
  1684. } else {
  1685. // no status or f.e. status = 'bad', give some more time to read
  1686. notification_interval = setTimeout(closeNotification, 8000);
  1687. }
  1688. }
  1689. }
  1690. // </notification>
  1691. // <notifs html5>
  1692. let notifs_html5_permission = 'denied';
  1693. function notifs_html5_is_supported() {
  1694. return window.Notification !== undefined;
  1695. }
  1696. function notifs_html5_ask_permission() {
  1697. try {
  1698. window.Notification.requestPermission(function () {
  1699. notifs_html5_permission = window.Notification.permission;
  1700. });
  1701. } catch (e) {
  1702. }
  1703. }
  1704. function notifs_html5_show(nb, nb_new) {
  1705. if (notifs_html5_permission !== 'granted') {
  1706. return;
  1707. }
  1708. try {
  1709. const notification = new window.Notification(context.i18n.notif_title_articles, {
  1710. icon: '../themes/icons/favicon-256-padding.png',
  1711. body: context.i18n.notif_body_new_articles.replace('%%d', nb_new) + ' ' + context.i18n.notif_body_unread_articles.replace('%%d', nb),
  1712. tag: 'freshRssNewArticles',
  1713. });
  1714. notification.onclick = function () {
  1715. delayedFunction(function () {
  1716. location.reload();
  1717. window.focus();
  1718. notification.close();
  1719. });
  1720. };
  1721. if (context.html5_notif_timeout !== 0) {
  1722. setTimeout(function () {
  1723. notification.close();
  1724. }, context.html5_notif_timeout * 1000);
  1725. }
  1726. } catch (e) {
  1727. }
  1728. }
  1729. function init_notifs_html5() {
  1730. if (!notifs_html5_is_supported()) {
  1731. return;
  1732. }
  1733. notifs_html5_permission = notifs_html5_ask_permission();
  1734. }
  1735. // </notifs html5>
  1736. function refreshUnreads() {
  1737. const req = new XMLHttpRequest();
  1738. req.open('GET', './?c=javascript&a=nbUnreadsPerFeed', true);
  1739. req.responseType = 'json';
  1740. req.onload = function (e) {
  1741. const json = xmlHttpRequestJson(this);
  1742. if (!json) {
  1743. return badAjax(false);
  1744. }
  1745. const isAll = document.querySelector('.category.all.active');
  1746. let new_articles = false;
  1747. let nbUnreadFeeds = 0;
  1748. const title = document.querySelector('.category.all .title');
  1749. const nb_unreads_before = title ? str2int(title.getAttribute('data-unread')) : 0;
  1750. Object.keys(json.feeds).forEach(function (feed_id) {
  1751. const nbUnreads = json.feeds[feed_id];
  1752. nbUnreadFeeds += nbUnreads;
  1753. feed_id = 'f_' + feed_id;
  1754. const elem = document.getElementById(feed_id);
  1755. const feed_unreads = elem ? str2int(elem.getAttribute('data-unread')) : 0;
  1756. if ((incUnreadsFeed(null, feed_id, nbUnreads - feed_unreads) || isAll) && // Update of current view?
  1757. (nbUnreads - feed_unreads > 0)) {
  1758. const newArticle = document.getElementById('new-article');
  1759. newArticle.removeAttribute('hidden');
  1760. newArticle.style.display = 'block';
  1761. new_articles = true;
  1762. }
  1763. });
  1764. const noArticlesToShow_div = document.getElementById('noArticlesToShow');
  1765. if (nbUnreadFeeds > 0 && noArticlesToShow_div) {
  1766. noArticlesToShow_div.classList.add('hide');
  1767. }
  1768. let nbUnreadTags = 0;
  1769. Object.keys(json.tags).forEach(function (tag_id) {
  1770. const nbUnreads = json.tags[tag_id];
  1771. nbUnreadTags += nbUnreads;
  1772. const tag = document.getElementById('t_' + tag_id);
  1773. if (tag) {
  1774. tag.setAttribute('data-unread', nbUnreads);
  1775. tag.querySelector('.item-title').setAttribute('data-unread', numberFormat(nbUnreads));
  1776. }
  1777. });
  1778. const tags = document.querySelector('.category.tags');
  1779. if (tags) {
  1780. tags.setAttribute('data-unread', nbUnreadTags);
  1781. tags.querySelector('.title').setAttribute('data-unread', numberFormat(nbUnreadTags));
  1782. }
  1783. const nb_unreads = title ? str2int(title.getAttribute('data-unread')) : 0;
  1784. if (nb_unreads > 0 && new_articles) {
  1785. faviconNbUnread(nb_unreads);
  1786. const nb_new = nb_unreads - nb_unreads_before;
  1787. notifs_html5_show(nb_unreads, nb_new);
  1788. }
  1789. };
  1790. req.send();
  1791. }
  1792. function toggle_bigMarkAsRead_button() {
  1793. const bigMarkAsRead_button = document.getElementById('bigMarkAsRead');
  1794. if (bigMarkAsRead_button) {
  1795. if (document.querySelector('.flux.not_read') != null) {
  1796. bigMarkAsRead_button.style = '';
  1797. bigMarkAsRead_button.querySelector('.markAllRead').style.visibility = '';
  1798. } else {
  1799. if (bigMarkAsRead_button.querySelector('.jumpNext')) {
  1800. bigMarkAsRead_button.querySelector('.markAllRead').style.visibility = 'hidden';
  1801. } else {
  1802. bigMarkAsRead_button.querySelector('.markAllRead').style.visibility = '';
  1803. bigMarkAsRead_button.style.visibility = 'hidden';
  1804. }
  1805. }
  1806. }
  1807. }
  1808. // <endless_mode>
  1809. let url_load_more = '';
  1810. let load_more = false;
  1811. let box_load_more = null;
  1812. function remove_existing_posts() {
  1813. document.querySelectorAll('.flux, .day').forEach(function (div) {
  1814. div.remove();
  1815. });
  1816. }
  1817. function load_more_posts() {
  1818. if (load_more || !url_load_more || !box_load_more) {
  1819. return;
  1820. }
  1821. load_more = true;
  1822. document.getElementById('load_more').classList.add('loading');
  1823. const req = new XMLHttpRequest();
  1824. req.open('GET', url_load_more, true);
  1825. req.responseType = 'document';
  1826. req.onload = function (e) {
  1827. if (context.sort === 'rand') {
  1828. document.scrollingElement.scrollTop = 0;
  1829. remove_existing_posts();
  1830. }
  1831. const html = this.response;
  1832. const streamFooter = document.getElementById('stream-footer');
  1833. const streamAdopted = document.adoptNode(html.getElementById('stream'));
  1834. streamAdopted.querySelectorAll('.flux, .day').forEach(function (div) {
  1835. box_load_more.insertBefore(div, streamFooter);
  1836. });
  1837. const streamFooterOld = streamFooter.querySelector('.stream-footer-inner');
  1838. const streamFooterNew = streamAdopted.querySelector('.stream-footer-inner');
  1839. streamFooter.replaceChild(streamFooterNew, streamFooterOld);
  1840. const bigMarkAsRead = document.getElementById('bigMarkAsRead');
  1841. const readAll = document.querySelector('#nav_menu_read_all .read_all');
  1842. if (readAll && bigMarkAsRead && bigMarkAsRead.formAction) {
  1843. if (context.display_order === 'ASC') {
  1844. readAll.formAction = bigMarkAsRead.formAction;
  1845. } else {
  1846. bigMarkAsRead.formAction = readAll.formAction;
  1847. }
  1848. toggle_bigMarkAsRead_button();
  1849. }
  1850. document.querySelectorAll('[id^=day_]').forEach(function (div) {
  1851. const ids = document.querySelectorAll('[id="' + div.id + '"]');
  1852. for (let i = ids.length - 1; i > 0; i--) { // Keep only the first
  1853. ids[i].remove();
  1854. }
  1855. });
  1856. init_load_more(box_load_more);
  1857. const div_load_more = document.getElementById('load_more');
  1858. if (bigMarkAsRead) {
  1859. bigMarkAsRead.removeAttribute('disabled');
  1860. }
  1861. if (div_load_more) {
  1862. div_load_more.classList.remove('loading');
  1863. }
  1864. load_more = false;
  1865. };
  1866. req.send();
  1867. }
  1868. const freshrssLoadMoreEvent = document.createEvent('Event');
  1869. freshrssLoadMoreEvent.initEvent('freshrss:load-more', true, true);
  1870. function init_load_more(box) {
  1871. box_load_more = box;
  1872. document.body.dispatchEvent(freshrssLoadMoreEvent);
  1873. const next_button = document.getElementById('load_more');
  1874. if (!next_button) {
  1875. // no more article to load
  1876. url_load_more = '';
  1877. return;
  1878. }
  1879. url_load_more = next_button.getAttribute('formaction');
  1880. next_button.onclick = function (e) {
  1881. load_more_posts();
  1882. return false;
  1883. };
  1884. }
  1885. // </endless_mode>
  1886. function init_confirm_action() {
  1887. document.body.onclick = function (ev) {
  1888. const b = ev.target.closest('.confirm');
  1889. if (b) {
  1890. let str_confirmation = this.getAttribute('data-str-confirm');
  1891. if (!str_confirmation) {
  1892. str_confirmation = context.i18n.confirmation_default;
  1893. }
  1894. return confirm(str_confirmation);
  1895. }
  1896. };
  1897. const slider = document.getElementById('slider');
  1898. if (slider) {
  1899. slider.addEventListener('freshrss:slider-load', function (e) {
  1900. slider.querySelectorAll('button.confirm').forEach(function (b) { b.disabled = false; });
  1901. });
  1902. }
  1903. document.querySelectorAll('button.confirm').forEach(function (b) { b.disabled = false; });
  1904. }
  1905. function faviconNbUnread(n) {
  1906. if (typeof n === 'undefined') {
  1907. const t = document.querySelector('.category.all .title');
  1908. n = t ? str2int(t.getAttribute('data-unread')) : 0;
  1909. }
  1910. // http://remysharp.com/2010/08/24/dynamic-favicons/
  1911. const canvas = document.createElement('canvas');
  1912. const link = document.getElementById('favicon').cloneNode(true);
  1913. const ratio = window.devicePixelRatio;
  1914. if (canvas.getContext && link) {
  1915. canvas.height = canvas.width = 16 * ratio;
  1916. const img = document.createElement('img');
  1917. img.onload = function () {
  1918. const ctx = canvas.getContext('2d');
  1919. ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
  1920. if (n > 0) {
  1921. let text = '';
  1922. if (n < 1000) {
  1923. text = n;
  1924. } else if (n < 100000) {
  1925. text = Math.floor(n / 1000) + 'k';
  1926. } else {
  1927. text = 'E' + Math.floor(Math.log10(n));
  1928. }
  1929. ctx.font = 'bold ' + 9 * ratio + 'px "Arial", sans-serif';
  1930. ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
  1931. ctx.fillRect(0, 7 * ratio, ctx.measureText(text).width, 9 * ratio);
  1932. ctx.fillStyle = '#F00';
  1933. ctx.fillText(text, 0, canvas.height - 1);
  1934. }
  1935. link.href = canvas.toDataURL('image/png');
  1936. // Check if data URI has generated a real favicon and if not, fallback to standard icon
  1937. if (link.href.length > 180) {
  1938. document.querySelector('link[rel~=icon]').remove();
  1939. document.head.appendChild(link);
  1940. }
  1941. };
  1942. img.src = '../favicon.ico';
  1943. }
  1944. }
  1945. function removeFirstLoadSpinner() {
  1946. const first_load = document.getElementById('first_load');
  1947. if (first_load) {
  1948. first_load.remove();
  1949. }
  1950. }
  1951. function init_normal() {
  1952. const stream = document.getElementById('stream');
  1953. if (!stream) {
  1954. if (window.console) {
  1955. console.log('FreshRSS waiting for content…');
  1956. }
  1957. setTimeout(init_normal, 100);
  1958. return;
  1959. }
  1960. init_column_categories();
  1961. init_stream(stream);
  1962. init_actualize();
  1963. faviconNbUnread();
  1964. document.addEventListener("visibilitychange", () => {
  1965. if (document.visibilityState === "hidden") {
  1966. const sidebar = document.getElementById('sidebar');
  1967. if (sidebar) { // Save sidebar scroll position
  1968. sessionStorage.setItem('FreshRSS_sidebar_scrollTop', sidebar.scrollTop);
  1969. }
  1970. if (mark_read_queue && mark_read_queue.length > 0) {
  1971. clearTimeout(send_mark_read_queue_timeout);
  1972. send_mark_queue_tick(null);
  1973. }
  1974. }
  1975. });
  1976. }
  1977. function init_csp_alert() {
  1978. if (!context.admin || context.suppress_csp_warning) {
  1979. return;
  1980. }
  1981. try {
  1982. // eslint-disable-next-line no-new-func
  1983. Function();
  1984. } catch (_) {
  1985. // Exit if 'script-src' is set and 'unsafe-eval' isn't set in CSP
  1986. return;
  1987. }
  1988. document.body.insertAdjacentHTML('afterbegin', `
  1989. <div class="alert alert-error">
  1990. <span>${context.i18n.unsafe_csp_header}</span>
  1991. </div>
  1992. `);
  1993. }
  1994. function init_main_beforeDOM() {
  1995. history.scrollRestoration = 'manual';
  1996. document.scrollingElement.scrollTop = 0;
  1997. init_shortcuts();
  1998. if (['normal', 'reader', 'global'].indexOf(context.current_view) >= 0) {
  1999. init_normal();
  2000. }
  2001. }
  2002. function init_main_afterDOM() {
  2003. removeFirstLoadSpinner();
  2004. init_notifications();
  2005. init_csp_alert();
  2006. init_confirm_action();
  2007. const stream = document.getElementById('stream');
  2008. if (stream) {
  2009. init_load_more(stream);
  2010. init_posts();
  2011. if (document.getElementById('new-article')) {
  2012. // Only relevant for interactive views
  2013. init_nav_entries();
  2014. init_notifs_html5();
  2015. toggle_bigMarkAsRead_button();
  2016. setTimeout(faviconNbUnread, 1000);
  2017. setInterval(refreshUnreads, 120000);
  2018. }
  2019. }
  2020. if (window.console) {
  2021. console.log('FreshRSS main init done.');
  2022. }
  2023. }
  2024. init_main_beforeDOM(); // Can be called before DOM is fully loaded
  2025. if (document.readyState && document.readyState !== 'loading') {
  2026. init_main_afterDOM();
  2027. } else {
  2028. if (window.console) {
  2029. console.log('FreshRSS waiting for DOMContentLoaded…');
  2030. }
  2031. document.addEventListener('DOMContentLoaded', init_main_afterDOM, false);
  2032. }
  2033. // @license-end