4
0

main.js 74 KB

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