]> Untitled Git - lemmy-ui.git/blob - src/shared/utils.ts
Some fixes.
[lemmy-ui.git] / src / shared / utils.ts
1 import "moment/locale/es";
2 import "moment/locale/el";
3 import "moment/locale/eu";
4 import "moment/locale/eo";
5 import "moment/locale/de";
6 import "moment/locale/zh-cn";
7 import "moment/locale/fr";
8 import "moment/locale/sv";
9 import "moment/locale/ru";
10 import "moment/locale/nl";
11 import "moment/locale/it";
12 import "moment/locale/fi";
13 import "moment/locale/ca";
14 import "moment/locale/fa";
15 import "moment/locale/pl";
16 import "moment/locale/pt-br";
17 import "moment/locale/ja";
18 import "moment/locale/ka";
19 import "moment/locale/hi";
20 import "moment/locale/gl";
21 import "moment/locale/tr";
22 import "moment/locale/hu";
23 import "moment/locale/uk";
24 import "moment/locale/sq";
25 import "moment/locale/km";
26 import "moment/locale/ga";
27 import "moment/locale/sr";
28 import "moment/locale/ko";
29 import "moment/locale/da";
30 import "moment/locale/hr";
31
32 import {
33   UserOperation,
34   CommentView,
35   LocalUserSettingsView,
36   SortType,
37   ListingType,
38   SearchType,
39   WebSocketResponse,
40   WebSocketJsonResponse,
41   Search,
42   SearchResponse,
43   PostView,
44   PrivateMessageView,
45   LemmyWebsocket,
46   PersonViewSafe,
47   CommunityView,
48 } from "lemmy-js-client";
49
50 import {
51   CommentSortType,
52   DataType,
53   IsoData,
54   CommentNode as CommentNodeI,
55 } from "./interfaces";
56 import { UserService, WebSocketService } from "./services";
57 var Tribute: any;
58 if (isBrowser()) {
59   Tribute = require("tributejs");
60 }
61 import markdown_it from "markdown-it";
62 import markdown_it_sub from "markdown-it-sub";
63 import markdown_it_sup from "markdown-it-sup";
64 import markdown_it_container from "markdown-it-container";
65 import emojiShortName from "emoji-short-name";
66 import Toastify from "toastify-js";
67 import tippy from "tippy.js";
68 import moment from "moment";
69 import { Subscription } from "rxjs";
70 import { retryWhen, delay, take } from "rxjs/operators";
71 import { i18n } from "./i18next";
72
73 export const wsClient = new LemmyWebsocket();
74
75 export const favIconUrl = "/static/assets/favicon.svg";
76 export const favIconPngUrl = "/static/assets/apple-touch-icon.png";
77 // TODO
78 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
79 export const repoUrl = "https://github.com/LemmyNet";
80 export const joinLemmyUrl = "https://join.lemmy.ml";
81 export const supportLemmyUrl = "https://join.lemmy.ml/support";
82 export const docsUrl = "https://join.lemmy.ml/docs/en/index.html";
83 export const helpGuideUrl = "https://join.lemmy.ml/docs/en/about/guide.html"; // TODO find a way to redirect to the non-en folder
84 export const markdownHelpUrl = `${helpGuideUrl}#markdown-guide`;
85 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
86 export const archiveUrl = "https://archive.is";
87 export const elementUrl = "https://element.io/";
88
89 export const postRefetchSeconds: number = 60 * 1000;
90 export const fetchLimit = 20;
91 export const mentionDropdownFetchLimit = 10;
92
93 export const languages = [
94   { code: "ca" },
95   { code: "en" },
96   { code: "el" },
97   { code: "eu" },
98   { code: "eo" },
99   { code: "es" },
100   { code: "da" },
101   { code: "de" },
102   { code: "ga" },
103   { code: "gl" },
104   { code: "hr" },
105   { code: "hu" },
106   { code: "ka" },
107   { code: "ko" },
108   { code: "km" },
109   { code: "hi" },
110   { code: "fa" },
111   { code: "ja" },
112   { code: "oc" },
113   { code: "pl" },
114   { code: "pt_BR" },
115   { code: "zh" },
116   { code: "fi" },
117   { code: "fr" },
118   { code: "sv" },
119   { code: "sq" },
120   { code: "sr_Latn" },
121   { code: "th" },
122   { code: "tr" },
123   { code: "uk" },
124   { code: "ru" },
125   { code: "nl" },
126   { code: "it" },
127 ];
128
129 export const themes = [
130   "litera",
131   "materia",
132   "minty",
133   "solar",
134   "united",
135   "cyborg",
136   "darkly",
137   "journal",
138   "sketchy",
139   "vaporwave",
140   "vaporwave-dark",
141   "i386",
142   "litely",
143 ];
144
145 const DEFAULT_ALPHABET =
146   "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
147
148 function getRandomCharFromAlphabet(alphabet: string): string {
149   return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
150 }
151
152 export function randomStr(
153   idDesiredLength = 20,
154   alphabet = DEFAULT_ALPHABET
155 ): string {
156   /**
157    * Create n-long array and map it to random chars from given alphabet.
158    * Then join individual chars as string
159    */
160   return Array.from({ length: idDesiredLength })
161     .map(() => {
162       return getRandomCharFromAlphabet(alphabet);
163     })
164     .join("");
165 }
166
167 export function wsJsonToRes<ResponseType>(
168   msg: WebSocketJsonResponse<ResponseType>
169 ): WebSocketResponse<ResponseType> {
170   return {
171     op: wsUserOp(msg),
172     data: msg.data,
173   };
174 }
175
176 export function wsUserOp(msg: any): UserOperation {
177   let opStr: string = msg.op;
178   return UserOperation[opStr];
179 }
180
181 export const md = new markdown_it({
182   html: false,
183   linkify: true,
184   typographer: true,
185 })
186   .use(markdown_it_sub)
187   .use(markdown_it_sup)
188   .use(markdown_it_container, "spoiler", {
189     validate: function (params: any) {
190       return params.trim().match(/^spoiler\s+(.*)$/);
191     },
192
193     render: function (tokens: any, idx: any) {
194       var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
195
196       if (tokens[idx].nesting === 1) {
197         // opening tag
198         return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
199       } else {
200         // closing tag
201         return "</details>\n";
202       }
203     },
204   });
205
206 export function hotRankComment(comment_view: CommentView): number {
207   return hotRank(comment_view.counts.score, comment_view.comment.published);
208 }
209
210 export function hotRankActivePost(post_view: PostView): number {
211   return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
212 }
213
214 export function hotRankPost(post_view: PostView): number {
215   return hotRank(post_view.counts.score, post_view.post.published);
216 }
217
218 export function hotRank(score: number, timeStr: string): number {
219   // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
220   let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
221   let now: Date = new Date();
222   let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
223
224   let rank =
225     (10000 * Math.log10(Math.max(1, 3 + score))) /
226     Math.pow(hoursElapsed + 2, 1.8);
227
228   // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
229
230   return rank;
231 }
232
233 export function mdToHtml(text: string) {
234   return { __html: md.render(text) };
235 }
236
237 export function getUnixTime(text: string): number {
238   return text ? new Date(text).getTime() / 1000 : undefined;
239 }
240
241 export function canMod(
242   localUserView: LocalUserSettingsView,
243   modIds: number[],
244   creator_id: number,
245   onSelf = false
246 ): boolean {
247   // You can do moderator actions only on the mods added after you.
248   if (localUserView) {
249     let yourIndex = modIds.findIndex(id => id == localUserView.person.id);
250     if (yourIndex == -1) {
251       return false;
252     } else {
253       // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
254       modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
255       return !modIds.includes(creator_id);
256     }
257   } else {
258     return false;
259   }
260 }
261
262 export function isMod(modIds: number[], creator_id: number): boolean {
263   return modIds.includes(creator_id);
264 }
265
266 const imageRegex = new RegExp(
267   /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
268 );
269 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
270
271 export function isImage(url: string) {
272   return imageRegex.test(url);
273 }
274
275 export function isVideo(url: string) {
276   return videoRegex.test(url);
277 }
278
279 export function validURL(str: string) {
280   return !!new URL(str);
281 }
282
283 export function communityRSSUrl(actorId: string, sort: string): string {
284   let url = new URL(actorId);
285   return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
286 }
287
288 export function validEmail(email: string) {
289   let re = /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
290   return re.test(String(email).toLowerCase());
291 }
292
293 export function capitalizeFirstLetter(str: string): string {
294   return str.charAt(0).toUpperCase() + str.slice(1);
295 }
296
297 export function routeSortTypeToEnum(sort: string): SortType {
298   return SortType[sort];
299 }
300
301 export function listingTypeFromNum(type_: number): ListingType {
302   return Object.values(ListingType)[type_];
303 }
304
305 export function sortTypeFromNum(type_: number): SortType {
306   return Object.values(SortType)[type_];
307 }
308
309 export function routeListingTypeToEnum(type: string): ListingType {
310   return ListingType[type];
311 }
312
313 export function routeDataTypeToEnum(type: string): DataType {
314   return DataType[capitalizeFirstLetter(type)];
315 }
316
317 export function routeSearchTypeToEnum(type: string): SearchType {
318   return SearchType[type];
319 }
320
321 export async function getPageTitle(url: string) {
322   let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
323   let title = await res.title;
324   return title;
325 }
326
327 export function debounce(func: any, wait = 1000, immediate = false) {
328   // 'private' variable for instance
329   // The returned function will be able to reference this due to closure.
330   // Each call to the returned function will share this common timer.
331   let timeout: any;
332
333   // Calling debounce returns a new anonymous function
334   return function () {
335     // reference the context and args for the setTimeout function
336     var args = arguments;
337
338     // Should the function be called now? If immediate is true
339     //   and not already in a timeout then the answer is: Yes
340     var callNow = immediate && !timeout;
341
342     // This is the basic debounce behaviour where you can call this
343     //   function several times, but it will only execute once
344     //   [before or after imposing a delay].
345     //   Each time the returned function is called, the timer starts over.
346     clearTimeout(timeout);
347
348     // Set the new timeout
349     timeout = setTimeout(function () {
350       // Inside the timeout function, clear the timeout variable
351       // which will let the next execution run when in 'immediate' mode
352       timeout = null;
353
354       // Check if the function already ran with the immediate flag
355       if (!immediate) {
356         // Call the original function with apply
357         // apply lets you define the 'this' object as well as the arguments
358         //    (both captured before setTimeout)
359         func.apply(this, args);
360       }
361     }, wait);
362
363     // Immediate mode and no wait timer? Execute the function..
364     if (callNow) func.apply(this, args);
365   };
366 }
367
368 // TODO
369 export function getLanguage(override?: string): string {
370   let localUserView = UserService.Instance.localUserView;
371   let lang =
372     override ||
373     (localUserView?.local_user.lang
374       ? localUserView.local_user.lang
375       : "browser");
376
377   if (lang == "browser" && isBrowser()) {
378     return getBrowserLanguage();
379   } else {
380     return lang;
381   }
382 }
383
384 export function getBrowserLanguage(): string {
385   return navigator.language;
386 }
387
388 export function getMomentLanguage(): string {
389   let lang = getLanguage();
390   if (lang.startsWith("zh")) {
391     lang = "zh-cn";
392   } else if (lang.startsWith("sv")) {
393     lang = "sv";
394   } else if (lang.startsWith("fr")) {
395     lang = "fr";
396   } else if (lang.startsWith("de")) {
397     lang = "de";
398   } else if (lang.startsWith("ru")) {
399     lang = "ru";
400   } else if (lang.startsWith("es")) {
401     lang = "es";
402   } else if (lang.startsWith("eo")) {
403     lang = "eo";
404   } else if (lang.startsWith("nl")) {
405     lang = "nl";
406   } else if (lang.startsWith("it")) {
407     lang = "it";
408   } else if (lang.startsWith("fi")) {
409     lang = "fi";
410   } else if (lang.startsWith("ca")) {
411     lang = "ca";
412   } else if (lang.startsWith("fa")) {
413     lang = "fa";
414   } else if (lang.startsWith("pl")) {
415     lang = "pl";
416   } else if (lang.startsWith("pt")) {
417     lang = "pt-br";
418   } else if (lang.startsWith("ja")) {
419     lang = "ja";
420   } else if (lang.startsWith("ka")) {
421     lang = "ka";
422   } else if (lang.startsWith("hi")) {
423     lang = "hi";
424   } else if (lang.startsWith("el")) {
425     lang = "el";
426   } else if (lang.startsWith("eu")) {
427     lang = "eu";
428   } else if (lang.startsWith("gl")) {
429     lang = "gl";
430   } else if (lang.startsWith("tr")) {
431     lang = "tr";
432   } else if (lang.startsWith("hu")) {
433     lang = "hu";
434   } else if (lang.startsWith("uk")) {
435     lang = "uk";
436   } else if (lang.startsWith("sq")) {
437     lang = "sq";
438   } else if (lang.startsWith("km")) {
439     lang = "km";
440   } else if (lang.startsWith("ga")) {
441     lang = "ga";
442   } else if (lang.startsWith("sr")) {
443     lang = "sr";
444   } else if (lang.startsWith("ko")) {
445     lang = "ko";
446   } else if (lang.startsWith("da")) {
447     lang = "da";
448   } else if (lang.startsWith("oc")) {
449     lang = "oc";
450   } else if (lang.startsWith("hr")) {
451     lang = "hr";
452   } else if (lang.startsWith("th")) {
453     lang = "th";
454   } else {
455     lang = "en";
456   }
457   return lang;
458 }
459
460 export function setTheme(theme: string, forceReload = false) {
461   if (!isBrowser()) {
462     return;
463   }
464   if (theme === "browser" && !forceReload) {
465     return;
466   }
467   // This is only run on a force reload
468   if (theme == "browser") {
469     theme = "darkly";
470   }
471
472   // Unload all the other themes
473   for (var i = 0; i < themes.length; i++) {
474     let styleSheet = document.getElementById(themes[i]);
475     if (styleSheet) {
476       styleSheet.setAttribute("disabled", "disabled");
477     }
478   }
479
480   document
481     .getElementById("default-light")
482     ?.setAttribute("disabled", "disabled");
483   document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
484
485   // Load the theme dynamically
486   let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
487   loadCss(theme, cssLoc);
488   document.getElementById(theme).removeAttribute("disabled");
489 }
490
491 export function loadCss(id: string, loc: string) {
492   if (!document.getElementById(id)) {
493     var head = document.getElementsByTagName("head")[0];
494     var link = document.createElement("link");
495     link.id = id;
496     link.rel = "stylesheet";
497     link.type = "text/css";
498     link.href = loc;
499     link.media = "all";
500     head.appendChild(link);
501   }
502 }
503
504 export function objectFlip(obj: any) {
505   const ret = {};
506   Object.keys(obj).forEach(key => {
507     ret[obj[key]] = key;
508   });
509   return ret;
510 }
511
512 export function showAvatars(): boolean {
513   return (
514     UserService.Instance.localUserView?.local_user.show_avatars ||
515     !UserService.Instance.localUserView
516   );
517 }
518
519 export function isCakeDay(published: string): boolean {
520   // moment(undefined) or moment.utc(undefined) returns the current date/time
521   // moment(null) or moment.utc(null) returns null
522   const createDate = moment.utc(published || null).local();
523   const currentDate = moment(new Date());
524
525   return (
526     createDate.date() === currentDate.date() &&
527     createDate.month() === currentDate.month() &&
528     createDate.year() !== currentDate.year()
529   );
530 }
531
532 export function toast(text: string, background = "success") {
533   if (isBrowser()) {
534     let backgroundColor = `var(--${background})`;
535     Toastify({
536       text: text,
537       backgroundColor: backgroundColor,
538       gravity: "bottom",
539       position: "left",
540     }).showToast();
541   }
542 }
543
544 export function pictrsDeleteToast(
545   clickToDeleteText: string,
546   deletePictureText: string,
547   deleteUrl: string
548 ) {
549   if (isBrowser()) {
550     let backgroundColor = `var(--light)`;
551     let toast = Toastify({
552       text: clickToDeleteText,
553       backgroundColor: backgroundColor,
554       gravity: "top",
555       position: "right",
556       duration: 10000,
557       onClick: () => {
558         if (toast) {
559           window.location.replace(deleteUrl);
560           alert(deletePictureText);
561           toast.hideToast();
562         }
563       },
564       close: true,
565     }).showToast();
566   }
567 }
568
569 interface NotifyInfo {
570   name: string;
571   icon?: string;
572   link: string;
573   body: string;
574 }
575
576 export function messageToastify(info: NotifyInfo, router: any) {
577   if (isBrowser()) {
578     let htmlBody = info.body ? md.render(info.body) : "";
579     let backgroundColor = `var(--light)`;
580
581     let toast = Toastify({
582       text: `${htmlBody}<br />${info.name}`,
583       avatar: info.icon ? info.icon : null,
584       backgroundColor: backgroundColor,
585       className: "text-dark",
586       close: true,
587       gravity: "top",
588       position: "right",
589       duration: 5000,
590       onClick: () => {
591         if (toast) {
592           toast.hideToast();
593           router.history.push(info.link);
594         }
595       },
596     }).showToast();
597   }
598 }
599
600 export function notifyPost(post_view: PostView, router: any) {
601   let info: NotifyInfo = {
602     name: post_view.community.name,
603     icon: post_view.community.icon,
604     link: `/post/${post_view.post.id}`,
605     body: post_view.post.name,
606   };
607   notify(info, router);
608 }
609
610 export function notifyComment(comment_view: CommentView, router: any) {
611   let info: NotifyInfo = {
612     name: comment_view.creator.name,
613     icon: comment_view.creator.avatar,
614     link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
615     body: comment_view.comment.content,
616   };
617   notify(info, router);
618 }
619
620 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
621   let info: NotifyInfo = {
622     name: pmv.creator.name,
623     icon: pmv.creator.avatar,
624     link: `/inbox`,
625     body: pmv.private_message.content,
626   };
627   notify(info, router);
628 }
629
630 function notify(info: NotifyInfo, router: any) {
631   messageToastify(info, router);
632
633   if (Notification.permission !== "granted") Notification.requestPermission();
634   else {
635     var notification = new Notification(info.name, {
636       icon: info.icon,
637       body: info.body,
638     });
639
640     notification.onclick = (ev: Event): any => {
641       ev.preventDefault();
642       router.history.push(info.link);
643     };
644   }
645 }
646
647 export function setupTribute() {
648   return new Tribute({
649     noMatchTemplate: function () {
650       return "";
651     },
652     collection: [
653       // Emojis
654       {
655         trigger: ":",
656         menuItemTemplate: (item: any) => {
657           let shortName = `:${item.original.key}:`;
658           return `${item.original.val} ${shortName}`;
659         },
660         selectTemplate: (item: any) => {
661           return `${item.original.val}`;
662         },
663         values: Object.entries(emojiShortName).map(e => {
664           return { key: e[1], val: e[0] };
665         }),
666         allowSpaces: false,
667         autocompleteMode: true,
668         // TODO
669         // menuItemLimit: mentionDropdownFetchLimit,
670         menuShowMinLength: 2,
671       },
672       // Persons
673       {
674         trigger: "@",
675         selectTemplate: (item: any) => {
676           let it: PersonTribute = item.original;
677           return `[${it.key}](${it.view.person.actor_id})`;
678         },
679         values: (text: string, cb: (persons: PersonTribute[]) => any) => {
680           personSearch(text, (persons: PersonTribute[]) => cb(persons));
681         },
682         allowSpaces: false,
683         autocompleteMode: true,
684         // TODO
685         // menuItemLimit: mentionDropdownFetchLimit,
686         menuShowMinLength: 2,
687       },
688
689       // Communities
690       {
691         trigger: "!",
692         selectTemplate: (item: any) => {
693           let it: CommunityTribute = item.original;
694           return `[${it.key}](${it.view.community.actor_id})`;
695         },
696         values: (text: string, cb: any) => {
697           communitySearch(text, (communities: CommunityTribute[]) =>
698             cb(communities)
699           );
700         },
701         allowSpaces: false,
702         autocompleteMode: true,
703         // TODO
704         // menuItemLimit: mentionDropdownFetchLimit,
705         menuShowMinLength: 2,
706       },
707     ],
708   });
709 }
710
711 var tippyInstance: any;
712 if (isBrowser()) {
713   tippyInstance = tippy("[data-tippy-content]");
714 }
715
716 export function setupTippy() {
717   if (isBrowser()) {
718     tippyInstance.forEach((e: any) => e.destroy());
719     tippyInstance = tippy("[data-tippy-content]", {
720       delay: [500, 0],
721       // Display on "long press"
722       touch: ["hold", 500],
723     });
724   }
725 }
726
727 interface PersonTribute {
728   key: string;
729   view: PersonViewSafe;
730 }
731
732 function personSearch(text: string, cb: (persons: PersonTribute[]) => any) {
733   if (text) {
734     let form: Search = {
735       q: text,
736       type_: SearchType.Users,
737       sort: SortType.TopAll,
738       page: 1,
739       limit: mentionDropdownFetchLimit,
740       auth: authField(false),
741     };
742
743     WebSocketService.Instance.send(wsClient.search(form));
744
745     let personSub = WebSocketService.Instance.subject.subscribe(
746       msg => {
747         let res = wsJsonToRes(msg);
748         if (res.op == UserOperation.Search) {
749           let data = res.data as SearchResponse;
750           let persons: PersonTribute[] = data.users.map(pv => {
751             let tribute: PersonTribute = {
752               key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
753               view: pv,
754             };
755             return tribute;
756           });
757           cb(persons);
758           personSub.unsubscribe();
759         }
760       },
761       err => console.error(err),
762       () => console.log("complete")
763     );
764   } else {
765     cb([]);
766   }
767 }
768
769 interface CommunityTribute {
770   key: string;
771   view: CommunityView;
772 }
773
774 function communitySearch(
775   text: string,
776   cb: (communities: CommunityTribute[]) => any
777 ) {
778   if (text) {
779     let form: Search = {
780       q: text,
781       type_: SearchType.Communities,
782       sort: SortType.TopAll,
783       page: 1,
784       limit: mentionDropdownFetchLimit,
785       auth: authField(false),
786     };
787
788     WebSocketService.Instance.send(wsClient.search(form));
789
790     let communitySub = WebSocketService.Instance.subject.subscribe(
791       msg => {
792         let res = wsJsonToRes(msg);
793         if (res.op == UserOperation.Search) {
794           let data = res.data as SearchResponse;
795           let communities: CommunityTribute[] = data.communities.map(cv => {
796             let tribute: CommunityTribute = {
797               key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
798               view: cv,
799             };
800             return tribute;
801           });
802           cb(communities);
803           communitySub.unsubscribe();
804         }
805       },
806       err => console.error(err),
807       () => console.log("complete")
808     );
809   } else {
810     cb([]);
811   }
812 }
813
814 export function getListingTypeFromProps(props: any): ListingType {
815   return props.match.params.listing_type
816     ? routeListingTypeToEnum(props.match.params.listing_type)
817     : UserService.Instance.localUserView
818     ? Object.values(ListingType)[
819         UserService.Instance.localUserView.local_user.default_listing_type
820       ]
821     : ListingType.Local;
822 }
823
824 // TODO might need to add a user setting for this too
825 export function getDataTypeFromProps(props: any): DataType {
826   return props.match.params.data_type
827     ? routeDataTypeToEnum(props.match.params.data_type)
828     : DataType.Post;
829 }
830
831 export function getSortTypeFromProps(props: any): SortType {
832   return props.match.params.sort
833     ? routeSortTypeToEnum(props.match.params.sort)
834     : UserService.Instance.localUserView
835     ? Object.values(SortType)[
836         UserService.Instance.localUserView.local_user.default_sort_type
837       ]
838     : SortType.Active;
839 }
840
841 export function getPageFromProps(props: any): number {
842   return props.match.params.page ? Number(props.match.params.page) : 1;
843 }
844
845 export function getRecipientIdFromProps(props: any): number {
846   return props.match.params.recipient_id
847     ? Number(props.match.params.recipient_id)
848     : 1;
849 }
850
851 export function getIdFromProps(props: any): number {
852   return Number(props.match.params.id);
853 }
854
855 export function getCommentIdFromProps(props: any): number {
856   return Number(props.match.params.comment_id);
857 }
858
859 export function getUsernameFromProps(props: any): string {
860   return props.match.params.username;
861 }
862
863 export function editCommentRes(data: CommentView, comments: CommentView[]) {
864   let found = comments.find(c => c.comment.id == data.comment.id);
865   if (found) {
866     found.comment.content = data.comment.content;
867     found.comment.updated = data.comment.updated;
868     found.comment.removed = data.comment.removed;
869     found.comment.deleted = data.comment.deleted;
870     found.counts.upvotes = data.counts.upvotes;
871     found.counts.downvotes = data.counts.downvotes;
872     found.counts.score = data.counts.score;
873   }
874 }
875
876 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
877   let found = comments.find(c => c.comment.id == data.comment.id);
878   if (found) {
879     found.saved = data.saved;
880   }
881 }
882
883 export function createCommentLikeRes(
884   data: CommentView,
885   comments: CommentView[]
886 ) {
887   let found = comments.find(c => c.comment.id === data.comment.id);
888   if (found) {
889     found.counts.score = data.counts.score;
890     found.counts.upvotes = data.counts.upvotes;
891     found.counts.downvotes = data.counts.downvotes;
892     if (data.my_vote !== null) {
893       found.my_vote = data.my_vote;
894     }
895   }
896 }
897
898 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
899   let found = posts.find(p => p.post.id == data.post.id);
900   if (found) {
901     createPostLikeRes(data, found);
902   }
903 }
904
905 export function createPostLikeRes(data: PostView, post_view: PostView) {
906   if (post_view) {
907     post_view.counts.score = data.counts.score;
908     post_view.counts.upvotes = data.counts.upvotes;
909     post_view.counts.downvotes = data.counts.downvotes;
910     if (data.my_vote !== null) {
911       post_view.my_vote = data.my_vote;
912     }
913   }
914 }
915
916 export function editPostFindRes(data: PostView, posts: PostView[]) {
917   let found = posts.find(p => p.post.id == data.post.id);
918   if (found) {
919     editPostRes(data, found);
920   }
921 }
922
923 export function editPostRes(data: PostView, post: PostView) {
924   if (post) {
925     post.post.url = data.post.url;
926     post.post.name = data.post.name;
927     post.post.nsfw = data.post.nsfw;
928     post.post.deleted = data.post.deleted;
929     post.post.removed = data.post.removed;
930     post.post.stickied = data.post.stickied;
931     post.post.body = data.post.body;
932     post.post.locked = data.post.locked;
933     post.saved = data.saved;
934   }
935 }
936
937 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
938   let nodes: CommentNodeI[] = [];
939   for (let comment of comments) {
940     nodes.push({ comment_view: comment });
941   }
942   return nodes;
943 }
944
945 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
946   // First, put removed and deleted comments at the bottom, then do your other sorts
947   if (sort == CommentSortType.Top) {
948     tree.sort(
949       (a, b) =>
950         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
951         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
952         b.comment_view.counts.score - a.comment_view.counts.score
953     );
954   } else if (sort == CommentSortType.New) {
955     tree.sort(
956       (a, b) =>
957         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
958         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
959         b.comment_view.comment.published.localeCompare(
960           a.comment_view.comment.published
961         )
962     );
963   } else if (sort == CommentSortType.Old) {
964     tree.sort(
965       (a, b) =>
966         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
967         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
968         a.comment_view.comment.published.localeCompare(
969           b.comment_view.comment.published
970         )
971     );
972   } else if (sort == CommentSortType.Hot) {
973     tree.sort(
974       (a, b) =>
975         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
976         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
977         hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
978     );
979   }
980
981   // Go through the children recursively
982   for (let node of tree) {
983     if (node.children) {
984       commentSort(node.children, sort);
985     }
986   }
987 }
988
989 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
990   commentSort(tree, convertCommentSortType(sort));
991 }
992
993 function convertCommentSortType(sort: SortType): CommentSortType {
994   if (
995     sort == SortType.TopAll ||
996     sort == SortType.TopDay ||
997     sort == SortType.TopWeek ||
998     sort == SortType.TopMonth ||
999     sort == SortType.TopYear
1000   ) {
1001     return CommentSortType.Top;
1002   } else if (sort == SortType.New) {
1003     return CommentSortType.New;
1004   } else if (sort == SortType.Hot || sort == SortType.Active) {
1005     return CommentSortType.Hot;
1006   } else {
1007     return CommentSortType.Hot;
1008   }
1009 }
1010
1011 export function buildCommentsTree(
1012   comments: CommentView[],
1013   commentSortType: CommentSortType
1014 ): CommentNodeI[] {
1015   let map = new Map<number, CommentNodeI>();
1016   for (let comment_view of comments) {
1017     let node: CommentNodeI = {
1018       comment_view: comment_view,
1019       children: [],
1020     };
1021     map.set(comment_view.comment.id, { ...node });
1022   }
1023   let tree: CommentNodeI[] = [];
1024   for (let comment_view of comments) {
1025     let child = map.get(comment_view.comment.id);
1026     if (comment_view.comment.parent_id) {
1027       let parent_ = map.get(comment_view.comment.parent_id);
1028       parent_.children.push(child);
1029     } else {
1030       tree.push(child);
1031     }
1032
1033     setDepth(child);
1034   }
1035
1036   commentSort(tree, commentSortType);
1037
1038   return tree;
1039 }
1040
1041 function setDepth(node: CommentNodeI, i = 0) {
1042   for (let child of node.children) {
1043     child.depth = i;
1044     setDepth(child, i + 1);
1045   }
1046 }
1047
1048 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1049   // Building a fake node to be used for later
1050   let node: CommentNodeI = {
1051     comment_view: cv,
1052     children: [],
1053     depth: 0,
1054   };
1055
1056   if (cv.comment.parent_id) {
1057     let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1058     if (parentComment) {
1059       node.depth = parentComment.depth + 1;
1060       parentComment.children.unshift(node);
1061     }
1062   } else {
1063     tree.unshift(node);
1064   }
1065 }
1066
1067 export function searchCommentTree(
1068   tree: CommentNodeI[],
1069   id: number
1070 ): CommentNodeI {
1071   for (let node of tree) {
1072     if (node.comment_view.comment.id === id) {
1073       return node;
1074     }
1075
1076     for (const child of node.children) {
1077       const res = searchCommentTree([child], id);
1078
1079       if (res) {
1080         return res;
1081       }
1082     }
1083   }
1084   return null;
1085 }
1086
1087 export const colorList: string[] = [
1088   hsl(0),
1089   hsl(100),
1090   hsl(150),
1091   hsl(200),
1092   hsl(250),
1093   hsl(300),
1094 ];
1095
1096 function hsl(num: number) {
1097   return `hsla(${num}, 35%, 50%, 1)`;
1098 }
1099
1100 export function previewLines(
1101   text: string,
1102   maxChars = 300,
1103   maxLines = 1
1104 ): string {
1105   return (
1106     text
1107       .slice(0, maxChars)
1108       .split("\n")
1109       // Use lines * 2 because markdown requires 2 lines
1110       .slice(0, maxLines * 2)
1111       .join("\n") + "..."
1112   );
1113 }
1114
1115 export function hostname(url: string): string {
1116   let cUrl = new URL(url);
1117   return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1118 }
1119
1120 export function validTitle(title?: string): boolean {
1121   // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1122   if (title === null || title.length < 3) return true;
1123
1124   const regex = new RegExp(/.*\S.*/, "g");
1125
1126   return regex.test(title);
1127 }
1128
1129 export function siteBannerCss(banner: string): string {
1130   return ` \
1131     background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1132     background-attachment: fixed; \
1133     background-position: top; \
1134     background-repeat: no-repeat; \
1135     background-size: 100% cover; \
1136
1137     width: 100%; \
1138     max-height: 100vh; \
1139     `;
1140 }
1141
1142 export function isBrowser() {
1143   return typeof window !== "undefined";
1144 }
1145
1146 export function setIsoData(context: any): IsoData {
1147   let isoData: IsoData = isBrowser()
1148     ? window.isoData
1149     : context.router.staticContext;
1150   return isoData;
1151 }
1152
1153 export function wsSubscribe(parseMessage: any): Subscription {
1154   if (isBrowser()) {
1155     return WebSocketService.Instance.subject
1156       .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1157       .subscribe(
1158         msg => parseMessage(msg),
1159         err => console.error(err),
1160         () => console.log("complete")
1161       );
1162   } else {
1163     return null;
1164   }
1165 }
1166
1167 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1168   if (auth) {
1169     obj.auth = auth;
1170   }
1171 }
1172
1173 export function authField(
1174   throwErr = true,
1175   auth = UserService.Instance.auth
1176 ): string {
1177   if (auth == null && throwErr) {
1178     toast(i18n.t("not_logged_in"), "danger");
1179     throw "Not logged in";
1180   } else {
1181     return auth;
1182   }
1183 }
1184
1185 moment.updateLocale("en", {
1186   relativeTime: {
1187     future: "in %s",
1188     past: "%s ago",
1189     s: "<1m",
1190     ss: "%ds",
1191     m: "1m",
1192     mm: "%dm",
1193     h: "1h",
1194     hh: "%dh",
1195     d: "1d",
1196     dd: "%dd",
1197     w: "1w",
1198     ww: "%dw",
1199     M: "1M",
1200     MM: "%dM",
1201     y: "1Y",
1202     yy: "%dY",
1203   },
1204 });
1205
1206 export function saveScrollPosition(context: any) {
1207   let path: string = context.router.route.location.pathname;
1208   let y = window.scrollY;
1209   sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1210 }
1211
1212 export function restoreScrollPosition(context: any) {
1213   let path: string = context.router.route.location.pathname;
1214   let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1215   window.scrollTo(0, y);
1216 }