main.js 76 KB

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