main.js 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343
  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(jump_to_unread) {
  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 (jump_to_unread && 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(jump_to_unread) {
  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 (jump_to_unread && 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. async 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. return 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. async 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. await 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 toggle_aside_click(manual = true) {
  841. const aside = document.querySelector('.aside');
  842. const toggle_aside = document.querySelector('#nav_menu_toggle_aside button');
  843. if (!toggle_aside) {
  844. return;
  845. }
  846. const active = toggle_aside.classList.contains('active');
  847. if (active) {
  848. toggle_aside.classList.remove('active');
  849. aside.classList.remove('visible');
  850. aside.style.display = 'none';
  851. } else {
  852. toggle_aside.classList.add('active');
  853. aside.classList.add('visible');
  854. aside.style.display = '';
  855. }
  856. if (manual && ['normal', 'reader'].includes(context.current_view)) {
  857. sessionStorage.setItem(`FreshRSS_aside-toggled_${context.current_view}`, !active ? 1 : 0);
  858. }
  859. }
  860. function init_nav_menu() {
  861. const aside = document.querySelector('.aside');
  862. const toggle_aside = document.querySelector('#nav_menu_toggle_aside button');
  863. if (!toggle_aside) {
  864. return;
  865. }
  866. function sync(e) {
  867. const active = toggle_aside.classList.contains('active');
  868. if ((e.matches && active) || (!e.matches && !active)) {
  869. toggle_aside_click(false);
  870. }
  871. }
  872. const media = window.matchMedia('(max-width: 840px)');
  873. media.onchange = sync;
  874. const state = sessionStorage.getItem(`FreshRSS_aside-toggled_${context.current_view}`);
  875. if (state !== null) {
  876. const active = toggle_aside.classList.contains('active');
  877. if (state != active) toggle_aside_click(false);
  878. }
  879. if (getComputedStyle(aside).display !== 'none') {
  880. if (context.current_view === 'normal') aside.classList.add('visible');
  881. sync(media);
  882. }
  883. const close_aside = [
  884. document.querySelector('.aside a.toggle_aside'),
  885. document.querySelector('a.close-aside'), // background of aside (#close)
  886. ];
  887. toggle_aside.addEventListener('click', toggle_aside_click);
  888. close_aside.forEach(close => close.addEventListener('click', toggle_aside_click));
  889. }
  890. function rememberOpenCategory(category_id, isOpen) {
  891. if (context.display_categories === 'remember') {
  892. const open_categories = JSON.parse(localStorage.getItem('FreshRSS_open_categories') || '{}');
  893. if (isOpen) {
  894. open_categories[category_id] = true;
  895. } else {
  896. delete open_categories[category_id];
  897. }
  898. localStorage.setItem('FreshRSS_open_categories', JSON.stringify(open_categories));
  899. }
  900. }
  901. function openCategory(category_id) {
  902. const category_element = document.getElementById(category_id);
  903. if (!category_element) return;
  904. category_element.querySelector('.tree-folder-items').classList.add('active');
  905. const img = category_element.querySelector('button.dropdown-toggle img');
  906. if (!img) return;
  907. img.src = img.src.replace('/icons/down.', '/icons/up.');
  908. img.alt = '🔼';
  909. }
  910. function loadJs(name) {
  911. if (!document.getElementById(name)) {
  912. const script = document.createElement('script');
  913. script.setAttribute('id', name);
  914. script.setAttribute('src', '../scripts/' + name + '?' + context.mtime[name]);
  915. script.setAttribute('defer', 'defer');
  916. script.setAttribute('async', 'async');
  917. document.head.appendChild(script);
  918. }
  919. }
  920. function init_column_categories() {
  921. if (context.current_view !== 'normal' && context.current_view !== 'reader') {
  922. return;
  923. }
  924. // Restore open categories
  925. if (context.display_categories === 'remember') {
  926. const open_categories = JSON.parse(localStorage.getItem('FreshRSS_open_categories') || '{}');
  927. Object.keys(open_categories).forEach(function (category_id) {
  928. openCategory(category_id);
  929. });
  930. }
  931. const sidebar_scrollTop = sessionStorage.getItem('FreshRSS_sidebar_scrollTop');
  932. if (sidebar_scrollTop) {
  933. // Restore sidebar scroll position (navigated from sidebar)
  934. document.querySelector('ul#sidebar').scrollTop = +sidebar_scrollTop;
  935. sessionStorage.removeItem('FreshRSS_sidebar_scrollTop');
  936. } else {
  937. // Scroll into filtered feed/category on sidebar (navigated from anywhere)
  938. const params = new URLSearchParams(location.search);
  939. const get = params.get('get');
  940. if (params.has('get') && (get.startsWith('f_') || get.startsWith('c_'))) {
  941. const selectedEl = document.getElementById(get);
  942. if (selectedEl) {
  943. selectedEl.scrollIntoView({ block: get.startsWith('f_') ? 'center' : 'start' });
  944. }
  945. }
  946. }
  947. document.getElementById('aside_feed').onclick = function (ev) {
  948. let a = ev.target.closest('.tree-folder > .tree-folder-title > button.dropdown-toggle');
  949. if (a) {
  950. const icon = a.querySelector('.icon');
  951. const category_id = a.closest('.category').id;
  952. if (icon.alt === '🔽' || icon.innerHTML === '🔽') {
  953. if (icon.src) {
  954. icon.src = icon.src.replace('/icons/down.', '/icons/up.');
  955. icon.alt = '🔼';
  956. } else {
  957. icon.innerHTML = '🔼';
  958. }
  959. rememberOpenCategory(category_id, true);
  960. } else {
  961. if (icon.src) {
  962. icon.src = icon.src.replace('/icons/up.', '/icons/down.');
  963. icon.alt = '🔽';
  964. } else {
  965. icon.innerHTML = '🔽';
  966. }
  967. rememberOpenCategory(category_id, false);
  968. }
  969. const ul = a.closest('li').querySelector('.tree-folder-items');
  970. let nbVisibleItems = 0;
  971. for (let i = ul.children.length - 1; i >= 0; i--) {
  972. if (ul.children[i].offsetHeight) {
  973. nbVisibleItems++;
  974. }
  975. }
  976. ul.classList.toggle('active');
  977. // CSS transition does not work on max-height:auto
  978. ul.style.maxHeight = ul.classList.contains('active') ? (nbVisibleItems * 4) + 'em' : 0;
  979. return false;
  980. }
  981. a = ev.target.closest('.tree-folder-items > .feed .dropdown-toggle');
  982. if (a) {
  983. const div = a.parentElement;
  984. const dropdownMenu = div.querySelector('.dropdown-menu');
  985. if (!dropdownMenu) {
  986. loadJs('extra.js');
  987. loadJs('feed.js');
  988. const itemId = a.closest('.item').id;
  989. const templateId = itemId.substring(0, 2) === 't_' ? 'tag_config_template' : 'feed_config_template';
  990. const id = itemId.substr(2);
  991. const feed_web = a.getAttribute('data-fweb') || '';
  992. const template = document.getElementById(templateId)
  993. .innerHTML.replace(/------/g, id).replace('http://example.net/', feed_web);
  994. div.insertAdjacentHTML('beforeend', template);
  995. if (feed_web == '') {
  996. const website = div.querySelector('.item.link.website');
  997. if (website) {
  998. website.remove();
  999. }
  1000. }
  1001. const b = div.querySelector('button.confirm');
  1002. if (b) {
  1003. b.disabled = false;
  1004. }
  1005. }
  1006. return true;
  1007. }
  1008. return true;
  1009. };
  1010. }
  1011. function init_shortcuts() {
  1012. Object.keys(context.shortcuts).forEach(function (k) {
  1013. context.shortcuts[k] = (context.shortcuts[k] || '').toUpperCase();
  1014. });
  1015. document.addEventListener('keydown', ev => {
  1016. if (ev.ctrlKey || ev.metaKey || (ev.altKey && ev.shiftKey) || ev.target.closest('input, select, textarea')) {
  1017. return;
  1018. }
  1019. const s = context.shortcuts;
  1020. let k = (ev.key.trim() || ev.code || 'Space').toUpperCase();
  1021. // IE11
  1022. if (k === 'SPACEBAR') k = 'SPACE';
  1023. else if (k === 'DEL') k = 'DELETE';
  1024. else if (k === 'ESC') k = 'ESCAPE';
  1025. if (location.hash.match(/^#dropdown-/)) {
  1026. const n = parseInt(k);
  1027. if (Number.isInteger(n)) {
  1028. switch (location.hash.substring(0, 15)) {
  1029. case '#dropdown-query':
  1030. user_filter(n);
  1031. break;
  1032. case '#dropdown-share':
  1033. auto_share(n);
  1034. break;
  1035. case '#dropdown-label':
  1036. mylabels(n);
  1037. break;
  1038. default:
  1039. return;
  1040. }
  1041. ev.preventDefault();
  1042. return;
  1043. }
  1044. }
  1045. if (k === s.actualize) {
  1046. const btn = document.getElementById('actualize');
  1047. if (btn) {
  1048. btn.click();
  1049. }
  1050. ev.preventDefault();
  1051. return;
  1052. }
  1053. if (k === s.next_entry) {
  1054. if (ev.altKey) {
  1055. next_category();
  1056. } else if (ev.shiftKey) {
  1057. next_feed(false);
  1058. } else {
  1059. next_entry(false);
  1060. }
  1061. ev.preventDefault();
  1062. return;
  1063. }
  1064. if (k === s.next_unread_entry) {
  1065. if (ev.altKey) {
  1066. next_unread_category();
  1067. } else if (ev.shiftKey) {
  1068. next_feed(true);
  1069. } else {
  1070. next_unread_entry(false);
  1071. }
  1072. ev.preventDefault();
  1073. return;
  1074. }
  1075. if (k === s.prev_entry) {
  1076. if (ev.altKey) {
  1077. prev_category();
  1078. } else if (ev.shiftKey) {
  1079. prev_feed(false);
  1080. } else {
  1081. prev_entry(false);
  1082. }
  1083. ev.preventDefault();
  1084. return;
  1085. }
  1086. if (k === s.mark_read) {
  1087. if (ev.altKey) {
  1088. mark_previous_read(document.querySelector('.flux.current'));
  1089. } else if (ev.shiftKey) {
  1090. document.querySelector('.nav_menu .read_all').click();
  1091. } else { // Toggle the read state
  1092. mark_read(document.querySelector('.flux.current'), false, false);
  1093. }
  1094. ev.preventDefault();
  1095. return;
  1096. }
  1097. if (k === s.first_entry) {
  1098. if (ev.altKey) {
  1099. first_category();
  1100. } else if (ev.shiftKey) {
  1101. first_feed();
  1102. } else {
  1103. const old_active = document.querySelector('.flux.current');
  1104. const first = document.querySelector('.flux');
  1105. if (first.classList.contains('flux')) {
  1106. toggleContent(first, old_active, false);
  1107. }
  1108. }
  1109. ev.preventDefault();
  1110. return;
  1111. }
  1112. if (k === s.last_entry) {
  1113. if (ev.altKey) {
  1114. last_category();
  1115. } else if (ev.shiftKey) {
  1116. last_feed();
  1117. } else {
  1118. const old_active = document.querySelector('.flux.current');
  1119. const last = document.querySelector('.flux:last-of-type');
  1120. if (last.classList.contains('flux')) {
  1121. toggleContent(last, old_active, false);
  1122. }
  1123. }
  1124. ev.preventDefault();
  1125. return;
  1126. }
  1127. if (ev.key === '?') {
  1128. window.location.href = context.urls.shortcuts;
  1129. return;
  1130. }
  1131. if (ev.altKey || ev.shiftKey) {
  1132. return;
  1133. }
  1134. if (k === s.mark_favorite) { // Toggle the favorite state
  1135. mark_favorite(document.querySelector('.flux.current'));
  1136. ev.preventDefault();
  1137. return;
  1138. }
  1139. if (k === s.go_website) {
  1140. if (context.auto_mark_site) {
  1141. mark_read(document.querySelector('.flux.current'), true, false);
  1142. }
  1143. const link_go_website = document.querySelector('.flux.current a.go_website');
  1144. if (link_go_website) {
  1145. window.open(link_go_website.href, '_blank', 'noopener');
  1146. ev.preventDefault();
  1147. }
  1148. return;
  1149. }
  1150. const hash = location.hash.substr(1);
  1151. if (k === s.skip_next_entry) { next_entry(true); ev.preventDefault(); return; }
  1152. if (k === s.skip_prev_entry) { prev_entry(true); ev.preventDefault(); return; }
  1153. if (k === s.collapse_entry) { collapse_entry(); ev.preventDefault(); return; }
  1154. if (k === s.mylabels) { mylabels(); ev.preventDefault(); return; }
  1155. if (k === s.auto_share) { auto_share(); ev.preventDefault(); return; }
  1156. if (k === s.user_filter) { user_filter(); ev.preventDefault(); return; }
  1157. if (k === s.load_more) { load_more_posts(); ev.preventDefault(); return; }
  1158. /* globals close_slider_listener */
  1159. if (k === s.close_menus && (
  1160. (hash === 'slider' && close_slider_listener()) ||
  1161. hash.startsWith('dropdown')
  1162. )) { location.hash = 'close'; ev.preventDefault(); return; }
  1163. if (k === s.help) { window.open(context.urls.help); ev.preventDefault(); return; }
  1164. if (k === s.focus_search) { document.getElementById('search').focus(); ev.preventDefault(); return; }
  1165. if (k === s.normal_view) { delayedClick(document.querySelector('#nav_menu_views .view-normal')); ev.preventDefault(); return; }
  1166. if (k === s.reading_view) { delayedClick(document.querySelector('#nav_menu_views .view-reader')); ev.preventDefault(); return; }
  1167. if (k === s.global_view) { delayedClick(document.querySelector('#nav_menu_views .view-global')); ev.preventDefault(); return; }
  1168. if (k === s.toggle_media) { toggle_media(); ev.preventDefault(); }
  1169. if (k === s.toggle_aside) { toggle_aside_click(); ev.preventDefault(); }
  1170. });
  1171. }
  1172. function init_stream(stream) {
  1173. stream.onclick = function (ev) {
  1174. let el = ev.target.closest('.flux a.read');
  1175. if (el) {
  1176. mark_read(el.closest('.flux'), false, false);
  1177. return false;
  1178. }
  1179. el = ev.target.closest('.flux a.bookmark');
  1180. if (el) {
  1181. mark_favorite(el.closest('.flux'));
  1182. return false;
  1183. }
  1184. el = ev.target.closest('.item a.title');
  1185. if (el) { // Allow default control/command-click behaviour such as open in background-tab
  1186. return ev.ctrlKey || ev.metaKey;
  1187. }
  1188. el = ev.target.closest('.flux .content .text a');
  1189. if (el) {
  1190. if (!el.closest('div').classList.contains('author')) {
  1191. el.target = '_blank';
  1192. el.rel = 'noreferrer';
  1193. }
  1194. return true;
  1195. }
  1196. el = ev.target.closest('.item.labels a.dropdown-toggle');
  1197. if (el) {
  1198. return show_labels_menu(el);
  1199. }
  1200. el = ev.target.closest('.item.share a.dropdown-toggle');
  1201. if (el) {
  1202. return show_share_menu(el);
  1203. }
  1204. el = ev.target.closest('.item.share > button[data-type="print"]');
  1205. if (el) { // Print
  1206. const html = document.documentElement;
  1207. const head = document.head.cloneNode(true);
  1208. head.querySelectorAll('script').forEach(js => js.remove());
  1209. const flux_content = el.closest('.flux_content');
  1210. let content_el = null;
  1211. if (flux_content) {
  1212. content_el = el.closest('.flux_content').querySelector('.content').cloneNode(true);
  1213. }
  1214. if (content_el === null) {
  1215. content_el = el.closest('.flux').querySelector('.flux_content .content').cloneNode(true);
  1216. }
  1217. content_el.querySelectorAll('a').forEach(link => {
  1218. // Avoid leaking the instance URL in PDFs
  1219. if (link.href.startsWith(location.origin)) {
  1220. link.removeAttribute('href');
  1221. }
  1222. });
  1223. content_el.querySelectorAll('details').forEach(el => el.setAttribute('open', 'open'));
  1224. const articleTitle = content_el.querySelector('.title a').innerText;
  1225. prevTitle = document.title;
  1226. // Chrome uses the parent's title to get the PDF save filename
  1227. document.title = articleTitle;
  1228. // Firefox uses the iframe's title to get the PDF save filename
  1229. // Note: Firefox Mobile saves PDFs with a filename that looks like: `temp[19 random digits].PDF` regardless of title
  1230. head.querySelector('title').innerText = articleTitle;
  1231. loadLazyImages(content_el);
  1232. const print_frame = document.createElement('iframe');
  1233. print_frame.style.display = 'none';
  1234. print_frame.srcdoc = `
  1235. <!DOCTYPE html>
  1236. <html class="${html.getAttribute('class')}">
  1237. <head>
  1238. ${head.innerHTML}
  1239. </head>
  1240. <body>
  1241. ${content_el.outerHTML}
  1242. </body>
  1243. </html>
  1244. `;
  1245. document.body.prepend(print_frame);
  1246. function afterPrint() {
  1247. print_frame.remove();
  1248. document.title = prevTitle;
  1249. prevTitle = '';
  1250. window.removeEventListener('focus', afterPrint);
  1251. }
  1252. print_frame.onload = () => {
  1253. const tmp_window = print_frame.contentWindow;
  1254. // Needed for Chrome
  1255. tmp_window.matchMedia('print').onchange = (e) => {
  1256. // UA check is needed to not trigger on Chrome Mobile
  1257. if (!e.matches && !navigator.userAgent.includes('Mobi')) {
  1258. afterPrint();
  1259. }
  1260. };
  1261. tmp_window.print();
  1262. };
  1263. // Needed for Firefox and Chrome Mobile
  1264. window.addEventListener('focus', afterPrint);
  1265. return false;
  1266. }
  1267. el = ev.target.closest('.item.share > button[data-type="clipboard"]');
  1268. if (el) { // Clipboard
  1269. if (navigator.clipboard) {
  1270. navigator.clipboard.writeText(el.dataset.url)
  1271. .then(() => {
  1272. toggleClass(el, 'ok');
  1273. })
  1274. .catch(e => {
  1275. console.log(e);
  1276. toggleClass(el, 'error');
  1277. });
  1278. } else {
  1279. // fallback, if navigator.clipboard is not available f.e. if access is not via https or localhost
  1280. const inputElement = document.createElement('input');
  1281. inputElement.value = el.dataset.url;
  1282. document.body.appendChild(inputElement);
  1283. inputElement.select();
  1284. if (document.execCommand && document.execCommand('copy')) {
  1285. toggleClass(el, 'ok');
  1286. } else {
  1287. console.log('document.execCommand("copy") failed');
  1288. toggleClass(el, 'error');
  1289. }
  1290. inputElement.remove();
  1291. }
  1292. return false;
  1293. }
  1294. el = ev.target.closest('.item.share > button[data-type="web-sharing-api"]');
  1295. if (el && navigator.share) { // https://developer.mozilla.org/en-US/docs/Web/API/Navigator/share
  1296. const shareData = {
  1297. url: el.dataset.url,
  1298. title: decodeURI(el.dataset.title),
  1299. };
  1300. navigator.share(shareData);
  1301. return false;
  1302. }
  1303. el = ev.target.closest('.item.share > a[data-type="email-webmail-firefox-fix"]');
  1304. if (el) {
  1305. window.open(el.href);
  1306. return false;
  1307. }
  1308. el = ev.target.closest('.item.share > a[href="POST"]');
  1309. if (el) { // Share by POST
  1310. const f = el.parentElement.querySelector('form');
  1311. f.disabled = false;
  1312. f.submit();
  1313. return false;
  1314. }
  1315. el = ev.target.closest('.flux_header, .flux_content');
  1316. if (el) { // flux_toggle
  1317. if (ev.target.closest('.reader, .content, .item.website, .item.link, .dropdown')) {
  1318. return true;
  1319. }
  1320. if ((!context.sides_close_article && ev.target.matches('.flux_content')) || ev.target.closest('footer')) {
  1321. // setting for not-closing after clicking outside article area
  1322. return false;
  1323. }
  1324. const old_active = document.querySelector('.flux.current');
  1325. const new_active = el.parentNode;
  1326. if (ev.target.tagName.toUpperCase() === 'A') { // Leave real links alone (but does not catch img in a link)
  1327. if (context.auto_mark_article) {
  1328. mark_read(new_active, true, false);
  1329. }
  1330. return true;
  1331. }
  1332. toggleContent(new_active, old_active, false);
  1333. return false;
  1334. }
  1335. };
  1336. stream.onmouseup = function (ev) { // Mouseup enables us to catch middle click, and control+click in IE/Edge
  1337. if (ev.altKey || ev.metaKey || ev.shiftKey) {
  1338. return;
  1339. }
  1340. let el = ev.target.closest('.item a.title');
  1341. if (el) {
  1342. if (ev.which == 1) {
  1343. if (ev.ctrlKey) { // Control+click
  1344. if (context.auto_mark_site) {
  1345. mark_read(el.closest('.flux'), true, false);
  1346. }
  1347. } else {
  1348. el.parentElement.click(); // Normal click, just toggle article.
  1349. }
  1350. } else if (ev.which == 2 && !ev.ctrlKey) { // Simple middle click: same behaviour as CTRL+click
  1351. if (context.auto_mark_article) {
  1352. const new_active = el.closest('.flux');
  1353. mark_read(new_active, true, false);
  1354. }
  1355. }
  1356. return;
  1357. }
  1358. if (context.auto_mark_site) {
  1359. // catch mouseup instead of click so we can have the correct behaviour
  1360. // with middle button click (scroll button).
  1361. el = ev.target.closest('.flux .link > a');
  1362. if (el) {
  1363. if (ev.which == 3) {
  1364. return;
  1365. }
  1366. mark_read(el.closest('.flux'), true, false);
  1367. }
  1368. }
  1369. };
  1370. stream.onchange = function (ev) {
  1371. const checkboxTag = ev.target.closest('.checkboxTag');
  1372. if (checkboxTag) { // Dynamic tags
  1373. ev.stopPropagation();
  1374. const tagId = checkboxTag.name.replace(/^t_/, '');
  1375. const tagName = checkboxTag.nextElementSibling ? checkboxTag.nextElementSibling.childNodes[0].value : '';
  1376. if ((tagId == 0 && tagName.length > 0) || tagId != 0) {
  1377. const isChecked = checkboxTag.checked;
  1378. const entry = checkboxTag.closest('div.flux');
  1379. const entryId = entry.id.replace(/^flux_/, '');
  1380. checkboxTag.disabled = true;
  1381. const req = new XMLHttpRequest();
  1382. req.open('POST', './?c=tag&a=tagEntry&ajax=1', true);
  1383. req.responseType = 'json';
  1384. req.onerror = function (e) {
  1385. checkboxTag.checked = !isChecked;
  1386. badAjax(this.status == 403);
  1387. };
  1388. req.onload = function (e) {
  1389. if (this.status != 200) {
  1390. return req.onerror(e);
  1391. }
  1392. if (entry.classList.contains('not_read')) {
  1393. incUnreadsTag('t_' + tagId, isChecked ? 1 : -1);
  1394. }
  1395. };
  1396. req.onloadend = function (e) {
  1397. checkboxTag.disabled = false;
  1398. if (tagId == 0) {
  1399. // new tag is added
  1400. forceReloadLabelsList = true;
  1401. loadDynamicTags(checkboxTag.closest('div.dropdown'));
  1402. } else {
  1403. // a tag was (un)checked
  1404. const dropdownmenu_current = ev.target.closest('.dropdown-menu');
  1405. const flux = ev.target.closest('.flux');
  1406. const dropdownmenu_all = flux.querySelectorAll('.dynamictags .dropdown-menu');
  1407. if (dropdownmenu_all.length > 1) {
  1408. // delete all other tag dropdown menus except the current one
  1409. dropdownmenu_all.forEach(
  1410. function (currentValue) {
  1411. if (currentValue !== dropdownmenu_current) {
  1412. currentValue.nextElementSibling.remove();
  1413. currentValue.parentNode.removeChild(currentValue);
  1414. }
  1415. }
  1416. );
  1417. }
  1418. }
  1419. };
  1420. req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
  1421. req.send(JSON.stringify({
  1422. _csrf: context.csrf,
  1423. id_tag: tagId,
  1424. name_tag: tagId == 0 ? tagName : '',
  1425. id_entry: entryId,
  1426. checked: isChecked,
  1427. ajax: 1,
  1428. }));
  1429. }
  1430. }
  1431. };
  1432. }
  1433. function toggleClass(el, cssclass) {
  1434. el.classList.remove(cssclass);
  1435. el.dataset.foo = el.offsetWidth; // it does nothing, but it is needed. See https://github.com/FreshRSS/FreshRSS/pull/5295
  1436. el.classList.add(cssclass);
  1437. }
  1438. function init_nav_entries() {
  1439. const nav_entries = document.getElementById('nav_entries');
  1440. if (nav_entries) {
  1441. nav_entries.querySelector('.previous_entry').onclick = function (e) {
  1442. prev_entry(false);
  1443. return false;
  1444. };
  1445. nav_entries.querySelector('.next_entry').onclick = function (e) {
  1446. next_entry(false);
  1447. return false;
  1448. };
  1449. nav_entries.querySelector('.up').onclick = function (e) {
  1450. const active_item = (document.querySelector('.flux.current') || document.querySelector('.flux'));
  1451. const windowTop = document.scrollingElement.scrollTop;
  1452. const item_top = active_item.offsetParent.offsetTop + active_item.offsetTop;
  1453. const nav_menu = document.querySelector('.nav_menu');
  1454. let nav_menu_height = 0;
  1455. if (getComputedStyle(nav_menu).position === 'fixed' || getComputedStyle(nav_menu).position === 'sticky') {
  1456. nav_menu_height = nav_menu.offsetHeight;
  1457. }
  1458. document.scrollingElement.scrollTop = windowTop > item_top ? item_top - nav_menu_height : 0 - nav_menu_height;
  1459. return false;
  1460. };
  1461. }
  1462. }
  1463. // forceReloadLabelsList default is false, so that the list does need a reload after opening it a second time.
  1464. // will be set to true, if a new tag is added. Then the labels list will be reloaded each opening.
  1465. // purpose of this flag: minimize the network traffic.
  1466. let forceReloadLabelsList = false;
  1467. async function loadDynamicTags(div) {
  1468. div.querySelectorAll('li.item').forEach(function (li) { li.remove(); });
  1469. const entryId = div.closest('div.flux').id.replace(/^flux_/, '');
  1470. let json;
  1471. try {
  1472. const response = await fetch('./?c=tag&a=getTagsForEntry&id_entry=' + entryId, {
  1473. headers: {
  1474. 'Accept': 'application/json',
  1475. }
  1476. });
  1477. if (!response.ok) {
  1478. throw new Error('HTTP error ' + response.status);
  1479. }
  1480. json = await response.json();
  1481. } catch (ex) {
  1482. div.querySelectorAll('li.item').forEach(function (li) { li.remove(); });
  1483. throw ex;
  1484. }
  1485. if (!context.anonymous) {
  1486. const li_item0 = document.createElement('li');
  1487. li_item0.setAttribute('class', 'item addItem');
  1488. const label = document.createElement('label');
  1489. label.setAttribute('class', 'noHover');
  1490. const input_checkboxTag = document.createElement('input');
  1491. input_checkboxTag.setAttribute('class', 'checkboxTag checkboxNewTag');
  1492. input_checkboxTag.setAttribute('name', 't_0');
  1493. input_checkboxTag.setAttribute('type', 'checkbox');
  1494. const input_newTag = document.createElement('input');
  1495. input_newTag.setAttribute('type', 'text');
  1496. input_newTag.setAttribute('name', 'newTag');
  1497. input_newTag.setAttribute('class', 'newTag');
  1498. input_newTag.setAttribute('list', 'datalist-labels');
  1499. input_newTag.addEventListener('keydown', function (ev) { if (ev.key.toUpperCase() == 'ENTER') { this.parentNode.previousSibling.click(); } });
  1500. const button_btn = document.createElement('button');
  1501. button_btn.setAttribute('type', 'button');
  1502. button_btn.setAttribute('class', 'btn');
  1503. button_btn.addEventListener('click', function () { this.parentNode.parentNode.click(); });
  1504. const text_plus = document.createTextNode('+');
  1505. const div_stick = document.createElement('div');
  1506. div_stick.setAttribute('class', 'stick');
  1507. button_btn.appendChild(text_plus);
  1508. div_stick.appendChild(input_newTag);
  1509. div_stick.appendChild(button_btn);
  1510. label.appendChild(input_checkboxTag);
  1511. label.appendChild(div_stick);
  1512. li_item0.appendChild(label);
  1513. div.querySelector('.dropdown-menu-scrollable').appendChild(li_item0);
  1514. }
  1515. let html = '';
  1516. let datalist = '';
  1517. if (json && json.length) {
  1518. let nbLabelsChecked = 0;
  1519. for (let i = 0; i < json.length; i++) {
  1520. const tag = json[i];
  1521. if (context.anonymous && !tag.checked) {
  1522. // In anonymous mode, show only the used tags
  1523. continue;
  1524. }
  1525. if (tag.checked) {
  1526. nbLabelsChecked++;
  1527. }
  1528. html += '<li class="item"><label><input ' +
  1529. (context.anonymous ? '' : 'class="checkboxTag" ') +
  1530. 'name="t_' + tag.id + '"type="checkbox" ' +
  1531. (context.anonymous ? 'disabled="disabled" ' : '') +
  1532. (tag.checked ? 'checked="checked" ' : '') + '/>' + tag.name + '</label></li>';
  1533. datalist += '<option value="' + tag.name + '"></option>';
  1534. }
  1535. if (context.anonymous && nbLabelsChecked === 0) {
  1536. html += '<li class="item"><span class="emptyLabels">' + context.i18n.labels_empty + '</span></li>';
  1537. }
  1538. }
  1539. div.querySelector('.dropdown-menu-scrollable').insertAdjacentHTML('beforeend', html);
  1540. const datalistLabels = document.getElementById('datalist-labels');
  1541. datalistLabels.innerHTML = ''; // clear before add the (updated) labels list
  1542. datalistLabels.insertAdjacentHTML('beforeend', datalist);
  1543. }
  1544. // <actualize>
  1545. let feeds_processed = 0;
  1546. let categories_processed = 0;
  1547. let to_process = 0;
  1548. function refreshFeed(feeds, feeds_count) {
  1549. const feed = feeds.pop();
  1550. if (!feed) {
  1551. return;
  1552. }
  1553. const req = new XMLHttpRequest();
  1554. req.open('POST', feed.url, true);
  1555. req.onloadend = function (e) {
  1556. feeds_processed++;
  1557. if (this.status != 200) {
  1558. badAjax(false);
  1559. } else {
  1560. const div = document.getElementById('actualizeProgress');
  1561. div.querySelector('.progress').innerHTML = (categories_processed + feeds_processed) + ' / ' + to_process;
  1562. div.querySelector('.title').innerHTML = feed.title;
  1563. }
  1564. if (feeds_processed === feeds_count) {
  1565. // Empty request to commit new articles
  1566. const req2 = new XMLHttpRequest();
  1567. req2.open('POST', './?c=feed&a=actualize&id=-1&ajax=1', true);
  1568. req2.onloadend = function (e) {
  1569. delayedFunction(function () { location.reload(); });
  1570. };
  1571. req2.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
  1572. req2.send(JSON.stringify({
  1573. _csrf: context.csrf,
  1574. noCommit: 0,
  1575. }));
  1576. } else {
  1577. refreshFeed(feeds, feeds_count);
  1578. }
  1579. };
  1580. req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
  1581. req.send(JSON.stringify({
  1582. _csrf: context.csrf,
  1583. noCommit: 1,
  1584. }));
  1585. }
  1586. function refreshFeeds(json) {
  1587. feeds_processed = 0;
  1588. if (!json.feeds || json.feeds.length === 0) {
  1589. // Empty request to commit new articles
  1590. const req2 = new XMLHttpRequest();
  1591. req2.open('POST', './?c=feed&a=actualize&id=-1&ajax=1', true);
  1592. req2.onloadend = function (e) {
  1593. context.ajax_loading = false;
  1594. };
  1595. req2.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
  1596. req2.send(JSON.stringify({
  1597. _csrf: context.csrf,
  1598. noCommit: 0,
  1599. }));
  1600. } else {
  1601. const feeds_count = json.feeds.length;
  1602. for (let i = context.nb_parallel_refresh; i > 0; i--) {
  1603. refreshFeed(json.feeds, feeds_count);
  1604. }
  1605. }
  1606. }
  1607. function refreshDynamicOpml(categories, categories_count, next) {
  1608. const category = categories.pop();
  1609. if (!category) {
  1610. return;
  1611. }
  1612. const req = new XMLHttpRequest();
  1613. req.open('POST', category.url, true);
  1614. req.onloadend = function (e) {
  1615. categories_processed++;
  1616. if (this.status != 200) {
  1617. badAjax(false);
  1618. } else {
  1619. const div = document.getElementById('actualizeProgress');
  1620. div.querySelector('.progress').innerHTML = (categories_processed + feeds_processed) + ' / ' + to_process;
  1621. div.querySelector('.title').innerHTML = category.title;
  1622. }
  1623. if (categories_processed === categories_count) {
  1624. if (next) { next(); }
  1625. } else {
  1626. refreshDynamicOpml(categories, categories_count, next);
  1627. }
  1628. };
  1629. req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
  1630. req.send(JSON.stringify({
  1631. _csrf: context.csrf,
  1632. noCommit: 1,
  1633. }));
  1634. }
  1635. function refreshDynamicOpmls(json, next) {
  1636. categories_processed = 0;
  1637. if (json.categories && json.categories.length > 0) {
  1638. const categories_count = json.categories.length;
  1639. for (let i = context.nb_parallel_refresh; i > 0; i--) {
  1640. refreshDynamicOpml(json.categories, categories_count, next);
  1641. }
  1642. } else {
  1643. if (next) { next(); }
  1644. }
  1645. }
  1646. function init_actualize() {
  1647. let auto = false;
  1648. let nbCategoriesFirstRound = 0;
  1649. let skipCategories = false;
  1650. const actualize = document.getElementById('actualize');
  1651. if (!actualize) {
  1652. return;
  1653. }
  1654. actualize.onclick = function () {
  1655. if (context.ajax_loading) {
  1656. return false;
  1657. }
  1658. context.ajax_loading = true;
  1659. const req = new XMLHttpRequest();
  1660. req.open('POST', './?c=javascript&a=actualize', true);
  1661. req.responseType = 'json';
  1662. req.onload = function (e) {
  1663. if (this.status != 200) {
  1664. return badAjax(false);
  1665. }
  1666. const json = xmlHttpRequestJson(this);
  1667. if (!json) {
  1668. return badAjax(false);
  1669. }
  1670. if (auto && json.categories.length < 1 && json.feeds.length < 1) {
  1671. auto = false;
  1672. context.ajax_loading = false;
  1673. return false;
  1674. }
  1675. to_process = json.categories.length + json.feeds.length + nbCategoriesFirstRound;
  1676. if (json.categories.length + json.feeds.length > 0 && !document.getElementById('actualizeProgress')) {
  1677. document.body.insertAdjacentHTML('beforeend', '<div id="actualizeProgress" class="notification good">' +
  1678. json.feedback_actualize + '<br /><span class="title">/</span><br /><span class="progress">0 / ' +
  1679. to_process + '</span></div>');
  1680. } else {
  1681. openNotification(json.feedback_no_refresh, 'good');
  1682. }
  1683. if (json.categories.length > 0 && !skipCategories) {
  1684. skipCategories = true; // To avoid risk of infinite loop
  1685. nbCategoriesFirstRound = json.categories.length;
  1686. // If some dynamic OPML categories are refreshed, need to reload the list of feeds before updating them
  1687. refreshDynamicOpmls(json, () => {
  1688. context.ajax_loading = false;
  1689. actualize.click();
  1690. });
  1691. } else {
  1692. refreshFeeds(json);
  1693. }
  1694. };
  1695. req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
  1696. req.send(JSON.stringify({
  1697. _csrf: context.csrf,
  1698. }));
  1699. return false;
  1700. };
  1701. if (context.auto_actualize_feeds) {
  1702. auto = true;
  1703. actualize.click();
  1704. }
  1705. }
  1706. // </actualize>
  1707. // <notification>
  1708. let notification = null;
  1709. let notification_interval = null;
  1710. let notification_working = false;
  1711. function openNotification(msg, status) {
  1712. if (notification_working === true) {
  1713. return false;
  1714. }
  1715. notification_working = true;
  1716. notification.querySelector('.msg').innerHTML = msg;
  1717. if (status == 'good') {
  1718. if (context.closeNotification.good > 0) {
  1719. notification_interval = setTimeout(closeNotification, context.closeNotification.good);
  1720. } else {
  1721. notification.classList.add('closed');
  1722. notification_working = false;
  1723. }
  1724. } else {
  1725. // no status or f.e. status = 'bad', give some more time to read
  1726. if (context.closeNotification.good > 0) {
  1727. notification_interval = setTimeout(closeNotification, context.closeNotification.bad);
  1728. }
  1729. }
  1730. notification.className = 'notification';
  1731. notification.classList.add(status);
  1732. }
  1733. function closeNotification() {
  1734. notification.classList.add('closed');
  1735. clearInterval(notification_interval);
  1736. notification_working = false;
  1737. }
  1738. function init_notifications() {
  1739. notification = document.getElementById('notification');
  1740. notification.querySelector('.close').addEventListener('click', function (ev) {
  1741. closeNotification();
  1742. ev.preventDefault();
  1743. return false;
  1744. });
  1745. notification.addEventListener('mouseenter', function () {
  1746. clearInterval(notification_interval);
  1747. });
  1748. notification.addEventListener('mouseleave', function () {
  1749. notification_interval = setTimeout(closeNotification, context.closeNotification.mouseLeave);
  1750. });
  1751. if (notification.querySelector('.msg').innerHTML.length > 0) {
  1752. notification_working = true;
  1753. if (notification.classList.contains('good')) {
  1754. notification_interval = setTimeout(closeNotification, context.closeNotification.good);
  1755. } else {
  1756. // no status or f.e. status = 'bad', give some more time to read
  1757. notification_interval = setTimeout(closeNotification, context.closeNotification.bad);
  1758. }
  1759. }
  1760. }
  1761. // </notification>
  1762. // <notifs html5>
  1763. let notifs_html5_permission = 'denied';
  1764. function notifs_html5_is_supported() {
  1765. return window.Notification !== undefined;
  1766. }
  1767. function notifs_html5_ask_permission() {
  1768. try {
  1769. window.Notification.requestPermission(function () {
  1770. notifs_html5_permission = window.Notification.permission;
  1771. });
  1772. } catch (e) {
  1773. }
  1774. }
  1775. function notifs_html5_show(nb, nb_new) {
  1776. if (notifs_html5_permission !== 'granted') {
  1777. return;
  1778. }
  1779. try {
  1780. const notification = new window.Notification(context.i18n.notif_title_articles, {
  1781. icon: '../themes/icons/favicon-256-padding.png',
  1782. body: context.i18n.notif_body_new_articles.replace('%%d', nb_new) + ' ' + context.i18n.notif_body_unread_articles.replace('%%d', nb),
  1783. tag: 'freshRssNewArticles',
  1784. });
  1785. notification.onclick = function () {
  1786. delayedFunction(function () {
  1787. location.reload();
  1788. window.focus();
  1789. notification.close();
  1790. });
  1791. };
  1792. if (context.html5_notif_timeout !== 0) {
  1793. setTimeout(function () {
  1794. notification.close();
  1795. }, context.html5_notif_timeout * 1000);
  1796. }
  1797. } catch (e) {
  1798. }
  1799. }
  1800. function init_notifs_html5() {
  1801. if (!notifs_html5_is_supported()) {
  1802. return;
  1803. }
  1804. notifs_html5_permission = notifs_html5_ask_permission();
  1805. }
  1806. // </notifs html5>
  1807. function refreshUnreads() {
  1808. const req = new XMLHttpRequest();
  1809. req.open('GET', './?c=javascript&a=nbUnreadsPerFeed', true);
  1810. req.responseType = 'json';
  1811. req.onload = function (e) {
  1812. const json = xmlHttpRequestJson(this);
  1813. if (!json) {
  1814. return badAjax(false);
  1815. }
  1816. const isAll = document.querySelector('.category.all.active');
  1817. let new_articles = false;
  1818. let nbUnreadFeeds = 0;
  1819. const title = document.querySelector('.category.all .title');
  1820. const nb_unreads_before = title ? str2int(title.getAttribute('data-unread')) : 0;
  1821. Object.keys(json.feeds).forEach(function (feed_id) {
  1822. const nbUnreads = json.feeds[feed_id];
  1823. nbUnreadFeeds += nbUnreads;
  1824. feed_id = 'f_' + feed_id;
  1825. const elem = document.getElementById(feed_id);
  1826. const feed_unreads = elem ? str2int(elem.getAttribute('data-unread')) : 0;
  1827. if ((incUnreadsFeed(null, feed_id, nbUnreads - feed_unreads) || isAll) && // Update of current view?
  1828. (nbUnreads - feed_unreads > 0)) {
  1829. const newArticle = document.getElementById('new-article');
  1830. newArticle.removeAttribute('hidden');
  1831. newArticle.style.display = 'block';
  1832. new_articles = true;
  1833. }
  1834. });
  1835. const noArticlesToShow_div = document.getElementById('noArticlesToShow');
  1836. if (nbUnreadFeeds > 0 && noArticlesToShow_div) {
  1837. noArticlesToShow_div.classList.add('hide');
  1838. }
  1839. let nbUnreadTags = 0;
  1840. Object.keys(json.tags).forEach(function (tag_id) {
  1841. const nbUnreads = json.tags[tag_id];
  1842. nbUnreadTags += nbUnreads;
  1843. const tag = document.getElementById('t_' + tag_id);
  1844. if (tag) {
  1845. tag.setAttribute('data-unread', nbUnreads);
  1846. tag.querySelector('.item-title').setAttribute('data-unread', numberFormat(nbUnreads));
  1847. }
  1848. });
  1849. const tags = document.querySelector('.category.tags');
  1850. if (tags) {
  1851. tags.setAttribute('data-unread', nbUnreadTags);
  1852. tags.querySelector('.title').setAttribute('data-unread', numberFormat(nbUnreadTags));
  1853. }
  1854. const nb_unreads = title ? str2int(title.getAttribute('data-unread')) : 0;
  1855. if (nb_unreads > 0 && new_articles) {
  1856. faviconNbUnread(nb_unreads);
  1857. const nb_new = nb_unreads - nb_unreads_before;
  1858. notifs_html5_show(nb_unreads, nb_new);
  1859. }
  1860. };
  1861. req.send();
  1862. }
  1863. function toggle_bigMarkAsRead_button() {
  1864. const bigMarkAsRead_button = document.getElementById('bigMarkAsRead');
  1865. if (bigMarkAsRead_button) {
  1866. if (document.querySelector('.flux.not_read') != null) {
  1867. bigMarkAsRead_button.style = '';
  1868. bigMarkAsRead_button.querySelector('.markAllRead').style.visibility = '';
  1869. } else {
  1870. if (bigMarkAsRead_button.querySelector('.jumpNext')) {
  1871. bigMarkAsRead_button.querySelector('.markAllRead').style.visibility = 'hidden';
  1872. } else {
  1873. bigMarkAsRead_button.querySelector('.markAllRead').style.visibility = '';
  1874. bigMarkAsRead_button.style.visibility = 'hidden';
  1875. }
  1876. }
  1877. }
  1878. }
  1879. // <endless_mode>
  1880. let url_load_more = '';
  1881. let load_more = false;
  1882. let box_load_more = null;
  1883. function remove_existing_posts() {
  1884. document.querySelectorAll('.flux, .transition').forEach(function (div) {
  1885. div.remove();
  1886. });
  1887. }
  1888. function load_more_posts() {
  1889. if (load_more || !url_load_more || !box_load_more) {
  1890. return;
  1891. }
  1892. load_more = true;
  1893. document.getElementById('load_more').classList.add('loading');
  1894. const req = new XMLHttpRequest();
  1895. req.open('GET', url_load_more, true);
  1896. req.responseType = 'document';
  1897. req.onload = function (e) {
  1898. if (context.sort === 'rand') {
  1899. document.scrollingElement.scrollTop = 0;
  1900. remove_existing_posts();
  1901. }
  1902. const html = this.response;
  1903. const streamFooter = document.getElementById('stream-footer');
  1904. const transitions = document.querySelectorAll('#stream > .transition');
  1905. let lastTransition = transitions.length > 0 ? transitions[transitions.length - 1] : null;
  1906. const streamAdopted = document.adoptNode(html.getElementById('stream'));
  1907. streamAdopted.querySelectorAll('.flux, .transition').forEach(function (div) {
  1908. if (lastTransition !== null && div.classList.contains('transition') && div.textContent === lastTransition.textContent) {
  1909. lastTransition = null;
  1910. return; // Skip duplicate transition
  1911. }
  1912. box_load_more.insertBefore(div, streamFooter);
  1913. });
  1914. const streamFooterOld = streamFooter.querySelector('.stream-footer-inner');
  1915. const streamFooterNew = streamAdopted.querySelector('.stream-footer-inner');
  1916. streamFooter.replaceChild(streamFooterNew, streamFooterOld);
  1917. const bigMarkAsRead = document.getElementById('bigMarkAsRead');
  1918. const readAll = document.querySelector('#nav_menu_read_all .read_all');
  1919. if (readAll && bigMarkAsRead && bigMarkAsRead.formAction) {
  1920. if (context.display_order === 'ASC') {
  1921. readAll.formAction = bigMarkAsRead.formAction;
  1922. } else {
  1923. bigMarkAsRead.formAction = readAll.formAction;
  1924. }
  1925. toggle_bigMarkAsRead_button();
  1926. }
  1927. init_load_more(box_load_more);
  1928. const div_load_more = document.getElementById('load_more');
  1929. if (bigMarkAsRead) {
  1930. bigMarkAsRead.removeAttribute('disabled');
  1931. }
  1932. if (div_load_more) {
  1933. div_load_more.classList.remove('loading');
  1934. }
  1935. load_more = false;
  1936. };
  1937. req.send();
  1938. }
  1939. const freshrssLoadMoreEvent = document.createEvent('Event');
  1940. freshrssLoadMoreEvent.initEvent('freshrss:load-more', true, true);
  1941. function init_load_more(box) {
  1942. box_load_more = box;
  1943. document.body.dispatchEvent(freshrssLoadMoreEvent);
  1944. const next_button = document.getElementById('load_more');
  1945. if (!next_button) {
  1946. // no more article to load
  1947. url_load_more = '';
  1948. return;
  1949. }
  1950. url_load_more = next_button.getAttribute('formaction');
  1951. next_button.onclick = function (e) {
  1952. load_more_posts();
  1953. return false;
  1954. };
  1955. }
  1956. // </endless_mode>
  1957. function init_confirm_action() {
  1958. document.body.onclick = function (ev) {
  1959. const b = ev.target.closest('.confirm');
  1960. if (b) {
  1961. let str_confirmation = this.getAttribute('data-str-confirm');
  1962. if (!str_confirmation) {
  1963. str_confirmation = context.i18n.confirmation_default;
  1964. }
  1965. return confirm(str_confirmation);
  1966. }
  1967. };
  1968. const slider = document.getElementById('slider');
  1969. if (slider) {
  1970. slider.addEventListener('freshrss:slider-load', function (e) {
  1971. slider.querySelectorAll('button.confirm').forEach(function (b) { b.disabled = false; });
  1972. });
  1973. }
  1974. document.querySelectorAll('button.confirm').forEach(function (b) { b.disabled = false; });
  1975. }
  1976. function faviconNbUnread(n) {
  1977. if (typeof n === 'undefined') {
  1978. const t = document.querySelector('.category.all .title');
  1979. n = t ? str2int(t.getAttribute('data-unread')) : 0;
  1980. }
  1981. // http://remysharp.com/2010/08/24/dynamic-favicons/
  1982. const canvas = document.createElement('canvas');
  1983. const link = document.getElementById('favicon').cloneNode(true);
  1984. const ratio = window.devicePixelRatio;
  1985. if (canvas.getContext && link) {
  1986. canvas.height = canvas.width = 16 * ratio;
  1987. const img = document.createElement('img');
  1988. img.onload = function () {
  1989. const ctx = canvas.getContext('2d');
  1990. ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
  1991. if (n > 0) {
  1992. let text = '';
  1993. if (n < 1000) {
  1994. text = n;
  1995. } else if (n < 100000) {
  1996. text = Math.floor(n / 1000) + 'k';
  1997. } else {
  1998. text = 'E' + Math.floor(Math.log10(n));
  1999. }
  2000. ctx.font = 'bold ' + 9 * ratio + 'px "Arial", sans-serif';
  2001. ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
  2002. ctx.fillRect(0, 7 * ratio, ctx.measureText(text).width, 9 * ratio);
  2003. ctx.fillStyle = '#F00';
  2004. ctx.fillText(text, 0, canvas.height - 1);
  2005. }
  2006. link.href = canvas.toDataURL('image/png');
  2007. // Check if data URI has generated a real favicon and if not, fallback to standard icon
  2008. if (link.href.length > 180) {
  2009. document.querySelector('link[rel~=icon]').remove();
  2010. document.head.appendChild(link);
  2011. }
  2012. };
  2013. img.src = '../favicon.ico';
  2014. }
  2015. }
  2016. function removeFirstLoadSpinner() {
  2017. const first_load = document.getElementById('first_load');
  2018. if (first_load) {
  2019. first_load.remove();
  2020. }
  2021. }
  2022. function init_normal() {
  2023. const stream = document.getElementById('stream');
  2024. if (!stream) {
  2025. if (window.console) {
  2026. console.log('FreshRSS waiting for content…');
  2027. }
  2028. setTimeout(init_normal, 100);
  2029. return;
  2030. }
  2031. init_column_categories();
  2032. init_stream(stream);
  2033. init_actualize();
  2034. faviconNbUnread();
  2035. const sidebar = document.querySelector('ul#sidebar');
  2036. if (sidebar) {
  2037. sidebar.addEventListener('click', (e) => {
  2038. if (!e.isTrusted) {
  2039. // Event was likely called via a keyboard shortcut shift+j/k using click()
  2040. return;
  2041. }
  2042. const target = e.target.closest('a.item-title, a.tree-folder-title');
  2043. if (target) {
  2044. // A page navigation should occur now, save the sidebar scroll position
  2045. sessionStorage.setItem('FreshRSS_sidebar_scrollTop', sidebar.scrollTop);
  2046. }
  2047. });
  2048. }
  2049. document.addEventListener("visibilitychange", () => {
  2050. if (document.visibilityState === "hidden") {
  2051. if (mark_read_queue && mark_read_queue.length > 0) {
  2052. clearTimeout(send_mark_read_queue_timeout);
  2053. send_mark_queue_tick(null);
  2054. }
  2055. }
  2056. });
  2057. }
  2058. function init_csp_alert() {
  2059. if (!context.admin || context.suppress_csp_warning) {
  2060. return;
  2061. }
  2062. try {
  2063. // eslint-disable-next-line no-new-func
  2064. Function();
  2065. } catch (_) {
  2066. // Exit if 'script-src' is set and 'unsafe-eval' isn't set in CSP
  2067. return;
  2068. }
  2069. document.body.insertAdjacentHTML('afterbegin', `
  2070. <div class="alert alert-error">
  2071. <span>${context.i18n.unsafe_csp_header}</span>
  2072. </div>
  2073. `);
  2074. }
  2075. function init_main_beforeDOM() {
  2076. history.scrollRestoration = 'manual';
  2077. document.scrollingElement.scrollTop = 0;
  2078. init_shortcuts();
  2079. if (['normal', 'reader', 'global'].indexOf(context.current_view) >= 0) {
  2080. init_normal();
  2081. }
  2082. }
  2083. function init_main_afterDOM() {
  2084. removeFirstLoadSpinner();
  2085. init_notifications();
  2086. init_csp_alert();
  2087. init_confirm_action();
  2088. init_nav_menu();
  2089. const stream = document.getElementById('stream');
  2090. if (stream) {
  2091. init_load_more(stream);
  2092. init_posts();
  2093. if (document.getElementById('new-article')) {
  2094. // Only relevant for interactive views
  2095. init_nav_entries();
  2096. init_notifs_html5();
  2097. toggle_bigMarkAsRead_button();
  2098. setTimeout(faviconNbUnread, 1000);
  2099. setInterval(refreshUnreads, 120000);
  2100. }
  2101. }
  2102. if (window.console) {
  2103. console.log('FreshRSS main init done.');
  2104. }
  2105. }
  2106. init_main_beforeDOM(); // Can be called before DOM is fully loaded
  2107. if (document.readyState && document.readyState !== 'loading') {
  2108. init_main_afterDOM();
  2109. } else {
  2110. if (window.console) {
  2111. console.log('FreshRSS waiting for DOMContentLoaded…');
  2112. }
  2113. document.addEventListener('DOMContentLoaded', init_main_afterDOM, false);
  2114. }
  2115. // @license-end