main.js 74 KB

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