main.js 72 KB

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