main.js 71 KB

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