main.js 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840
  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. /* eslint-enable no-var */
  38. (function parseJsonVars() {
  39. const jsonVars = document.getElementById('jsonVars');
  40. const json = JSON.parse(jsonVars.innerHTML);
  41. jsonVars.outerHTML = '';
  42. context = json.context;
  43. context.ajax_loading = false;
  44. context.i18n = json.i18n;
  45. context.shortcuts = json.shortcuts;
  46. context.urls = json.urls;
  47. context.icons = json.icons;
  48. context.icons.read = decodeURIComponent(context.icons.read);
  49. context.icons.unread = decodeURIComponent(context.icons.unread);
  50. context.extensions = json.extensions;
  51. }());
  52. // </Global context>
  53. function badAjax(reload) {
  54. openNotification(context.i18n.notif_request_failed, 'bad');
  55. if (reload) {
  56. setTimeout(function () { location.reload(); }, 2000);
  57. }
  58. return true;
  59. }
  60. function needsScroll(elem) {
  61. const winBottom = document.scrollingElement.scrollTop + document.scrollingElement.clientHeight;
  62. const elemTop = elem.offsetParent.offsetTop + elem.offsetTop;
  63. const elemBottom = elemTop + elem.offsetHeight;
  64. if (elemTop < document.scrollingElement.scrollTop || elemBottom > winBottom) {
  65. return elemTop - (document.scrollingElement.clientHeight / 2);
  66. }
  67. return 0;
  68. }
  69. function str2int(str) {
  70. if (!str) {
  71. return 0;
  72. }
  73. return parseInt(str.replace(/\D/g, ''), 10) || 0;
  74. }
  75. function numberFormat(nStr) {
  76. if (nStr < 0) {
  77. return 0;
  78. }
  79. // http://www.mredkj.com/javascript/numberFormat.html
  80. nStr += '';
  81. const x = nStr.split('.');
  82. const x2 = x.length > 1 ? '.' + x[1] : '';
  83. const rgx = /(\d+)(\d{3})/;
  84. let x1 = x[0];
  85. while (rgx.test(x1)) {
  86. x1 = x1.replace(rgx, '$1 $2');
  87. }
  88. return x1 + x2;
  89. }
  90. function incLabel(p, inc, spaceAfter) {
  91. const i = str2int(p) + inc;
  92. return i > 0 ? ((spaceAfter ? '' : ' ') + '(' + numberFormat(i) + ')' + (spaceAfter ? ' ' : '')) : '';
  93. }
  94. function incUnreadsFeed(article, feed_id, nb) {
  95. // Update unread: feed
  96. let elem = document.getElementById(feed_id);
  97. let feed_unreads = elem ? str2int(elem.getAttribute('data-unread')) : 0;
  98. const feed_priority = elem ? str2int(elem.getAttribute('data-priority')) : 0;
  99. if (elem) {
  100. elem.setAttribute('data-unread', feed_unreads + nb);
  101. elem = elem.querySelector('.item-title');
  102. if (elem) {
  103. elem.setAttribute('data-unread', numberFormat(feed_unreads + nb));
  104. }
  105. }
  106. // Update unread: category
  107. elem = document.getElementById(feed_id);
  108. elem = elem ? elem.closest('.category') : null;
  109. if (elem) {
  110. feed_unreads = str2int(elem.getAttribute('data-unread'));
  111. elem.setAttribute('data-unread', feed_unreads + nb);
  112. elem = elem.querySelector('.title');
  113. if (elem) {
  114. elem.setAttribute('data-unread', numberFormat(feed_unreads + nb));
  115. }
  116. }
  117. // Update unread: all
  118. if (feed_priority > 0) {
  119. elem = document.querySelector('#aside_feed .all .title');
  120. if (elem) {
  121. feed_unreads = elem ? str2int(elem.getAttribute('data-unread')) : 0;
  122. elem.setAttribute('data-unread', numberFormat(feed_unreads + nb));
  123. }
  124. }
  125. // Update unread: favourites
  126. if (article && article.closest('div').classList.contains('favorite')) {
  127. elem = document.querySelector('#aside_feed .favorites .title');
  128. if (elem) {
  129. feed_unreads = elem ? str2int(elem.getAttribute('data-unread')) : 0;
  130. elem.setAttribute('data-unread', numberFormat(feed_unreads + nb));
  131. }
  132. }
  133. let isCurrentView = false;
  134. // Update unread: title
  135. document.title = document.title.replace(/^((?:\([\s0-9]+\) )?)/, function (m, p1) {
  136. const feed = document.getElementById(feed_id);
  137. if (article || (feed && feed.closest('.active'))) {
  138. isCurrentView = true;
  139. return incLabel(p1, nb, true);
  140. } else if (document.querySelector('.all.active')) {
  141. isCurrentView = feed_priority > 0;
  142. return incLabel(p1, feed_priority > 0 ? nb : 0, true);
  143. } else {
  144. return p1;
  145. }
  146. });
  147. return isCurrentView;
  148. }
  149. function incUnreadsTag(tag_id, nb) {
  150. let t = document.getElementById(tag_id);
  151. if (t) {
  152. const unreads = str2int(t.getAttribute('data-unread'));
  153. t.setAttribute('data-unread', unreads + nb);
  154. t.querySelector('.item-title').setAttribute('data-unread', numberFormat(unreads + nb));
  155. }
  156. t = document.querySelector('.category.tags .title');
  157. if (t) {
  158. const unreads = str2int(t.getAttribute('data-unread'));
  159. t.setAttribute('data-unread', numberFormat(unreads + nb));
  160. }
  161. }
  162. function removeArticle(div) {
  163. if (!div || div.classList.contains('not_read') || (context.auto_mark_article && div.classList.contains('active'))) {
  164. return;
  165. }
  166. let scrollTop = box_to_follow.scrollTop;
  167. let dirty = false;
  168. const p = div.previousElementSibling;
  169. const n = div.nextElementSibling;
  170. if (p && p.classList.contains('day') && n && n.classList.contains('day')) {
  171. scrollTop -= p.offsetHeight;
  172. dirty = true;
  173. p.remove();
  174. }
  175. if (div.offsetHeight > 0 && div.offsetParent.offsetTop + div.offsetTop + div.offsetHeight < scrollTop) {
  176. scrollTop -= div.offsetHeight;
  177. dirty = true;
  178. }
  179. div.remove();
  180. if (dirty) {
  181. box_to_follow.scrollTop = scrollTop;
  182. }
  183. }
  184. const pending_entries = {};
  185. let mark_read_queue = [];
  186. function send_mark_read_queue(queue, asRead, callback) {
  187. if (!queue || queue.length === 0) {
  188. if (callback) {
  189. callback();
  190. }
  191. return;
  192. }
  193. const req = new XMLHttpRequest();
  194. req.open('POST', '.?c=entry&a=read' + (asRead ? '' : '&is_read=0'), true);
  195. req.responseType = 'json';
  196. req.onerror = function (e) {
  197. for (let i = queue.length - 1; i >= 0; i--) {
  198. delete pending_entries['flux_' + queue[i]];
  199. }
  200. badAjax(this.status == 403);
  201. };
  202. req.onload = function (e) {
  203. if (this.status != 200) {
  204. return req.onerror(e);
  205. }
  206. const json = xmlHttpRequestJson(this);
  207. if (!json) {
  208. return req.onerror(e);
  209. }
  210. for (let i = queue.length - 1; i >= 0; i--) {
  211. const div = document.getElementById('flux_' + queue[i]);
  212. const myIcons = context.icons;
  213. let inc = 0;
  214. if (div.classList.contains('not_read')) {
  215. div.classList.remove('not_read');
  216. div.querySelectorAll('a.read').forEach(function (a) {
  217. a.href = a.href.replace('&is_read=0', '') + '&is_read=1';
  218. });
  219. div.querySelectorAll('a.read > .icon').forEach(function (img) { img.outerHTML = myIcons.read; });
  220. inc--;
  221. if (context.auto_remove_article) {
  222. removeArticle(div);
  223. }
  224. } else {
  225. div.classList.add('not_read');
  226. div.classList.add('keep_unread'); // Split for IE11
  227. div.querySelectorAll('a.read').forEach(function (a) {
  228. a.href = a.href.replace('&is_read=1', '');
  229. });
  230. div.querySelectorAll('a.read > .icon').forEach(function (img) { img.outerHTML = myIcons.unread; });
  231. inc++;
  232. }
  233. const feed_link = div.querySelector('.website > a, a.website');
  234. if (feed_link) {
  235. const feed_url = feed_link.href;
  236. const feed_id = feed_url.substr(feed_url.lastIndexOf('f_'));
  237. incUnreadsFeed(div, feed_id, inc);
  238. }
  239. delete pending_entries['flux_' + queue[i]];
  240. }
  241. faviconNbUnread();
  242. if (json.tags) {
  243. const tagIds = Object.keys(json.tags);
  244. for (let i = tagIds.length - 1; i >= 0; i--) {
  245. const tagId = tagIds[i];
  246. incUnreadsTag(tagId, (asRead ? -1 : 1) * json.tags[tagId].length);
  247. }
  248. }
  249. onScroll();
  250. if (callback) {
  251. callback();
  252. }
  253. };
  254. req.setRequestHeader('Content-Type', 'application/json');
  255. req.send(JSON.stringify({
  256. ajax: true,
  257. _csrf: context.csrf,
  258. id: queue,
  259. }));
  260. }
  261. let send_mark_read_queue_timeout = 0;
  262. function send_mark_queue_tick(callback) {
  263. send_mark_read_queue_timeout = 0;
  264. const queue = mark_read_queue.slice(0);
  265. mark_read_queue = [];
  266. send_mark_read_queue(queue, true, callback);
  267. }
  268. const delayedFunction = send_mark_queue_tick;
  269. function delayedClick(a) {
  270. if (a) {
  271. delayedFunction(function () { a.click(); });
  272. }
  273. }
  274. function mark_read(div, only_not_read, asBatch) {
  275. if (!div || !div.id || context.anonymous ||
  276. (only_not_read && !div.classList.contains('not_read'))) {
  277. return false;
  278. }
  279. if (pending_entries[div.id]) {
  280. return false;
  281. }
  282. pending_entries[div.id] = true;
  283. const asRead = div.classList.contains('not_read');
  284. const entryId = div.id.replace(/^flux_/, '');
  285. if (asRead && asBatch) {
  286. mark_read_queue.push(entryId);
  287. if (send_mark_read_queue_timeout == 0) {
  288. send_mark_read_queue_timeout = setTimeout(function () { send_mark_queue_tick(null); }, 1000);
  289. }
  290. } else {
  291. const queue = [entryId];
  292. send_mark_read_queue(queue, asRead);
  293. }
  294. }
  295. function mark_previous_read(div) {
  296. while (div) {
  297. mark_read(div, true, true);
  298. div = div.previousElementSibling;
  299. }
  300. }
  301. function mark_favorite(div) {
  302. if (!div) {
  303. return false;
  304. }
  305. const a = div.querySelector('a.bookmark');
  306. const url = a ? a.href : '';
  307. if (!url) {
  308. return false;
  309. }
  310. if (pending_entries[div.id]) {
  311. return false;
  312. }
  313. pending_entries[div.id] = true;
  314. const req = new XMLHttpRequest();
  315. req.open('POST', url, true);
  316. req.responseType = 'json';
  317. req.onerror = function (e) {
  318. delete pending_entries[div.id];
  319. badAjax(this.status == 403);
  320. };
  321. req.onload = function (e) {
  322. if (this.status != 200) {
  323. return req.onerror(e);
  324. }
  325. const json = xmlHttpRequestJson(this);
  326. if (!json) {
  327. return req.onerror(e);
  328. }
  329. let inc = 0;
  330. if (div.classList.contains('favorite')) {
  331. div.classList.remove('favorite');
  332. inc--;
  333. } else {
  334. div.classList.add('favorite');
  335. inc++;
  336. }
  337. div.querySelectorAll('a.bookmark').forEach(function (a) { a.href = json.url; });
  338. div.querySelectorAll('a.bookmark > .icon').forEach(function (img) { img.outerHTML = json.icon; });
  339. const favourites = document.querySelector('#aside_feed .favorites .title');
  340. if (favourites) {
  341. favourites.textContent = favourites.textContent.replace(/((?: \([\s0-9]+\))?\s*)$/, function (m, p1) {
  342. return incLabel(p1, inc, false);
  343. });
  344. }
  345. if (div.classList.contains('not_read')) {
  346. const elem = document.querySelector('#aside_feed .favorites .title');
  347. const feed_unreads = elem ? str2int(elem.getAttribute('data-unread')) : 0;
  348. if (elem) {
  349. elem.setAttribute('data-unread', numberFormat(feed_unreads + inc));
  350. }
  351. }
  352. delete pending_entries[div.id];
  353. };
  354. req.setRequestHeader('Content-Type', 'application/json');
  355. req.send(JSON.stringify({
  356. ajax: true,
  357. _csrf: context.csrf,
  358. }));
  359. }
  360. const freshrssOpenArticleEvent = document.createEvent('Event');
  361. freshrssOpenArticleEvent.initEvent('freshrss:openArticle', true, true);
  362. function toggleContent(new_active, old_active, skipping) {
  363. // If skipping, move current without activating or marking as read
  364. if (!new_active) {
  365. return;
  366. }
  367. if (context.does_lazyload && !skipping) {
  368. new_active.querySelectorAll('img[data-original], iframe[data-original]').forEach(function (el) {
  369. el.src = el.getAttribute('data-original');
  370. el.removeAttribute('data-original');
  371. });
  372. }
  373. if (old_active !== new_active) {
  374. if (!skipping) {
  375. new_active.classList.add('active');
  376. }
  377. new_active.classList.add('current');
  378. if (old_active) {
  379. old_active.classList.remove('active');
  380. old_active.classList.remove('current'); // Split for IE11
  381. if (context.auto_remove_article) {
  382. removeArticle(old_active);
  383. }
  384. }
  385. } else {
  386. new_active.classList.toggle('active');
  387. }
  388. const relative_move = context.current_view === 'global';
  389. const box_to_move = relative_move ? document.getElementById('panel') : document.scrollingElement;
  390. if (context.sticky_post) { // Stick the article to the top when opened
  391. const prev_article = new_active.previousElementSibling;
  392. let new_pos = new_active.offsetParent.offsetTop + new_active.offsetTop;
  393. if (prev_article && new_active.offsetTop - prev_article.offsetTop <= 150) {
  394. new_pos = prev_article.offsetParent.offsetTop + prev_article.offsetTop;
  395. if (relative_move) {
  396. new_pos -= box_to_move.offsetTop;
  397. }
  398. }
  399. if (skipping) {
  400. // when skipping, this feels more natural if it’s not so near the top
  401. new_pos -= document.body.clientHeight / 4;
  402. }
  403. if (relative_move) {
  404. new_pos += box_to_move.scrollTop;
  405. }
  406. box_to_move.scrollTop = new_pos;
  407. }
  408. if (new_active.classList.contains('active') && !skipping) {
  409. if (context.auto_mark_article) {
  410. mark_read(new_active, true, true);
  411. }
  412. new_active.dispatchEvent(freshrssOpenArticleEvent);
  413. }
  414. onScroll();
  415. }
  416. function prev_entry(skipping) {
  417. const old_active = document.querySelector('.flux.current');
  418. let new_active = old_active;
  419. if (new_active) {
  420. do new_active = new_active.previousElementSibling;
  421. while (new_active && !new_active.classList.contains('flux'));
  422. if (!new_active) {
  423. prev_feed();
  424. }
  425. } else {
  426. new_active = document.querySelector('.flux');
  427. }
  428. toggleContent(new_active, old_active, skipping);
  429. }
  430. function next_entry(skipping) {
  431. const old_active = document.querySelector('.flux.current');
  432. let new_active = old_active;
  433. if (new_active) {
  434. do new_active = new_active.nextElementSibling;
  435. while (new_active && !new_active.classList.contains('flux'));
  436. if (!new_active) {
  437. next_feed();
  438. }
  439. } else {
  440. new_active = document.querySelector('.flux');
  441. }
  442. toggleContent(new_active, old_active, skipping);
  443. }
  444. function next_unread_entry(skipping) {
  445. const old_active = document.querySelector('.flux.current');
  446. let new_active = old_active;
  447. if (new_active) {
  448. do new_active = new_active.nextElementSibling;
  449. while (new_active && !new_active.classList.contains('not_read'));
  450. if (!new_active) {
  451. next_feed();
  452. }
  453. } else {
  454. new_active = document.querySelector('.not_read');
  455. }
  456. toggleContent(new_active, old_active, skipping);
  457. }
  458. function prev_feed() {
  459. let found = false;
  460. let adjacent = null;
  461. const feeds = document.querySelectorAll('#aside_feed .feed');
  462. for (let i = feeds.length - 1; i >= 0; i--) {
  463. const feed = feeds[i];
  464. if (feed.classList.contains('active')) {
  465. found = true;
  466. continue;
  467. }
  468. if (!found) {
  469. continue;
  470. }
  471. if (getComputedStyle(feed).display === 'none') {
  472. continue;
  473. }
  474. if (feed.dataset.unread != 0) {
  475. return delayedClick(feed.querySelector('a.item-title'));
  476. } else if (adjacent === null) {
  477. adjacent = feed;
  478. }
  479. }
  480. if (found) {
  481. delayedClick(adjacent.querySelector('a.item-title'));
  482. } else {
  483. last_feed();
  484. }
  485. }
  486. function next_feed() {
  487. let found = false;
  488. let adjacent = null;
  489. const feeds = document.querySelectorAll('#aside_feed .feed');
  490. for (let i = 0; i < feeds.length; i++) {
  491. const feed = feeds[i];
  492. if (feed.classList.contains('active')) {
  493. found = true;
  494. continue;
  495. }
  496. if (!found) {
  497. continue;
  498. }
  499. if (getComputedStyle(feed).display === 'none') {
  500. continue;
  501. }
  502. if (feed.dataset.unread != 0) {
  503. return delayedClick(feed.querySelector('a.item-title'));
  504. } else if (adjacent === null) {
  505. adjacent = feed;
  506. }
  507. }
  508. if (found) {
  509. delayedClick(adjacent.querySelector('a.item-title'));
  510. } else {
  511. first_feed();
  512. }
  513. }
  514. function first_feed() {
  515. const a = document.querySelector('#aside_feed .category.active .feed:not([data-unread="0"]) a.item-title');
  516. delayedClick(a);
  517. }
  518. function last_feed() {
  519. const links = document.querySelectorAll('#aside_feed .category.active .feed:not([data-unread="0"]) a.item-title');
  520. if (links && links.length > 0) {
  521. delayedClick(links[links.length - 1]);
  522. }
  523. }
  524. function prev_category() {
  525. const active_cat = document.querySelector('#aside_feed .category.active');
  526. if (active_cat) {
  527. let cat = active_cat;
  528. do cat = cat.previousElementSibling;
  529. while (cat && getComputedStyle(cat).display === 'none');
  530. if (cat) {
  531. delayedClick(cat.querySelector('a.title'));
  532. }
  533. } else {
  534. last_category();
  535. }
  536. }
  537. function next_category() {
  538. const active_cat = document.querySelector('#aside_feed .category.active');
  539. if (active_cat) {
  540. let cat = active_cat;
  541. do cat = cat.nextElementSibling;
  542. while (cat && getComputedStyle(cat).display === 'none');
  543. if (cat) {
  544. delayedClick(cat.querySelector('a.title'));
  545. }
  546. } else {
  547. first_category();
  548. }
  549. }
  550. function next_unread_category() {
  551. const active_cat = document.querySelector('#aside_feed .category.active');
  552. if (active_cat) {
  553. let cat = active_cat;
  554. do cat = cat.nextElementSibling;
  555. while (cat && cat.getAttribute('data-unread') <= 0);
  556. if (cat) {
  557. delayedClick(cat.querySelector('a.title'));
  558. }
  559. } else {
  560. first_category();
  561. }
  562. }
  563. function first_category() {
  564. const a = document.querySelector('#aside_feed .category:not([data-unread="0"]) a.title');
  565. delayedClick(a);
  566. }
  567. function last_category() {
  568. const links = document.querySelectorAll('#aside_feed .category:not([data-unread="0"]) a.title');
  569. if (links && links.length > 0) {
  570. delayedClick(links[links.length - 1]);
  571. }
  572. }
  573. function collapse_entry() {
  574. const flux_current = document.querySelector('.flux.current');
  575. toggleContent(flux_current, flux_current, false);
  576. }
  577. function toggle_media() {
  578. const media = document.querySelector('.flux.current video,.flux.current audio');
  579. if (media === null) {
  580. return;
  581. }
  582. if (media.paused) {
  583. media.play();
  584. } else {
  585. media.pause();
  586. }
  587. }
  588. function user_filter(key) {
  589. const filter = document.getElementById('dropdown-query');
  590. const filters = filter.parentElement.querySelectorAll('.dropdown-menu > .query > a');
  591. if (typeof key === 'undefined') {
  592. if (!filters.length) {
  593. return;
  594. }
  595. // Display the filter div
  596. location.hash = filter.id;
  597. // Force scrolling to the filter div
  598. const scroll = needsScroll(document.querySelector('.header'));
  599. if (scroll !== 0) {
  600. document.scrollingElement.scrollTop = scroll;
  601. }
  602. // Force the key value if there is only one action, so we can trigger it automatically
  603. if (filters.length === 1) {
  604. key = 1;
  605. } else {
  606. return;
  607. }
  608. }
  609. // Trigger selected share action
  610. key = parseInt(key);
  611. if (key <= filters.length) {
  612. filters[key - 1].click();
  613. }
  614. }
  615. function auto_share(key) {
  616. const share = document.querySelector('.flux.current.active .dropdown-target[id^="dropdown-share"]');
  617. if (!share) {
  618. return;
  619. }
  620. const shares = share.parentElement.querySelectorAll('.dropdown-menu .item a');
  621. if (typeof key === 'undefined') {
  622. // Display the share div
  623. location.hash = share.id;
  624. // Force scrolling to the share div
  625. const scrollTop = needsScroll(share.closest('.bottom'));
  626. if (scrollTop !== 0) {
  627. document.scrollingElement.scrollTop = scrollTop;
  628. }
  629. // Force the key value if there is only one action, so we can trigger it automatically
  630. if (shares.length === 1) {
  631. key = 1;
  632. } else {
  633. return;
  634. }
  635. }
  636. // Trigger selected share action and hide the share div
  637. key = parseInt(key);
  638. if (key <= shares.length) {
  639. shares[key - 1].click();
  640. share.parentElement.querySelector('.dropdown-menu + a.dropdown-close').click();
  641. }
  642. }
  643. let box_to_follow;
  644. function onScroll() {
  645. if (!box_to_follow) {
  646. return;
  647. }
  648. if (context.auto_mark_scroll) {
  649. const minTop = 40 + box_to_follow.scrollTop;
  650. document.querySelectorAll('.not_read:not(.keep_unread)').forEach(function (div) {
  651. if (div.offsetHeight > 0 &&
  652. div.offsetParent.offsetTop + div.offsetTop + div.offsetHeight < minTop) {
  653. mark_read(div, true, true);
  654. }
  655. });
  656. }
  657. if (context.auto_load_more) {
  658. const streamFooter = document.getElementById('stream-footer');
  659. if (streamFooter && box_to_follow.offsetHeight > 0 &&
  660. box_to_follow.scrollTop + box_to_follow.offsetHeight + (window.innerHeight / 2) >= streamFooter.offsetTop) {
  661. load_more_posts();
  662. }
  663. }
  664. }
  665. function init_posts() {
  666. if (context.auto_load_more || context.auto_mark_scroll || context.auto_remove_article) {
  667. box_to_follow = context.current_view === 'global' ? document.getElementById('panel') : document.scrollingElement;
  668. let lastScroll = 0; // Throttle
  669. let timerId = 0;
  670. (box_to_follow === document.scrollingElement ? window : box_to_follow).onscroll = function () {
  671. clearTimeout(timerId);
  672. if (lastScroll + 500 < Date.now()) {
  673. lastScroll = Date.now();
  674. onScroll();
  675. } else {
  676. timerId = setTimeout(onScroll, 500);
  677. }
  678. };
  679. onScroll();
  680. }
  681. if (!navigator.share && document.styleSheets.length > 0) {
  682. // https://developer.mozilla.org/en-US/docs/Web/API/Navigator/share
  683. // do not show the menu entry if browser does not support navigator.share
  684. document.styleSheets[0].insertRule(
  685. 'button.as-link[data-type="web-sharing-api"] {display: none !important;}',
  686. document.styleSheets[0].cssRules.length
  687. );
  688. }
  689. }
  690. function rememberOpenCategory(category_id, isOpen) {
  691. if (context.display_categories === 'remember') {
  692. const open_categories = JSON.parse(localStorage.getItem('FreshRSS_open_categories') || '{}');
  693. if (isOpen) {
  694. open_categories[category_id] = true;
  695. } else {
  696. delete open_categories[category_id];
  697. }
  698. localStorage.setItem('FreshRSS_open_categories', JSON.stringify(open_categories));
  699. }
  700. }
  701. function openCategory(category_id) {
  702. const category_element = document.getElementById(category_id);
  703. category_element.querySelector('.tree-folder-items').classList.add('active');
  704. const img = category_element.querySelector('a.dropdown-toggle img');
  705. img.src = img.src.replace('/icons/down.', '/icons/up.');
  706. img.alt = '🔼';
  707. }
  708. function loadJs(name) {
  709. if (!document.getElementById(name)) {
  710. const script = document.createElement('script');
  711. script.setAttribute('id', name);
  712. script.setAttribute('src', '../scripts/' + name + '?' + context.mtime[name]);
  713. script.setAttribute('defer', 'defer');
  714. script.setAttribute('async', 'async');
  715. document.head.appendChild(script);
  716. }
  717. }
  718. function init_column_categories() {
  719. if (context.current_view !== 'normal' && context.current_view !== 'reader') {
  720. return;
  721. }
  722. // Restore sidebar scroll position
  723. document.getElementById('sidebar').scrollTop = +sessionStorage.getItem('FreshRSS_sidebar_scrollTop');
  724. // Restore open categories
  725. if (context.display_categories === 'remember') {
  726. const open_categories = JSON.parse(localStorage.getItem('FreshRSS_open_categories') || '{}');
  727. Object.keys(open_categories).forEach(function (category_id) {
  728. openCategory(category_id);
  729. });
  730. }
  731. document.getElementById('aside_feed').onclick = function (ev) {
  732. let a = ev.target.closest('.tree-folder > .tree-folder-title > a.dropdown-toggle');
  733. if (a) {
  734. const icon = a.querySelector('.icon');
  735. const category_id = a.closest('.category').id;
  736. if (icon.alt === '🔽' || icon.innerHTML === '🔽') {
  737. if (icon.src) {
  738. icon.src = icon.src.replace('/icons/down.', '/icons/up.');
  739. icon.alt = '🔼';
  740. } else {
  741. icon.innerHTML = '🔼';
  742. }
  743. rememberOpenCategory(category_id, true);
  744. } else {
  745. if (icon.src) {
  746. icon.src = icon.src.replace('/icons/up.', '/icons/down.');
  747. icon.alt = '🔽';
  748. } else {
  749. icon.innerHTML = '🔽';
  750. }
  751. rememberOpenCategory(category_id, false);
  752. }
  753. const ul = a.closest('li').querySelector('.tree-folder-items');
  754. let nbVisibleItems = 0;
  755. for (let i = ul.children.length - 1; i >= 0; i--) {
  756. if (ul.children[i].offsetHeight) {
  757. nbVisibleItems++;
  758. }
  759. }
  760. ul.classList.toggle('active');
  761. // CSS transition does not work on max-height:auto
  762. ul.style.maxHeight = ul.classList.contains('active') ? (nbVisibleItems * 4) + 'em' : 0;
  763. return false;
  764. }
  765. a = ev.target.closest('.tree-folder-items > .feed .dropdown-toggle');
  766. if (a) {
  767. loadJs('extra.js');
  768. loadJs('feed.js');
  769. const itemId = a.closest('.item').id;
  770. const templateId = itemId.substring(0, 2) === 't_' ? 'tag_config_template' : 'feed_config_template';
  771. const id = itemId.substr(2);
  772. const feed_web = a.getAttribute('data-fweb');
  773. const div = a.parentElement;
  774. const dropdownMenu = div.querySelector('.dropdown-menu');
  775. const template = document.getElementById(templateId)
  776. .innerHTML.replace(/------/g, id).replace('http://example.net/', feed_web);
  777. if (!dropdownMenu) {
  778. a.href = '#dropdown-' + id;
  779. div.querySelector('.dropdown-target').id = 'dropdown-' + id;
  780. div.insertAdjacentHTML('beforeend', template);
  781. if (feed_web.length < 1) {
  782. div.querySelector('.item.link.website').remove();
  783. }
  784. const b = div.querySelector('button.confirm');
  785. if (b) {
  786. b.disabled = false;
  787. }
  788. } else if (getComputedStyle(dropdownMenu).display === 'none') {
  789. const id2 = div.closest('.item').id.substr(2);
  790. a.href = '#dropdown-' + id2;
  791. } else {
  792. a.href = '#close';
  793. }
  794. return true;
  795. }
  796. return true;
  797. };
  798. }
  799. function init_shortcuts() {
  800. Object.keys(context.shortcuts).forEach(function (k) {
  801. context.shortcuts[k] = (context.shortcuts[k] || '').toUpperCase();
  802. });
  803. document.addEventListener('keydown', ev => {
  804. if (ev.target.closest('input, textarea') ||
  805. ev.ctrlKey || ev.metaKey || (ev.altKey && ev.shiftKey)) {
  806. return;
  807. }
  808. const s = context.shortcuts;
  809. let k = (ev.key.trim() || ev.code || 'Space').toUpperCase();
  810. // IE11
  811. if (k === 'SPACEBAR') k = 'SPACE';
  812. else if (k === 'DEL') k = 'DELETE';
  813. else if (k === 'ESC') k = 'ESCAPE';
  814. if (location.hash.match(/^#dropdown-/)) {
  815. const n = parseInt(k);
  816. if (n) {
  817. if (location.hash === '#dropdown-query') {
  818. user_filter(n);
  819. } else {
  820. auto_share(n);
  821. }
  822. ev.preventDefault();
  823. return;
  824. }
  825. }
  826. if (k === s.actualize) {
  827. const btn = document.getElementById('actualize');
  828. if (btn) {
  829. btn.click();
  830. }
  831. ev.preventDefault();
  832. return;
  833. }
  834. if (k === s.next_entry) {
  835. if (ev.altKey) {
  836. next_category();
  837. } else if (ev.shiftKey) {
  838. next_feed();
  839. } else {
  840. next_entry(false);
  841. }
  842. ev.preventDefault();
  843. return;
  844. }
  845. if (k === s.next_unread_entry) {
  846. if (ev.altKey) {
  847. next_unread_category();
  848. } else if (ev.shiftKey) {
  849. next_feed();
  850. } else {
  851. next_unread_entry(false);
  852. }
  853. ev.preventDefault();
  854. return;
  855. }
  856. if (k === s.prev_entry) {
  857. if (ev.altKey) {
  858. prev_category();
  859. } else if (ev.shiftKey) {
  860. prev_feed();
  861. } else {
  862. prev_entry(false);
  863. }
  864. ev.preventDefault();
  865. return;
  866. }
  867. if (k === s.mark_read) {
  868. if (ev.altKey) {
  869. mark_previous_read(document.querySelector('.flux.current'));
  870. } else if (ev.shiftKey) {
  871. document.querySelector('.nav_menu .read_all').click();
  872. } else { // Toggle the read state
  873. mark_read(document.querySelector('.flux.current'), false, false);
  874. }
  875. ev.preventDefault();
  876. return;
  877. }
  878. if (k === s.first_entry) {
  879. if (ev.altKey) {
  880. first_category();
  881. } else if (ev.shiftKey) {
  882. first_feed();
  883. } else {
  884. const old_active = document.querySelector('.flux.current');
  885. const first = document.querySelector('.flux');
  886. if (first.classList.contains('flux')) {
  887. toggleContent(first, old_active, false);
  888. }
  889. }
  890. ev.preventDefault();
  891. return;
  892. }
  893. if (k === s.last_entry) {
  894. if (ev.altKey) {
  895. last_category();
  896. } else if (ev.shiftKey) {
  897. last_feed();
  898. } else {
  899. const old_active = document.querySelector('.flux.current');
  900. const last = document.querySelector('.flux:last-of-type');
  901. if (last.classList.contains('flux')) {
  902. toggleContent(last, old_active, false);
  903. }
  904. }
  905. ev.preventDefault();
  906. return;
  907. }
  908. if (ev.altKey || ev.shiftKey) {
  909. return;
  910. }
  911. if (k === s.mark_favorite) { // Toggle the favorite state
  912. mark_favorite(document.querySelector('.flux.current'));
  913. ev.preventDefault();
  914. return;
  915. }
  916. if (k === s.go_website) {
  917. if (context.auto_mark_site) {
  918. mark_read(document.querySelector('.flux.current'), true, false);
  919. }
  920. const newWindow = window.open();
  921. if (newWindow) {
  922. newWindow.opener = null;
  923. newWindow.location = document.querySelector('.flux.current a.go_website').href;
  924. }
  925. ev.preventDefault();
  926. return;
  927. }
  928. if (k === s.skip_next_entry) { next_entry(true); ev.preventDefault(); return; }
  929. if (k === s.skip_prev_entry) { prev_entry(true); ev.preventDefault(); return; }
  930. if (k === s.collapse_entry) { collapse_entry(); ev.preventDefault(); return; }
  931. if (k === s.auto_share) { auto_share(); ev.preventDefault(); return; }
  932. if (k === s.user_filter) { user_filter(); ev.preventDefault(); return; }
  933. if (k === s.load_more) { load_more_posts(); ev.preventDefault(); return; }
  934. if (k === s.close_dropdown) { location.hash = null; ev.preventDefault(); return; }
  935. if (k === s.help) { window.open(context.urls.help); ev.preventDefault(); return; }
  936. if (k === s.focus_search) { document.getElementById('search').focus(); ev.preventDefault(); return; }
  937. if (k === s.normal_view) { delayedClick(document.querySelector('#nav_menu_views .view-normal')); ev.preventDefault(); return; }
  938. if (k === s.reading_view) { delayedClick(document.querySelector('#nav_menu_views .view-reader')); ev.preventDefault(); return; }
  939. if (k === s.global_view) { delayedClick(document.querySelector('#nav_menu_views .view-global')); ev.preventDefault(); return; }
  940. if (k === s.rss_view) { delayedClick(document.querySelector('#nav_menu_views .view-rss')); ev.preventDefault(); return; }
  941. if (k === s.toggle_media) { toggle_media(); ev.preventDefault(); }
  942. });
  943. }
  944. function init_stream(stream) {
  945. stream.onclick = function (ev) {
  946. let el = ev.target.closest('.flux a.read');
  947. if (el) {
  948. mark_read(el.closest('.flux'), false, false);
  949. return false;
  950. }
  951. el = ev.target.closest('.flux a.bookmark');
  952. if (el) {
  953. mark_favorite(el.closest('.flux'));
  954. return false;
  955. }
  956. el = ev.target.closest('.dynamictags');
  957. if (el) {
  958. loadDynamicTags(el);
  959. return true;
  960. }
  961. el = ev.target.closest('.item.title > a');
  962. if (el) { // Allow default control-click behaviour such as open in background-tab
  963. return ev.ctrlKey;
  964. }
  965. el = ev.target.closest('.flux .content .text a');
  966. if (el) {
  967. if (!el.closest('div').classList.contains('author')) {
  968. el.target = '_blank';
  969. el.rel = 'noreferrer';
  970. }
  971. return true;
  972. }
  973. el = ev.target.closest('.item.share > button[data-type="print"]');
  974. if (el) { // Print
  975. const tmp_window = window.open();
  976. for (let i = 0; i < document.styleSheets.length; i++) {
  977. tmp_window.document.writeln('<link href="' + document.styleSheets[i].href + '" rel="stylesheet" type="text/css" />');
  978. }
  979. tmp_window.document.writeln(el.closest('.flux_content').querySelector('.content').innerHTML);
  980. tmp_window.document.close();
  981. tmp_window.focus();
  982. tmp_window.print();
  983. tmp_window.close();
  984. return false;
  985. }
  986. el = ev.target.closest('.item.share > button[data-type="clipboard"]');
  987. if (el && navigator.clipboard) { // Clipboard
  988. navigator.clipboard.writeText(el.dataset.url);
  989. return false;
  990. }
  991. el = ev.target.closest('.item.share > button[data-type="web-sharing-api"]');
  992. if (el && navigator.share) { // https://developer.mozilla.org/en-US/docs/Web/API/Navigator/share
  993. const shareData = {
  994. url: el.dataset.url,
  995. title: decodeURI(el.dataset.title),
  996. };
  997. navigator.share(shareData);
  998. return false;
  999. }
  1000. el = ev.target.closest('.item.share > a[href="POST"]');
  1001. if (el) { // Share by POST
  1002. const f = el.parentElement.querySelector('form');
  1003. f.disabled = false;
  1004. f.submit();
  1005. return false;
  1006. }
  1007. el = ev.target.closest('.flux_header, .flux_content');
  1008. if (el) { // flux_toggle
  1009. if (ev.target.closest('.content, .item.website, .item.link, .dropdown')) {
  1010. return true;
  1011. }
  1012. if (!context.sides_close_article && ev.target.matches('div.flux_content')) {
  1013. // setting for not-closing after clicking outside article area
  1014. return false;
  1015. }
  1016. const old_active = document.querySelector('.flux.current');
  1017. const new_active = el.parentNode;
  1018. if (ev.target.tagName.toUpperCase() === 'A') { // Leave real links alone (but does not catch img in a link)
  1019. if (context.auto_mark_article) {
  1020. mark_read(new_active, true, false);
  1021. }
  1022. return true;
  1023. }
  1024. toggleContent(new_active, old_active, false);
  1025. return false;
  1026. }
  1027. };
  1028. stream.onmouseup = function (ev) { // Mouseup enables us to catch middle click, and control+click in IE/Edge
  1029. if (ev.altKey || ev.metaKey || ev.shiftKey) {
  1030. return;
  1031. }
  1032. let el = ev.target.closest('.item.title > a');
  1033. if (el) {
  1034. if (ev.which == 1) {
  1035. if (ev.ctrlKey) { // Control+click
  1036. if (context.auto_mark_site) {
  1037. mark_read(el.closest('.flux'), true, false);
  1038. }
  1039. } else {
  1040. el.parentElement.click(); // Normal click, just toggle article.
  1041. }
  1042. } else if (ev.which == 2 && !ev.ctrlKey) { // Simple middle click: same behaviour as CTRL+click
  1043. if (context.auto_mark_article) {
  1044. const new_active = el.closest('.flux');
  1045. mark_read(new_active, true, false);
  1046. }
  1047. }
  1048. return;
  1049. }
  1050. if (context.auto_mark_site) {
  1051. // catch mouseup instead of click so we can have the correct behaviour
  1052. // with middle button click (scroll button).
  1053. el = ev.target.closest('.flux .link > a');
  1054. if (el) {
  1055. if (ev.which == 3) {
  1056. return;
  1057. }
  1058. mark_read(el.closest('.flux'), true, false);
  1059. }
  1060. }
  1061. };
  1062. stream.onchange = function (ev) {
  1063. const checkboxTag = ev.target.closest('.checkboxTag');
  1064. if (checkboxTag) { // Dynamic tags
  1065. ev.stopPropagation();
  1066. const tagId = checkboxTag.name.replace(/^t_/, '');
  1067. const tagName = checkboxTag.nextElementSibling ? checkboxTag.nextElementSibling.childNodes[0].value : '';
  1068. if ((tagId == 0 && tagName.length > 0) || tagId != 0) {
  1069. const isChecked = checkboxTag.checked;
  1070. const entry = checkboxTag.closest('div.flux');
  1071. const entryId = entry.id.replace(/^flux_/, '');
  1072. checkboxTag.disabled = true;
  1073. const req = new XMLHttpRequest();
  1074. req.open('POST', './?c=tag&a=tagEntry', true);
  1075. req.responseType = 'json';
  1076. req.onerror = function (e) {
  1077. checkboxTag.checked = !isChecked;
  1078. badAjax(this.status == 403);
  1079. };
  1080. req.onload = function (e) {
  1081. if (this.status != 200) {
  1082. return req.onerror(e);
  1083. }
  1084. if (entry.classList.contains('not_read')) {
  1085. incUnreadsTag('t_' + tagId, isChecked ? 1 : -1);
  1086. }
  1087. };
  1088. req.onloadend = function (e) {
  1089. checkboxTag.disabled = false;
  1090. if (tagId == 0) {
  1091. loadDynamicTags(checkboxTag.closest('div.dropdown'));
  1092. }
  1093. };
  1094. req.setRequestHeader('Content-Type', 'application/json');
  1095. req.send(JSON.stringify({
  1096. _csrf: context.csrf,
  1097. id_tag: tagId,
  1098. name_tag: tagId == 0 ? tagName : '',
  1099. id_entry: entryId,
  1100. checked: isChecked,
  1101. ajax: 1,
  1102. }));
  1103. }
  1104. }
  1105. };
  1106. }
  1107. function init_nav_entries() {
  1108. const nav_entries = document.getElementById('nav_entries');
  1109. if (nav_entries) {
  1110. nav_entries.querySelector('.previous_entry').onclick = function (e) {
  1111. prev_entry(false);
  1112. return false;
  1113. };
  1114. nav_entries.querySelector('.next_entry').onclick = function (e) {
  1115. next_entry(false);
  1116. return false;
  1117. };
  1118. nav_entries.querySelector('.up').onclick = function (e) {
  1119. const active_item = (document.querySelector('.flux.current') || document.querySelector('.flux'));
  1120. const windowTop = document.scrollingElement.scrollTop;
  1121. const item_top = active_item.offsetParent.offsetTop + active_item.offsetTop;
  1122. document.scrollingElement.scrollTop = windowTop > item_top ? item_top : 0;
  1123. return false;
  1124. };
  1125. }
  1126. }
  1127. function loadDynamicTags(div) {
  1128. div.classList.remove('dynamictags');
  1129. div.querySelectorAll('li.item').forEach(function (li) { li.remove(); });
  1130. const entryId = div.closest('div.flux').id.replace(/^flux_/, '');
  1131. const req = new XMLHttpRequest();
  1132. req.open('GET', './?c=tag&a=getTagsForEntry&id_entry=' + entryId, true);
  1133. req.responseType = 'json';
  1134. req.onerror = function (e) {
  1135. div.querySelectorAll('li.item').forEach(function (li) { li.remove(); });
  1136. div.classList.add('dynamictags');
  1137. };
  1138. req.onload = function (e) {
  1139. if (this.status != 200) {
  1140. return req.onerror(e);
  1141. }
  1142. const json = xmlHttpRequestJson(this);
  1143. if (!json) {
  1144. return req.onerror(e);
  1145. }
  1146. const li_item0 = document.createElement('li');
  1147. li_item0.setAttribute('class', 'item addItem');
  1148. const label = document.createElement('label');
  1149. label.setAttribute('class', 'noHover');
  1150. const input_checkboxTag = document.createElement('input');
  1151. input_checkboxTag.setAttribute('class', 'checkboxTag checkboxNewTag');
  1152. input_checkboxTag.setAttribute('name', 't_0');
  1153. input_checkboxTag.setAttribute('type', 'checkbox');
  1154. const input_newTag = document.createElement('input');
  1155. input_newTag.setAttribute('type', 'text');
  1156. input_newTag.setAttribute('name', 'newTag');
  1157. input_newTag.addEventListener('keydown', function (ev) { if (ev.key.toUpperCase() == 'ENTER') { this.parentNode.previousSibling.click(); } });
  1158. const button_btn = document.createElement('button');
  1159. button_btn.setAttribute('type', 'button');
  1160. button_btn.setAttribute('class', 'btn');
  1161. button_btn.addEventListener('click', function () { this.parentNode.parentNode.click(); });
  1162. const text_plus = document.createTextNode('+');
  1163. const div_stick = document.createElement('div');
  1164. div_stick.setAttribute('class', 'stick');
  1165. button_btn.appendChild(text_plus);
  1166. div_stick.appendChild(input_newTag);
  1167. div_stick.appendChild(button_btn);
  1168. label.appendChild(input_checkboxTag);
  1169. label.appendChild(div_stick);
  1170. li_item0.appendChild(label);
  1171. div.querySelector('.dropdown-menu').appendChild(li_item0);
  1172. let html = '';
  1173. if (json && json.length) {
  1174. for (let i = 0; i < json.length; i++) {
  1175. const tag = json[i];
  1176. html += '<li class="item"><label><input class="checkboxTag" name="t_' + tag.id + '" type="checkbox"' +
  1177. (tag.checked ? ' checked="checked"' : '') + '> ' + tag.name + '</label></li>';
  1178. }
  1179. }
  1180. div.querySelector('.dropdown-menu').insertAdjacentHTML('beforeend', html);
  1181. };
  1182. req.send();
  1183. }
  1184. // <actualize>
  1185. let feeds_processed = 0;
  1186. let categories_processed = 0;
  1187. let to_process = 0;
  1188. function refreshFeed(feeds, feeds_count) {
  1189. const feed = feeds.pop();
  1190. if (!feed) {
  1191. return;
  1192. }
  1193. const req = new XMLHttpRequest();
  1194. req.open('POST', feed.url, true);
  1195. req.onloadend = function (e) {
  1196. feeds_processed++;
  1197. if (this.status != 200) {
  1198. badAjax(false);
  1199. } else {
  1200. const div = document.getElementById('actualizeProgress');
  1201. div.querySelector('.progress').innerHTML = (categories_processed + feeds_processed) + ' / ' + to_process;
  1202. div.querySelector('.title').innerHTML = feed.title;
  1203. }
  1204. if (feeds_processed === feeds_count) {
  1205. // Empty request to commit new articles
  1206. const req2 = new XMLHttpRequest();
  1207. req2.open('POST', './?c=feed&a=actualize&id=-1&ajax=1', true);
  1208. req2.onloadend = function (e) {
  1209. delayedFunction(function () { location.reload(); });
  1210. };
  1211. req2.setRequestHeader('Content-Type', 'application/json');
  1212. req2.send(JSON.stringify({
  1213. _csrf: context.csrf,
  1214. noCommit: 0,
  1215. }));
  1216. } else {
  1217. refreshFeed(feeds, feeds_count);
  1218. }
  1219. };
  1220. req.setRequestHeader('Content-Type', 'application/json');
  1221. req.send(JSON.stringify({
  1222. _csrf: context.csrf,
  1223. noCommit: 1,
  1224. }));
  1225. }
  1226. function refreshFeeds(json) {
  1227. feeds_processed = 0;
  1228. if (!json.feeds || json.feeds.length === 0) {
  1229. // Empty request to commit new articles
  1230. const req2 = new XMLHttpRequest();
  1231. req2.open('POST', './?c=feed&a=actualize&id=-1&ajax=1', true);
  1232. req2.onloadend = function (e) {
  1233. context.ajax_loading = false;
  1234. };
  1235. req2.setRequestHeader('Content-Type', 'application/json');
  1236. req2.send(JSON.stringify({
  1237. _csrf: context.csrf,
  1238. noCommit: 0,
  1239. }));
  1240. } else {
  1241. const feeds_count = json.feeds.length;
  1242. for (let i = 10; i > 0; i--) {
  1243. refreshFeed(json.feeds, feeds_count);
  1244. }
  1245. }
  1246. }
  1247. function refreshDynamicOpml(categories, categories_count, next) {
  1248. const category = categories.pop();
  1249. if (!category) {
  1250. return;
  1251. }
  1252. const req = new XMLHttpRequest();
  1253. req.open('POST', category.url, true);
  1254. req.onloadend = function (e) {
  1255. categories_processed++;
  1256. if (this.status != 200) {
  1257. badAjax(false);
  1258. } else {
  1259. const div = document.getElementById('actualizeProgress');
  1260. div.querySelector('.progress').innerHTML = (categories_processed + feeds_processed) + ' / ' + to_process;
  1261. div.querySelector('.title').innerHTML = category.title;
  1262. }
  1263. if (categories_processed === categories_count) {
  1264. if (next) { next(); }
  1265. } else {
  1266. refreshDynamicOpml(categories, categories_count, next);
  1267. }
  1268. };
  1269. req.setRequestHeader('Content-Type', 'application/json');
  1270. req.send(JSON.stringify({
  1271. _csrf: context.csrf,
  1272. noCommit: 1,
  1273. }));
  1274. }
  1275. function refreshDynamicOpmls(json, next) {
  1276. categories_processed = 0;
  1277. if (json.categories && json.categories.length > 0) {
  1278. const categories_count = json.categories.length;
  1279. for (let i = 10; i > 0; i--) {
  1280. refreshDynamicOpml(json.categories, categories_count, next);
  1281. }
  1282. } else {
  1283. if (next) { next(); }
  1284. }
  1285. }
  1286. function init_actualize() {
  1287. let auto = false;
  1288. let nbCategoriesFirstRound = 0;
  1289. let skipCategories = false;
  1290. const actualize = document.getElementById('actualize');
  1291. if (!actualize) {
  1292. return;
  1293. }
  1294. actualize.onclick = function () {
  1295. if (context.ajax_loading) {
  1296. return false;
  1297. }
  1298. context.ajax_loading = true;
  1299. const req = new XMLHttpRequest();
  1300. req.open('POST', './?c=javascript&a=actualize', true);
  1301. req.responseType = 'json';
  1302. req.onload = function (e) {
  1303. if (this.status != 200) {
  1304. return badAjax(false);
  1305. }
  1306. const json = xmlHttpRequestJson(this);
  1307. if (!json) {
  1308. return badAjax(false);
  1309. }
  1310. if (auto && json.categories.length < 1 && json.feeds.length < 1) {
  1311. auto = false;
  1312. context.ajax_loading = false;
  1313. return false;
  1314. }
  1315. to_process = json.categories.length + json.feeds.length + nbCategoriesFirstRound;
  1316. if (json.categories.length + json.feeds.length > 0 && !document.getElementById('actualizeProgress')) {
  1317. document.body.insertAdjacentHTML('beforeend', '<div id="actualizeProgress" class="notification good">' +
  1318. json.feedback_actualize + '<br /><span class="title">/</span><br /><span class="progress">0 / ' +
  1319. to_process + '</span></div>');
  1320. } else {
  1321. openNotification(json.feedback_no_refresh, 'good');
  1322. }
  1323. if (json.categories.length > 0 && !skipCategories) {
  1324. skipCategories = true; // To avoid risk of infinite loop
  1325. nbCategoriesFirstRound = json.categories.length;
  1326. // If some dynamic OPML categories are refreshed, need to reload the list of feeds before updating them
  1327. refreshDynamicOpmls(json, () => {
  1328. context.ajax_loading = false;
  1329. actualize.click();
  1330. });
  1331. } else {
  1332. refreshFeeds(json);
  1333. }
  1334. };
  1335. req.setRequestHeader('Content-Type', 'application/json');
  1336. req.send(JSON.stringify({
  1337. _csrf: context.csrf,
  1338. }));
  1339. return false;
  1340. };
  1341. if (context.auto_actualize_feeds) {
  1342. auto = true;
  1343. actualize.click();
  1344. }
  1345. }
  1346. // </actualize>
  1347. // <notification>
  1348. let notification = null;
  1349. let notification_interval = null;
  1350. let notification_working = false;
  1351. function openNotification(msg, status) {
  1352. if (notification_working === true) {
  1353. return false;
  1354. }
  1355. notification_working = true;
  1356. notification.querySelector('.msg').innerHTML = msg;
  1357. notification.className = 'notification';
  1358. notification.classList.add(status);
  1359. if (status == 'good') {
  1360. notification_interval = setTimeout(closeNotification, 4000);
  1361. } else {
  1362. // no status or f.e. status = 'bad', give some more time to read
  1363. notification_interval = setTimeout(closeNotification, 8000);
  1364. }
  1365. }
  1366. function closeNotification() {
  1367. notification.classList.add('closed');
  1368. clearInterval(notification_interval);
  1369. notification_working = false;
  1370. }
  1371. function init_notifications() {
  1372. notification = document.getElementById('notification');
  1373. notification.querySelector('a.close').addEventListener('click', function (ev) {
  1374. closeNotification();
  1375. ev.preventDefault();
  1376. return false;
  1377. });
  1378. notification.addEventListener('mouseenter', function () {
  1379. clearInterval(notification_interval);
  1380. });
  1381. notification.addEventListener('mouseleave', function () {
  1382. notification_interval = setTimeout(closeNotification, 3000);
  1383. });
  1384. if (notification.querySelector('.msg').innerHTML.length > 0) {
  1385. notification_working = true;
  1386. if (notification.classList.contains('good')) {
  1387. notification_interval = setTimeout(closeNotification, 4000);
  1388. } else {
  1389. // no status or f.e. status = 'bad', give some more time to read
  1390. notification_interval = setTimeout(closeNotification, 8000);
  1391. }
  1392. }
  1393. }
  1394. // </notification>
  1395. // <notifs html5>
  1396. let notifs_html5_permission = 'denied';
  1397. function notifs_html5_is_supported() {
  1398. return window.Notification !== undefined;
  1399. }
  1400. function notifs_html5_ask_permission() {
  1401. window.Notification.requestPermission(function () {
  1402. notifs_html5_permission = window.Notification.permission;
  1403. });
  1404. }
  1405. function notifs_html5_show(nb, nb_new) {
  1406. if (notifs_html5_permission !== 'granted') {
  1407. return;
  1408. }
  1409. const notification = new window.Notification(context.i18n.notif_title_articles, {
  1410. icon: '../themes/icons/favicon-256-padding.png',
  1411. body: context.i18n.notif_body_new_articles.replace('%d', nb_new) + ' ' + context.i18n.notif_body_unread_articles.replace('%d', nb),
  1412. tag: 'freshRssNewArticles',
  1413. });
  1414. notification.onclick = function () {
  1415. delayedFunction(function () {
  1416. location.reload();
  1417. window.focus();
  1418. notification.close();
  1419. });
  1420. };
  1421. if (context.html5_notif_timeout !== 0) {
  1422. setTimeout(function () {
  1423. notification.close();
  1424. }, context.html5_notif_timeout * 1000);
  1425. }
  1426. }
  1427. function init_notifs_html5() {
  1428. if (!notifs_html5_is_supported()) {
  1429. return;
  1430. }
  1431. notifs_html5_permission = notifs_html5_ask_permission();
  1432. }
  1433. // </notifs html5>
  1434. function refreshUnreads() {
  1435. const req = new XMLHttpRequest();
  1436. req.open('GET', './?c=javascript&a=nbUnreadsPerFeed', true);
  1437. req.responseType = 'json';
  1438. req.onload = function (e) {
  1439. const json = xmlHttpRequestJson(this);
  1440. if (!json) {
  1441. return badAjax(false);
  1442. }
  1443. const isAll = document.querySelector('.category.all.active');
  1444. let new_articles = false;
  1445. let nbUnreadFeeds = 0;
  1446. const title = document.querySelector('.category.all .title');
  1447. const nb_unreads_before = title ? str2int(title.getAttribute('data-unread')) : 0;
  1448. Object.keys(json.feeds).forEach(function (feed_id) {
  1449. const nbUnreads = json.feeds[feed_id];
  1450. nbUnreadFeeds += nbUnreads;
  1451. feed_id = 'f_' + feed_id;
  1452. const elem = document.getElementById(feed_id);
  1453. const feed_unreads = elem ? str2int(elem.getAttribute('data-unread')) : 0;
  1454. if ((incUnreadsFeed(null, feed_id, nbUnreads - feed_unreads) || isAll) && // Update of current view?
  1455. (nbUnreads - feed_unreads > 0)) {
  1456. const newArticle = document.getElementById('new-article');
  1457. newArticle.setAttribute('aria-hidden', 'false');
  1458. newArticle.style.display = 'block';
  1459. new_articles = true;
  1460. }
  1461. });
  1462. const noArticlesToShow_div = document.getElementById('noArticlesToShow');
  1463. if (nbUnreadFeeds > 0 && noArticlesToShow_div) {
  1464. noArticlesToShow_div.classList.add('hide');
  1465. }
  1466. let nbUnreadTags = 0;
  1467. Object.keys(json.tags).forEach(function (tag_id) {
  1468. const nbUnreads = json.tags[tag_id];
  1469. nbUnreadTags += nbUnreads;
  1470. const tag = document.getElementById('t_' + tag_id);
  1471. if (tag) {
  1472. tag.setAttribute('data-unread', nbUnreads);
  1473. tag.querySelector('.item-title').setAttribute('data-unread', numberFormat(nbUnreads));
  1474. }
  1475. });
  1476. const tags = document.querySelector('.category.tags');
  1477. if (tags) {
  1478. tags.setAttribute('data-unread', nbUnreadTags);
  1479. tags.querySelector('.title').setAttribute('data-unread', numberFormat(nbUnreadTags));
  1480. }
  1481. const nb_unreads = title ? str2int(title.getAttribute('data-unread')) : 0;
  1482. if (nb_unreads > 0 && new_articles) {
  1483. faviconNbUnread(nb_unreads);
  1484. const nb_new = nb_unreads - nb_unreads_before;
  1485. notifs_html5_show(nb_unreads, nb_new);
  1486. }
  1487. };
  1488. req.send();
  1489. }
  1490. // <endless_mode>
  1491. let url_load_more = '';
  1492. let load_more = false;
  1493. let box_load_more = null;
  1494. function load_more_posts() {
  1495. if (load_more || !url_load_more || !box_load_more) {
  1496. return;
  1497. }
  1498. load_more = true;
  1499. document.getElementById('load_more').classList.add('loading');
  1500. const req = new XMLHttpRequest();
  1501. req.open('GET', url_load_more, true);
  1502. req.responseType = 'document';
  1503. req.onload = function (e) {
  1504. const html = this.response;
  1505. const streamFooter = document.getElementById('stream-footer');
  1506. const streamAdopted = document.adoptNode(html.getElementById('stream'));
  1507. streamAdopted.querySelectorAll('.flux, .day').forEach(function (div) {
  1508. box_load_more.insertBefore(div, streamFooter);
  1509. });
  1510. const streamFooterOld = streamFooter.querySelector('.stream-footer-inner');
  1511. const streamFooterNew = streamAdopted.querySelector('.stream-footer-inner');
  1512. streamFooter.replaceChild(streamFooterNew, streamFooterOld);
  1513. const bigMarkAsRead = document.getElementById('bigMarkAsRead');
  1514. const readAll = document.querySelector('#nav_menu_read_all .read_all');
  1515. if (readAll && bigMarkAsRead && bigMarkAsRead.formAction) {
  1516. if (context.display_order === 'ASC') {
  1517. readAll.formAction = bigMarkAsRead.formAction;
  1518. } else {
  1519. bigMarkAsRead.formAction = readAll.formAction;
  1520. }
  1521. }
  1522. document.querySelectorAll('[id^=day_]').forEach(function (div) {
  1523. const ids = document.querySelectorAll('[id="' + div.id + '"]');
  1524. for (let i = ids.length - 1; i > 0; i--) { // Keep only the first
  1525. ids[i].remove();
  1526. }
  1527. });
  1528. init_load_more(box_load_more);
  1529. const div_load_more = document.getElementById('load_more');
  1530. if (bigMarkAsRead) {
  1531. bigMarkAsRead.removeAttribute('disabled');
  1532. }
  1533. if (div_load_more) {
  1534. div_load_more.classList.remove('loading');
  1535. }
  1536. load_more = false;
  1537. };
  1538. req.send();
  1539. }
  1540. const freshrssLoadMoreEvent = document.createEvent('Event');
  1541. freshrssLoadMoreEvent.initEvent('freshrss:load-more', true, true);
  1542. function init_load_more(box) {
  1543. box_load_more = box;
  1544. document.body.dispatchEvent(freshrssLoadMoreEvent);
  1545. const next_button = document.getElementById('load_more');
  1546. if (!next_button) {
  1547. // no more article to load
  1548. url_load_more = '';
  1549. return;
  1550. }
  1551. url_load_more = next_button.getAttribute('formaction');
  1552. next_button.onclick = function (e) {
  1553. load_more_posts();
  1554. return false;
  1555. };
  1556. }
  1557. // </endless_mode>
  1558. function init_confirm_action() {
  1559. document.body.onclick = function (ev) {
  1560. const b = ev.target.closest('.confirm');
  1561. if (b) {
  1562. let str_confirmation = this.getAttribute('data-str-confirm');
  1563. if (!str_confirmation) {
  1564. str_confirmation = context.i18n.confirmation_default;
  1565. }
  1566. return confirm(str_confirmation);
  1567. }
  1568. };
  1569. document.querySelectorAll('button.confirm').forEach(function (b) { b.disabled = false; });
  1570. }
  1571. function faviconNbUnread(n) {
  1572. if (typeof n === 'undefined') {
  1573. const t = document.querySelector('.category.all .title');
  1574. n = t ? str2int(t.getAttribute('data-unread')) : 0;
  1575. }
  1576. // http://remysharp.com/2010/08/24/dynamic-favicons/
  1577. const canvas = document.createElement('canvas');
  1578. const link = document.getElementById('favicon').cloneNode(true);
  1579. const ratio = window.devicePixelRatio;
  1580. if (canvas.getContext && link) {
  1581. canvas.height = canvas.width = 16 * ratio;
  1582. const img = document.createElement('img');
  1583. img.onload = function () {
  1584. const ctx = canvas.getContext('2d');
  1585. ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
  1586. if (n > 0) {
  1587. let text = '';
  1588. if (n < 1000) {
  1589. text = n;
  1590. } else if (n < 100000) {
  1591. text = Math.floor(n / 1000) + 'k';
  1592. } else {
  1593. text = 'E' + Math.floor(Math.log10(n));
  1594. }
  1595. ctx.font = 'bold ' + 9 * ratio + 'px "Arial", sans-serif';
  1596. ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
  1597. ctx.fillRect(0, 7 * ratio, ctx.measureText(text).width, 9 * ratio);
  1598. ctx.fillStyle = '#F00';
  1599. ctx.fillText(text, 0, canvas.height - 1);
  1600. }
  1601. link.href = canvas.toDataURL('image/png');
  1602. // Check if data URI has generated a real favicon and if not, fallback to standard icon
  1603. if (link.href.length > 180) {
  1604. document.querySelector('link[rel~=icon]').remove();
  1605. document.head.appendChild(link);
  1606. }
  1607. };
  1608. img.src = '../favicon.ico';
  1609. }
  1610. }
  1611. function removeFirstLoadSpinner() {
  1612. const first_load = document.getElementById('first_load');
  1613. if (first_load) {
  1614. first_load.remove();
  1615. }
  1616. }
  1617. function init_normal() {
  1618. const stream = document.getElementById('stream');
  1619. if (!stream) {
  1620. if (window.console) {
  1621. console.log('FreshRSS waiting for content…');
  1622. }
  1623. setTimeout(init_normal, 100);
  1624. return;
  1625. }
  1626. init_column_categories();
  1627. init_stream(stream);
  1628. init_actualize();
  1629. faviconNbUnread();
  1630. window.onbeforeunload = function (e) {
  1631. const sidebar = document.getElementById('sidebar');
  1632. if (sidebar) { // Save sidebar scroll position
  1633. sessionStorage.setItem('FreshRSS_sidebar_scrollTop', sidebar.scrollTop);
  1634. }
  1635. if (mark_read_queue && mark_read_queue.length > 0) {
  1636. return false;
  1637. }
  1638. };
  1639. }
  1640. function init_main_beforeDOM() {
  1641. document.scrollingElement.scrollTop = 0;
  1642. init_shortcuts();
  1643. if (['normal', 'reader', 'global'].indexOf(context.current_view) >= 0) {
  1644. init_normal();
  1645. }
  1646. }
  1647. function init_main_afterDOM() {
  1648. removeFirstLoadSpinner();
  1649. init_notifications();
  1650. init_confirm_action();
  1651. const stream = document.getElementById('stream');
  1652. if (stream) {
  1653. init_load_more(stream);
  1654. init_posts();
  1655. init_nav_entries();
  1656. init_notifs_html5();
  1657. setTimeout(faviconNbUnread, 1000);
  1658. setInterval(refreshUnreads, 120000);
  1659. }
  1660. if (window.console) {
  1661. console.log('FreshRSS main init done.');
  1662. }
  1663. }
  1664. init_main_beforeDOM(); // Can be called before DOM is fully loaded
  1665. if (document.readyState && document.readyState !== 'loading') {
  1666. init_main_afterDOM();
  1667. } else {
  1668. if (window.console) {
  1669. console.log('FreshRSS waiting for DOMContentLoaded…');
  1670. }
  1671. document.addEventListener('DOMContentLoaded', init_main_afterDOM, false);
  1672. }
  1673. // @license-end