main.js 77 KB

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