main.js 74 KB

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