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