main.js 75 KB

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