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