main.js 77 KB

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