main.js 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247
  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]').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) {
  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) {
  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. if (k === s.skip_next_entry) { next_entry(true); ev.preventDefault(); return; }
  1087. if (k === s.skip_prev_entry) { prev_entry(true); ev.preventDefault(); return; }
  1088. if (k === s.collapse_entry) { collapse_entry(); ev.preventDefault(); return; }
  1089. if (k === s.mylabels) { mylabels(); ev.preventDefault(); return; }
  1090. if (k === s.auto_share) { auto_share(); ev.preventDefault(); return; }
  1091. if (k === s.user_filter) { user_filter(); ev.preventDefault(); return; }
  1092. if (k === s.load_more) { load_more_posts(); ev.preventDefault(); return; }
  1093. if (k === s.close_dropdown) { location.hash = null; ev.preventDefault(); return; }
  1094. if (k === s.help) { window.open(context.urls.help); ev.preventDefault(); return; }
  1095. if (k === s.focus_search) { document.getElementById('search').focus(); ev.preventDefault(); return; }
  1096. if (k === s.normal_view) { delayedClick(document.querySelector('#nav_menu_views .view-normal')); ev.preventDefault(); return; }
  1097. if (k === s.reading_view) { delayedClick(document.querySelector('#nav_menu_views .view-reader')); ev.preventDefault(); return; }
  1098. if (k === s.global_view) { delayedClick(document.querySelector('#nav_menu_views .view-global')); ev.preventDefault(); return; }
  1099. if (k === s.toggle_media) { toggle_media(); ev.preventDefault(); }
  1100. });
  1101. }
  1102. function init_stream(stream) {
  1103. stream.onclick = function (ev) {
  1104. let el = ev.target.closest('.flux a.read');
  1105. if (el) {
  1106. mark_read(el.closest('.flux'), false, false);
  1107. return false;
  1108. }
  1109. el = ev.target.closest('.flux a.bookmark');
  1110. if (el) {
  1111. mark_favorite(el.closest('.flux'));
  1112. return false;
  1113. }
  1114. el = ev.target.closest('.item a.title');
  1115. if (el) { // Allow default control/command-click behaviour such as open in background-tab
  1116. return ev.ctrlKey || ev.metaKey;
  1117. }
  1118. el = ev.target.closest('.flux .content .text a');
  1119. if (el) {
  1120. if (!el.closest('div').classList.contains('author')) {
  1121. el.target = '_blank';
  1122. el.rel = 'noreferrer';
  1123. }
  1124. return true;
  1125. }
  1126. el = ev.target.closest('.item.labels a.dropdown-toggle');
  1127. if (el) {
  1128. return show_labels_menu(el);
  1129. }
  1130. el = ev.target.closest('.item.share a.dropdown-toggle');
  1131. if (el) {
  1132. return show_share_menu(el);
  1133. }
  1134. el = ev.target.closest('.item.share > button[data-type="print"]');
  1135. if (el) { // Print
  1136. const html = document.documentElement;
  1137. const head = document.head.cloneNode(true);
  1138. head.querySelectorAll('script').forEach(js => js.remove());
  1139. const flux_content = el.closest('.flux_content');
  1140. let content_el = null;
  1141. if (flux_content) {
  1142. content_el = el.closest('.flux_content').querySelector('.content').cloneNode(true);
  1143. }
  1144. if (content_el === null) {
  1145. content_el = el.closest('.flux').querySelector('.flux_content .content').cloneNode(true);
  1146. }
  1147. content_el.querySelectorAll('a').forEach(link => {
  1148. // Avoid leaking the instance URL in PDFs
  1149. if (link.href.startsWith(location.origin)) {
  1150. link.removeAttribute('href');
  1151. }
  1152. });
  1153. content_el.querySelectorAll('details').forEach(el => el.setAttribute('open', 'open'));
  1154. const articleTitle = content_el.querySelector('.title a').innerText;
  1155. prevTitle = document.title;
  1156. // Chrome uses the parent's title to get the PDF save filename
  1157. document.title = articleTitle;
  1158. // Firefox uses the iframe's title to get the PDF save filename
  1159. // Note: Firefox Mobile saves PDFs with a filename that looks like: `temp[19 random digits].PDF` regardless of title
  1160. head.querySelector('title').innerText = articleTitle;
  1161. loadLazyImages(content_el);
  1162. const print_frame = document.createElement('iframe');
  1163. print_frame.style.display = 'none';
  1164. print_frame.srcdoc = `
  1165. <!DOCTYPE html>
  1166. <html class="${html.getAttribute('class')}">
  1167. <head>
  1168. ${head.innerHTML}
  1169. </head>
  1170. <body>
  1171. ${content_el.outerHTML}
  1172. </body>
  1173. </html>
  1174. `;
  1175. document.body.prepend(print_frame);
  1176. function afterPrint() {
  1177. print_frame.remove();
  1178. document.title = prevTitle;
  1179. prevTitle = '';
  1180. window.removeEventListener('focus', afterPrint);
  1181. }
  1182. print_frame.onload = () => {
  1183. const tmp_window = print_frame.contentWindow;
  1184. // Needed for Chrome
  1185. tmp_window.matchMedia('print').onchange = (e) => {
  1186. // UA check is needed to not trigger on Chrome Mobile
  1187. if (!e.matches && !navigator.userAgent.includes('Mobi')) {
  1188. afterPrint();
  1189. }
  1190. };
  1191. tmp_window.print();
  1192. };
  1193. // Needed for Firefox and Chrome Mobile
  1194. window.addEventListener('focus', afterPrint);
  1195. return false;
  1196. }
  1197. el = ev.target.closest('.item.share > button[data-type="clipboard"]');
  1198. if (el) { // Clipboard
  1199. if (navigator.clipboard) {
  1200. navigator.clipboard.writeText(el.dataset.url)
  1201. .then(() => {
  1202. toggleClass(el, 'ok');
  1203. })
  1204. .catch(e => {
  1205. console.log(e);
  1206. toggleClass(el, 'error');
  1207. });
  1208. } else {
  1209. // fallback, if navigator.clipboard is not available f.e. if access is not via https or localhost
  1210. const inputElement = document.createElement('input');
  1211. inputElement.value = el.dataset.url;
  1212. document.body.appendChild(inputElement);
  1213. inputElement.select();
  1214. if (document.execCommand && document.execCommand('copy')) {
  1215. toggleClass(el, 'ok');
  1216. } else {
  1217. console.log('document.execCommand("copy") failed');
  1218. toggleClass(el, 'error');
  1219. }
  1220. inputElement.remove();
  1221. }
  1222. return false;
  1223. }
  1224. el = ev.target.closest('.item.share > button[data-type="web-sharing-api"]');
  1225. if (el && navigator.share) { // https://developer.mozilla.org/en-US/docs/Web/API/Navigator/share
  1226. const shareData = {
  1227. url: el.dataset.url,
  1228. title: decodeURI(el.dataset.title),
  1229. };
  1230. navigator.share(shareData);
  1231. return false;
  1232. }
  1233. el = ev.target.closest('.item.share > a[data-type="email-webmail-firefox-fix"]');
  1234. if (el) {
  1235. window.open(el.href);
  1236. return false;
  1237. }
  1238. el = ev.target.closest('.item.share > a[href="POST"]');
  1239. if (el) { // Share by POST
  1240. const f = el.parentElement.querySelector('form');
  1241. f.disabled = false;
  1242. f.submit();
  1243. return false;
  1244. }
  1245. el = ev.target.closest('.flux_header, .flux_content');
  1246. if (el) { // flux_toggle
  1247. if (ev.target.closest('.reader, .content, .item.website, .item.link, .dropdown')) {
  1248. return true;
  1249. }
  1250. if ((!context.sides_close_article && ev.target.matches('.flux_content')) || ev.target.closest('footer')) {
  1251. // setting for not-closing after clicking outside article area
  1252. return false;
  1253. }
  1254. const old_active = document.querySelector('.flux.current');
  1255. const new_active = el.parentNode;
  1256. if (ev.target.tagName.toUpperCase() === 'A') { // Leave real links alone (but does not catch img in a link)
  1257. if (context.auto_mark_article) {
  1258. mark_read(new_active, true, false);
  1259. }
  1260. return true;
  1261. }
  1262. toggleContent(new_active, old_active, false);
  1263. return false;
  1264. }
  1265. };
  1266. stream.onmouseup = function (ev) { // Mouseup enables us to catch middle click, and control+click in IE/Edge
  1267. if (ev.altKey || ev.metaKey || ev.shiftKey) {
  1268. return;
  1269. }
  1270. let el = ev.target.closest('.item a.title');
  1271. if (el) {
  1272. if (ev.which == 1) {
  1273. if (ev.ctrlKey) { // Control+click
  1274. if (context.auto_mark_site) {
  1275. mark_read(el.closest('.flux'), true, false);
  1276. }
  1277. } else {
  1278. el.parentElement.click(); // Normal click, just toggle article.
  1279. }
  1280. } else if (ev.which == 2 && !ev.ctrlKey) { // Simple middle click: same behaviour as CTRL+click
  1281. if (context.auto_mark_article) {
  1282. const new_active = el.closest('.flux');
  1283. mark_read(new_active, true, false);
  1284. }
  1285. }
  1286. return;
  1287. }
  1288. if (context.auto_mark_site) {
  1289. // catch mouseup instead of click so we can have the correct behaviour
  1290. // with middle button click (scroll button).
  1291. el = ev.target.closest('.flux .link > a');
  1292. if (el) {
  1293. if (ev.which == 3) {
  1294. return;
  1295. }
  1296. mark_read(el.closest('.flux'), true, false);
  1297. }
  1298. }
  1299. };
  1300. stream.onchange = function (ev) {
  1301. const checkboxTag = ev.target.closest('.checkboxTag');
  1302. if (checkboxTag) { // Dynamic tags
  1303. ev.stopPropagation();
  1304. const tagId = checkboxTag.name.replace(/^t_/, '');
  1305. const tagName = checkboxTag.nextElementSibling ? checkboxTag.nextElementSibling.childNodes[0].value : '';
  1306. if ((tagId == 0 && tagName.length > 0) || tagId != 0) {
  1307. const isChecked = checkboxTag.checked;
  1308. const entry = checkboxTag.closest('div.flux');
  1309. const entryId = entry.id.replace(/^flux_/, '');
  1310. checkboxTag.disabled = true;
  1311. const req = new XMLHttpRequest();
  1312. req.open('POST', './?c=tag&a=tagEntry&ajax=1', true);
  1313. req.responseType = 'json';
  1314. req.onerror = function (e) {
  1315. checkboxTag.checked = !isChecked;
  1316. badAjax(this.status == 403);
  1317. };
  1318. req.onload = function (e) {
  1319. if (this.status != 200) {
  1320. return req.onerror(e);
  1321. }
  1322. if (entry.classList.contains('not_read')) {
  1323. incUnreadsTag('t_' + tagId, isChecked ? 1 : -1);
  1324. }
  1325. };
  1326. req.onloadend = function (e) {
  1327. checkboxTag.disabled = false;
  1328. if (tagId == 0) {
  1329. // new tag is added
  1330. forceReloadLabelsList = true;
  1331. loadDynamicTags(checkboxTag.closest('div.dropdown'));
  1332. } else {
  1333. // a tag was (un)checked
  1334. const dropdownmenu_current = ev.target.closest('.dropdown-menu');
  1335. const flux = ev.target.closest('.flux');
  1336. const dropdownmenu_all = flux.querySelectorAll('.dynamictags .dropdown-menu');
  1337. if (dropdownmenu_all.length > 1) {
  1338. // delete all other tag dropdown menus except the current one
  1339. dropdownmenu_all.forEach(
  1340. function (currentValue) {
  1341. if (currentValue !== dropdownmenu_current) {
  1342. currentValue.nextElementSibling.remove();
  1343. currentValue.parentNode.removeChild(currentValue);
  1344. }
  1345. }
  1346. );
  1347. }
  1348. }
  1349. };
  1350. req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
  1351. req.send(JSON.stringify({
  1352. _csrf: context.csrf,
  1353. id_tag: tagId,
  1354. name_tag: tagId == 0 ? tagName : '',
  1355. id_entry: entryId,
  1356. checked: isChecked,
  1357. ajax: 1,
  1358. }));
  1359. }
  1360. }
  1361. };
  1362. }
  1363. function toggleClass(el, cssclass) {
  1364. el.classList.remove(cssclass);
  1365. el.dataset.foo = el.offsetWidth; // it does nothing, but it is needed. See https://github.com/FreshRSS/FreshRSS/pull/5295
  1366. el.classList.add(cssclass);
  1367. }
  1368. function init_nav_entries() {
  1369. const nav_entries = document.getElementById('nav_entries');
  1370. if (nav_entries) {
  1371. nav_entries.querySelector('.previous_entry').onclick = function (e) {
  1372. prev_entry(false);
  1373. return false;
  1374. };
  1375. nav_entries.querySelector('.next_entry').onclick = function (e) {
  1376. next_entry(false);
  1377. return false;
  1378. };
  1379. nav_entries.querySelector('.up').onclick = function (e) {
  1380. const active_item = (document.querySelector('.flux.current') || document.querySelector('.flux'));
  1381. const windowTop = document.scrollingElement.scrollTop;
  1382. const item_top = active_item.offsetParent.offsetTop + active_item.offsetTop;
  1383. const nav_menu = document.querySelector('.nav_menu');
  1384. let nav_menu_height = 0;
  1385. if (getComputedStyle(nav_menu).position === 'fixed' || getComputedStyle(nav_menu).position === 'sticky') {
  1386. nav_menu_height = nav_menu.offsetHeight;
  1387. }
  1388. document.scrollingElement.scrollTop = windowTop > item_top ? item_top - nav_menu_height : 0 - nav_menu_height;
  1389. return false;
  1390. };
  1391. }
  1392. }
  1393. // forceReloadLabelsList default is false, so that the list does need a reload after opening it a second time.
  1394. // will be set to true, if a new tag is added. Then the labels list will be reloaded each opening.
  1395. // purpose of this flag: minimize the network traffic.
  1396. let forceReloadLabelsList = false;
  1397. function loadDynamicTags(div) {
  1398. div.querySelectorAll('li.item').forEach(function (li) { li.remove(); });
  1399. const entryId = div.closest('div.flux').id.replace(/^flux_/, '');
  1400. const req = new XMLHttpRequest();
  1401. req.open('GET', './?c=tag&a=getTagsForEntry&id_entry=' + entryId, true);
  1402. req.responseType = 'json';
  1403. req.onerror = function (e) {
  1404. div.querySelectorAll('li.item').forEach(function (li) { li.remove(); });
  1405. };
  1406. req.onload = function (e) {
  1407. if (this.status != 200) {
  1408. return req.onerror(e);
  1409. }
  1410. const json = xmlHttpRequestJson(this);
  1411. if (!json) {
  1412. return req.onerror(e);
  1413. }
  1414. if (!context.anonymous) {
  1415. const li_item0 = document.createElement('li');
  1416. li_item0.setAttribute('class', 'item addItem');
  1417. const label = document.createElement('label');
  1418. label.setAttribute('class', 'noHover');
  1419. const input_checkboxTag = document.createElement('input');
  1420. input_checkboxTag.setAttribute('class', 'checkboxTag checkboxNewTag');
  1421. input_checkboxTag.setAttribute('name', 't_0');
  1422. input_checkboxTag.setAttribute('type', 'checkbox');
  1423. const input_newTag = document.createElement('input');
  1424. input_newTag.setAttribute('type', 'text');
  1425. input_newTag.setAttribute('name', 'newTag');
  1426. input_newTag.setAttribute('class', 'newTag');
  1427. input_newTag.setAttribute('list', 'datalist-labels');
  1428. input_newTag.addEventListener('keydown', function (ev) { if (ev.key.toUpperCase() == 'ENTER') { this.parentNode.previousSibling.click(); } });
  1429. const button_btn = document.createElement('button');
  1430. button_btn.setAttribute('type', 'button');
  1431. button_btn.setAttribute('class', 'btn');
  1432. button_btn.addEventListener('click', function () { this.parentNode.parentNode.click(); });
  1433. const text_plus = document.createTextNode('+');
  1434. const div_stick = document.createElement('div');
  1435. div_stick.setAttribute('class', 'stick');
  1436. button_btn.appendChild(text_plus);
  1437. div_stick.appendChild(input_newTag);
  1438. div_stick.appendChild(button_btn);
  1439. label.appendChild(input_checkboxTag);
  1440. label.appendChild(div_stick);
  1441. li_item0.appendChild(label);
  1442. div.querySelector('.dropdown-menu-scrollable').appendChild(li_item0);
  1443. }
  1444. let html = '';
  1445. let datalist = '';
  1446. if (json && json.length) {
  1447. let nbLabelsChecked = 0;
  1448. for (let i = 0; i < json.length; i++) {
  1449. const tag = json[i];
  1450. if (context.anonymous && !tag.checked) {
  1451. // In anomymous mode, show only the used tags
  1452. continue;
  1453. }
  1454. if (tag.checked) {
  1455. nbLabelsChecked++;
  1456. }
  1457. html += '<li class="item"><label><input ' +
  1458. (context.anonymous ? '' : 'class="checkboxTag" ') +
  1459. 'name="t_' + tag.id + '"type="checkbox" ' +
  1460. (context.anonymous ? 'disabled="disabled" ' : '') +
  1461. (tag.checked ? 'checked="checked" ' : '') + '/>' + tag.name + '</label></li>';
  1462. datalist += '<option value="' + tag.name + '"></option>';
  1463. }
  1464. if (context.anonymous && nbLabelsChecked === 0) {
  1465. html += '<li class="item"><span class="emptyLabels">' + context.i18n.labels_empty + '</span></li>';
  1466. }
  1467. }
  1468. div.querySelector('.dropdown-menu-scrollable').insertAdjacentHTML('beforeend', html);
  1469. const datalistLabels = document.getElementById('datalist-labels');
  1470. datalistLabels.innerHTML = ''; // clear before add the (updated) labels list
  1471. datalistLabels.insertAdjacentHTML('beforeend', datalist);
  1472. };
  1473. req.send();
  1474. }
  1475. // <actualize>
  1476. let feeds_processed = 0;
  1477. let categories_processed = 0;
  1478. let to_process = 0;
  1479. function refreshFeed(feeds, feeds_count) {
  1480. const feed = feeds.pop();
  1481. if (!feed) {
  1482. return;
  1483. }
  1484. const req = new XMLHttpRequest();
  1485. req.open('POST', feed.url, true);
  1486. req.onloadend = function (e) {
  1487. feeds_processed++;
  1488. if (this.status != 200) {
  1489. badAjax(false);
  1490. } else {
  1491. const div = document.getElementById('actualizeProgress');
  1492. div.querySelector('.progress').innerHTML = (categories_processed + feeds_processed) + ' / ' + to_process;
  1493. div.querySelector('.title').innerHTML = feed.title;
  1494. }
  1495. if (feeds_processed === feeds_count) {
  1496. // Empty request to commit new articles
  1497. const req2 = new XMLHttpRequest();
  1498. req2.open('POST', './?c=feed&a=actualize&id=-1&ajax=1', true);
  1499. req2.onloadend = function (e) {
  1500. delayedFunction(function () { location.reload(); });
  1501. };
  1502. req2.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
  1503. req2.send(JSON.stringify({
  1504. _csrf: context.csrf,
  1505. noCommit: 0,
  1506. }));
  1507. } else {
  1508. refreshFeed(feeds, feeds_count);
  1509. }
  1510. };
  1511. req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
  1512. req.send(JSON.stringify({
  1513. _csrf: context.csrf,
  1514. noCommit: 1,
  1515. }));
  1516. }
  1517. function refreshFeeds(json) {
  1518. feeds_processed = 0;
  1519. if (!json.feeds || json.feeds.length === 0) {
  1520. // Empty request to commit new articles
  1521. const req2 = new XMLHttpRequest();
  1522. req2.open('POST', './?c=feed&a=actualize&id=-1&ajax=1', true);
  1523. req2.onloadend = function (e) {
  1524. context.ajax_loading = false;
  1525. };
  1526. req2.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
  1527. req2.send(JSON.stringify({
  1528. _csrf: context.csrf,
  1529. noCommit: 0,
  1530. }));
  1531. } else {
  1532. const feeds_count = json.feeds.length;
  1533. for (let i = context.nb_parallel_refresh; i > 0; i--) {
  1534. refreshFeed(json.feeds, feeds_count);
  1535. }
  1536. }
  1537. }
  1538. function refreshDynamicOpml(categories, categories_count, next) {
  1539. const category = categories.pop();
  1540. if (!category) {
  1541. return;
  1542. }
  1543. const req = new XMLHttpRequest();
  1544. req.open('POST', category.url, true);
  1545. req.onloadend = function (e) {
  1546. categories_processed++;
  1547. if (this.status != 200) {
  1548. badAjax(false);
  1549. } else {
  1550. const div = document.getElementById('actualizeProgress');
  1551. div.querySelector('.progress').innerHTML = (categories_processed + feeds_processed) + ' / ' + to_process;
  1552. div.querySelector('.title').innerHTML = category.title;
  1553. }
  1554. if (categories_processed === categories_count) {
  1555. if (next) { next(); }
  1556. } else {
  1557. refreshDynamicOpml(categories, categories_count, next);
  1558. }
  1559. };
  1560. req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
  1561. req.send(JSON.stringify({
  1562. _csrf: context.csrf,
  1563. noCommit: 1,
  1564. }));
  1565. }
  1566. function refreshDynamicOpmls(json, next) {
  1567. categories_processed = 0;
  1568. if (json.categories && json.categories.length > 0) {
  1569. const categories_count = json.categories.length;
  1570. for (let i = context.nb_parallel_refresh; i > 0; i--) {
  1571. refreshDynamicOpml(json.categories, categories_count, next);
  1572. }
  1573. } else {
  1574. if (next) { next(); }
  1575. }
  1576. }
  1577. function init_actualize() {
  1578. let auto = false;
  1579. let nbCategoriesFirstRound = 0;
  1580. let skipCategories = false;
  1581. const actualize = document.getElementById('actualize');
  1582. if (!actualize) {
  1583. return;
  1584. }
  1585. actualize.onclick = function () {
  1586. if (context.ajax_loading) {
  1587. return false;
  1588. }
  1589. context.ajax_loading = true;
  1590. const req = new XMLHttpRequest();
  1591. req.open('POST', './?c=javascript&a=actualize', true);
  1592. req.responseType = 'json';
  1593. req.onload = function (e) {
  1594. if (this.status != 200) {
  1595. return badAjax(false);
  1596. }
  1597. const json = xmlHttpRequestJson(this);
  1598. if (!json) {
  1599. return badAjax(false);
  1600. }
  1601. if (auto && json.categories.length < 1 && json.feeds.length < 1) {
  1602. auto = false;
  1603. context.ajax_loading = false;
  1604. return false;
  1605. }
  1606. to_process = json.categories.length + json.feeds.length + nbCategoriesFirstRound;
  1607. if (json.categories.length + json.feeds.length > 0 && !document.getElementById('actualizeProgress')) {
  1608. document.body.insertAdjacentHTML('beforeend', '<div id="actualizeProgress" class="notification good">' +
  1609. json.feedback_actualize + '<br /><span class="title">/</span><br /><span class="progress">0 / ' +
  1610. to_process + '</span></div>');
  1611. } else {
  1612. openNotification(json.feedback_no_refresh, 'good');
  1613. }
  1614. if (json.categories.length > 0 && !skipCategories) {
  1615. skipCategories = true; // To avoid risk of infinite loop
  1616. nbCategoriesFirstRound = json.categories.length;
  1617. // If some dynamic OPML categories are refreshed, need to reload the list of feeds before updating them
  1618. refreshDynamicOpmls(json, () => {
  1619. context.ajax_loading = false;
  1620. actualize.click();
  1621. });
  1622. } else {
  1623. refreshFeeds(json);
  1624. }
  1625. };
  1626. req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
  1627. req.send(JSON.stringify({
  1628. _csrf: context.csrf,
  1629. }));
  1630. return false;
  1631. };
  1632. if (context.auto_actualize_feeds) {
  1633. auto = true;
  1634. actualize.click();
  1635. }
  1636. }
  1637. // </actualize>
  1638. // <notification>
  1639. let notification = null;
  1640. let notification_interval = null;
  1641. let notification_working = false;
  1642. function openNotification(msg, status) {
  1643. if (notification_working === true) {
  1644. return false;
  1645. }
  1646. notification_working = true;
  1647. notification.querySelector('.msg').innerHTML = msg;
  1648. notification.className = 'notification';
  1649. notification.classList.add(status);
  1650. if (status == 'good') {
  1651. notification_interval = setTimeout(closeNotification, 4000);
  1652. } else {
  1653. // no status or f.e. status = 'bad', give some more time to read
  1654. notification_interval = setTimeout(closeNotification, 8000);
  1655. }
  1656. }
  1657. function closeNotification() {
  1658. notification.classList.add('closed');
  1659. clearInterval(notification_interval);
  1660. notification_working = false;
  1661. }
  1662. function init_notifications() {
  1663. notification = document.getElementById('notification');
  1664. notification.querySelector('.close').addEventListener('click', function (ev) {
  1665. closeNotification();
  1666. ev.preventDefault();
  1667. return false;
  1668. });
  1669. notification.addEventListener('mouseenter', function () {
  1670. clearInterval(notification_interval);
  1671. });
  1672. notification.addEventListener('mouseleave', function () {
  1673. notification_interval = setTimeout(closeNotification, 3000);
  1674. });
  1675. if (notification.querySelector('.msg').innerHTML.length > 0) {
  1676. notification_working = true;
  1677. if (notification.classList.contains('good')) {
  1678. notification_interval = setTimeout(closeNotification, 4000);
  1679. } else {
  1680. // no status or f.e. status = 'bad', give some more time to read
  1681. notification_interval = setTimeout(closeNotification, 8000);
  1682. }
  1683. }
  1684. }
  1685. // </notification>
  1686. // <notifs html5>
  1687. let notifs_html5_permission = 'denied';
  1688. function notifs_html5_is_supported() {
  1689. return window.Notification !== undefined;
  1690. }
  1691. function notifs_html5_ask_permission() {
  1692. try {
  1693. window.Notification.requestPermission(function () {
  1694. notifs_html5_permission = window.Notification.permission;
  1695. });
  1696. } catch (e) {
  1697. }
  1698. }
  1699. function notifs_html5_show(nb, nb_new) {
  1700. if (notifs_html5_permission !== 'granted') {
  1701. return;
  1702. }
  1703. try {
  1704. const notification = new window.Notification(context.i18n.notif_title_articles, {
  1705. icon: '../themes/icons/favicon-256-padding.png',
  1706. body: context.i18n.notif_body_new_articles.replace('%%d', nb_new) + ' ' + context.i18n.notif_body_unread_articles.replace('%%d', nb),
  1707. tag: 'freshRssNewArticles',
  1708. });
  1709. notification.onclick = function () {
  1710. delayedFunction(function () {
  1711. location.reload();
  1712. window.focus();
  1713. notification.close();
  1714. });
  1715. };
  1716. if (context.html5_notif_timeout !== 0) {
  1717. setTimeout(function () {
  1718. notification.close();
  1719. }, context.html5_notif_timeout * 1000);
  1720. }
  1721. } catch (e) {
  1722. }
  1723. }
  1724. function init_notifs_html5() {
  1725. if (!notifs_html5_is_supported()) {
  1726. return;
  1727. }
  1728. notifs_html5_permission = notifs_html5_ask_permission();
  1729. }
  1730. // </notifs html5>
  1731. function refreshUnreads() {
  1732. const req = new XMLHttpRequest();
  1733. req.open('GET', './?c=javascript&a=nbUnreadsPerFeed', true);
  1734. req.responseType = 'json';
  1735. req.onload = function (e) {
  1736. const json = xmlHttpRequestJson(this);
  1737. if (!json) {
  1738. return badAjax(false);
  1739. }
  1740. const isAll = document.querySelector('.category.all.active');
  1741. let new_articles = false;
  1742. let nbUnreadFeeds = 0;
  1743. const title = document.querySelector('.category.all .title');
  1744. const nb_unreads_before = title ? str2int(title.getAttribute('data-unread')) : 0;
  1745. Object.keys(json.feeds).forEach(function (feed_id) {
  1746. const nbUnreads = json.feeds[feed_id];
  1747. nbUnreadFeeds += nbUnreads;
  1748. feed_id = 'f_' + feed_id;
  1749. const elem = document.getElementById(feed_id);
  1750. const feed_unreads = elem ? str2int(elem.getAttribute('data-unread')) : 0;
  1751. if ((incUnreadsFeed(null, feed_id, nbUnreads - feed_unreads) || isAll) && // Update of current view?
  1752. (nbUnreads - feed_unreads > 0)) {
  1753. const newArticle = document.getElementById('new-article');
  1754. newArticle.removeAttribute('hidden');
  1755. newArticle.style.display = 'block';
  1756. new_articles = true;
  1757. }
  1758. });
  1759. const noArticlesToShow_div = document.getElementById('noArticlesToShow');
  1760. if (nbUnreadFeeds > 0 && noArticlesToShow_div) {
  1761. noArticlesToShow_div.classList.add('hide');
  1762. }
  1763. let nbUnreadTags = 0;
  1764. Object.keys(json.tags).forEach(function (tag_id) {
  1765. const nbUnreads = json.tags[tag_id];
  1766. nbUnreadTags += nbUnreads;
  1767. const tag = document.getElementById('t_' + tag_id);
  1768. if (tag) {
  1769. tag.setAttribute('data-unread', nbUnreads);
  1770. tag.querySelector('.item-title').setAttribute('data-unread', numberFormat(nbUnreads));
  1771. }
  1772. });
  1773. const tags = document.querySelector('.category.tags');
  1774. if (tags) {
  1775. tags.setAttribute('data-unread', nbUnreadTags);
  1776. tags.querySelector('.title').setAttribute('data-unread', numberFormat(nbUnreadTags));
  1777. }
  1778. const nb_unreads = title ? str2int(title.getAttribute('data-unread')) : 0;
  1779. if (nb_unreads > 0 && new_articles) {
  1780. faviconNbUnread(nb_unreads);
  1781. const nb_new = nb_unreads - nb_unreads_before;
  1782. notifs_html5_show(nb_unreads, nb_new);
  1783. }
  1784. };
  1785. req.send();
  1786. }
  1787. function toggle_bigMarkAsRead_button() {
  1788. const bigMarkAsRead_button = document.getElementById('bigMarkAsRead');
  1789. if (bigMarkAsRead_button) {
  1790. if (document.querySelector('.flux.not_read') != null) {
  1791. bigMarkAsRead_button.style = '';
  1792. bigMarkAsRead_button.querySelector('.markAllRead').style.visibility = '';
  1793. } else {
  1794. if (bigMarkAsRead_button.querySelector('.jumpNext')) {
  1795. bigMarkAsRead_button.querySelector('.markAllRead').style.visibility = 'hidden';
  1796. } else {
  1797. bigMarkAsRead_button.querySelector('.markAllRead').style.visibility = '';
  1798. bigMarkAsRead_button.style.visibility = 'hidden';
  1799. }
  1800. }
  1801. }
  1802. }
  1803. // <endless_mode>
  1804. let url_load_more = '';
  1805. let load_more = false;
  1806. let box_load_more = null;
  1807. function remove_existing_posts() {
  1808. document.querySelectorAll('.flux, .day').forEach(function (div) {
  1809. div.remove();
  1810. });
  1811. }
  1812. function load_more_posts() {
  1813. if (load_more || !url_load_more || !box_load_more) {
  1814. return;
  1815. }
  1816. load_more = true;
  1817. document.getElementById('load_more').classList.add('loading');
  1818. const req = new XMLHttpRequest();
  1819. req.open('GET', url_load_more, true);
  1820. req.responseType = 'document';
  1821. req.onload = function (e) {
  1822. if (context.sort === 'rand') {
  1823. document.scrollingElement.scrollTop = 0;
  1824. remove_existing_posts();
  1825. }
  1826. const html = this.response;
  1827. const streamFooter = document.getElementById('stream-footer');
  1828. const streamAdopted = document.adoptNode(html.getElementById('stream'));
  1829. streamAdopted.querySelectorAll('.flux, .day').forEach(function (div) {
  1830. box_load_more.insertBefore(div, streamFooter);
  1831. });
  1832. const streamFooterOld = streamFooter.querySelector('.stream-footer-inner');
  1833. const streamFooterNew = streamAdopted.querySelector('.stream-footer-inner');
  1834. streamFooter.replaceChild(streamFooterNew, streamFooterOld);
  1835. const bigMarkAsRead = document.getElementById('bigMarkAsRead');
  1836. const readAll = document.querySelector('#nav_menu_read_all .read_all');
  1837. if (readAll && bigMarkAsRead && bigMarkAsRead.formAction) {
  1838. if (context.display_order === 'ASC') {
  1839. readAll.formAction = bigMarkAsRead.formAction;
  1840. } else {
  1841. bigMarkAsRead.formAction = readAll.formAction;
  1842. }
  1843. toggle_bigMarkAsRead_button();
  1844. }
  1845. document.querySelectorAll('[id^=day_]').forEach(function (div) {
  1846. const ids = document.querySelectorAll('[id="' + div.id + '"]');
  1847. for (let i = ids.length - 1; i > 0; i--) { // Keep only the first
  1848. ids[i].remove();
  1849. }
  1850. });
  1851. init_load_more(box_load_more);
  1852. const div_load_more = document.getElementById('load_more');
  1853. if (bigMarkAsRead) {
  1854. bigMarkAsRead.removeAttribute('disabled');
  1855. }
  1856. if (div_load_more) {
  1857. div_load_more.classList.remove('loading');
  1858. }
  1859. load_more = false;
  1860. };
  1861. req.send();
  1862. }
  1863. const freshrssLoadMoreEvent = document.createEvent('Event');
  1864. freshrssLoadMoreEvent.initEvent('freshrss:load-more', true, true);
  1865. function init_load_more(box) {
  1866. box_load_more = box;
  1867. document.body.dispatchEvent(freshrssLoadMoreEvent);
  1868. const next_button = document.getElementById('load_more');
  1869. if (!next_button) {
  1870. // no more article to load
  1871. url_load_more = '';
  1872. return;
  1873. }
  1874. url_load_more = next_button.getAttribute('formaction');
  1875. next_button.onclick = function (e) {
  1876. load_more_posts();
  1877. return false;
  1878. };
  1879. }
  1880. // </endless_mode>
  1881. function init_confirm_action() {
  1882. document.body.onclick = function (ev) {
  1883. const b = ev.target.closest('.confirm');
  1884. if (b) {
  1885. let str_confirmation = this.getAttribute('data-str-confirm');
  1886. if (!str_confirmation) {
  1887. str_confirmation = context.i18n.confirmation_default;
  1888. }
  1889. return confirm(str_confirmation);
  1890. }
  1891. };
  1892. const slider = document.getElementById('slider');
  1893. if (slider) {
  1894. slider.addEventListener('freshrss:slider-load', function (e) {
  1895. slider.querySelectorAll('button.confirm').forEach(function (b) { b.disabled = false; });
  1896. });
  1897. }
  1898. document.querySelectorAll('button.confirm').forEach(function (b) { b.disabled = false; });
  1899. }
  1900. function faviconNbUnread(n) {
  1901. if (typeof n === 'undefined') {
  1902. const t = document.querySelector('.category.all .title');
  1903. n = t ? str2int(t.getAttribute('data-unread')) : 0;
  1904. }
  1905. // http://remysharp.com/2010/08/24/dynamic-favicons/
  1906. const canvas = document.createElement('canvas');
  1907. const link = document.getElementById('favicon').cloneNode(true);
  1908. const ratio = window.devicePixelRatio;
  1909. if (canvas.getContext && link) {
  1910. canvas.height = canvas.width = 16 * ratio;
  1911. const img = document.createElement('img');
  1912. img.onload = function () {
  1913. const ctx = canvas.getContext('2d');
  1914. ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
  1915. if (n > 0) {
  1916. let text = '';
  1917. if (n < 1000) {
  1918. text = n;
  1919. } else if (n < 100000) {
  1920. text = Math.floor(n / 1000) + 'k';
  1921. } else {
  1922. text = 'E' + Math.floor(Math.log10(n));
  1923. }
  1924. ctx.font = 'bold ' + 9 * ratio + 'px "Arial", sans-serif';
  1925. ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
  1926. ctx.fillRect(0, 7 * ratio, ctx.measureText(text).width, 9 * ratio);
  1927. ctx.fillStyle = '#F00';
  1928. ctx.fillText(text, 0, canvas.height - 1);
  1929. }
  1930. link.href = canvas.toDataURL('image/png');
  1931. // Check if data URI has generated a real favicon and if not, fallback to standard icon
  1932. if (link.href.length > 180) {
  1933. document.querySelector('link[rel~=icon]').remove();
  1934. document.head.appendChild(link);
  1935. }
  1936. };
  1937. img.src = '../favicon.ico';
  1938. }
  1939. }
  1940. function removeFirstLoadSpinner() {
  1941. const first_load = document.getElementById('first_load');
  1942. if (first_load) {
  1943. first_load.remove();
  1944. }
  1945. }
  1946. function init_normal() {
  1947. const stream = document.getElementById('stream');
  1948. if (!stream) {
  1949. if (window.console) {
  1950. console.log('FreshRSS waiting for content…');
  1951. }
  1952. setTimeout(init_normal, 100);
  1953. return;
  1954. }
  1955. init_column_categories();
  1956. init_stream(stream);
  1957. init_actualize();
  1958. faviconNbUnread();
  1959. document.addEventListener("visibilitychange", () => {
  1960. if (document.visibilityState === "hidden") {
  1961. const sidebar = document.getElementById('sidebar');
  1962. if (sidebar) { // Save sidebar scroll position
  1963. sessionStorage.setItem('FreshRSS_sidebar_scrollTop', sidebar.scrollTop);
  1964. }
  1965. if (mark_read_queue && mark_read_queue.length > 0) {
  1966. clearTimeout(send_mark_read_queue_timeout);
  1967. send_mark_queue_tick(null);
  1968. }
  1969. }
  1970. });
  1971. }
  1972. function init_csp_alert() {
  1973. if (!context.admin || context.suppress_csp_warning) {
  1974. return;
  1975. }
  1976. try {
  1977. // eslint-disable-next-line no-new-func
  1978. Function();
  1979. } catch (_) {
  1980. // Exit if 'script-src' is set and 'unsafe-eval' isn't set in CSP
  1981. return;
  1982. }
  1983. document.body.insertAdjacentHTML('afterbegin', `
  1984. <div class="alert alert-error">
  1985. <span>${context.i18n.unsafe_csp_header}</span>
  1986. </div>
  1987. `);
  1988. }
  1989. function init_main_beforeDOM() {
  1990. history.scrollRestoration = 'manual';
  1991. document.scrollingElement.scrollTop = 0;
  1992. init_shortcuts();
  1993. if (['normal', 'reader', 'global'].indexOf(context.current_view) >= 0) {
  1994. init_normal();
  1995. }
  1996. }
  1997. function init_main_afterDOM() {
  1998. removeFirstLoadSpinner();
  1999. init_notifications();
  2000. init_csp_alert();
  2001. init_confirm_action();
  2002. const stream = document.getElementById('stream');
  2003. if (stream) {
  2004. init_load_more(stream);
  2005. init_posts();
  2006. if (document.getElementById('new-article')) {
  2007. // Only relevant for interactive views
  2008. init_nav_entries();
  2009. init_notifs_html5();
  2010. toggle_bigMarkAsRead_button();
  2011. setTimeout(faviconNbUnread, 1000);
  2012. setInterval(refreshUnreads, 120000);
  2013. }
  2014. }
  2015. if (window.console) {
  2016. console.log('FreshRSS main init done.');
  2017. }
  2018. }
  2019. init_main_beforeDOM(); // Can be called before DOM is fully loaded
  2020. if (document.readyState && document.readyState !== 'loading') {
  2021. init_main_afterDOM();
  2022. } else {
  2023. if (window.console) {
  2024. console.log('FreshRSS waiting for DOMContentLoaded…');
  2025. }
  2026. document.addEventListener('DOMContentLoaded', init_main_afterDOM, false);
  2027. }
  2028. // @license-end