]> Untitled Git - lemmy-ui.git/blob - src/shared/utils.ts
user_ -> person table migration.
[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/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: "th", name: "ภาษาไทย" },
122   { code: "tr", name: "Türkçe" },
123   { code: "uk", name: "Українська Mова" },
124   { code: "ru", name: "Русский" },
125   { code: "nl", name: "Nederlands" },
126   { code: "it", name: "Italiano" },
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 // TODO
385 export function getBrowserLanguage(): string {
386   return navigator.language;
387 }
388
389 export function getMomentLanguage(): string {
390   let lang = getLanguage();
391   if (lang.startsWith("zh")) {
392     lang = "zh-cn";
393   } else if (lang.startsWith("sv")) {
394     lang = "sv";
395   } else if (lang.startsWith("fr")) {
396     lang = "fr";
397   } else if (lang.startsWith("de")) {
398     lang = "de";
399   } else if (lang.startsWith("ru")) {
400     lang = "ru";
401   } else if (lang.startsWith("es")) {
402     lang = "es";
403   } else if (lang.startsWith("eo")) {
404     lang = "eo";
405   } else if (lang.startsWith("nl")) {
406     lang = "nl";
407   } else if (lang.startsWith("it")) {
408     lang = "it";
409   } else if (lang.startsWith("fi")) {
410     lang = "fi";
411   } else if (lang.startsWith("ca")) {
412     lang = "ca";
413   } else if (lang.startsWith("fa")) {
414     lang = "fa";
415   } else if (lang.startsWith("pl")) {
416     lang = "pl";
417   } else if (lang.startsWith("pt")) {
418     lang = "pt-br";
419   } else if (lang.startsWith("ja")) {
420     lang = "ja";
421   } else if (lang.startsWith("ka")) {
422     lang = "ka";
423   } else if (lang.startsWith("hi")) {
424     lang = "hi";
425   } else if (lang.startsWith("el")) {
426     lang = "el";
427   } else if (lang.startsWith("eu")) {
428     lang = "eu";
429   } else if (lang.startsWith("gl")) {
430     lang = "gl";
431   } else if (lang.startsWith("tr")) {
432     lang = "tr";
433   } else if (lang.startsWith("hu")) {
434     lang = "hu";
435   } else if (lang.startsWith("uk")) {
436     lang = "uk";
437   } else if (lang.startsWith("sq")) {
438     lang = "sq";
439   } else if (lang.startsWith("km")) {
440     lang = "km";
441   } else if (lang.startsWith("ga")) {
442     lang = "ga";
443   } else if (lang.startsWith("sr")) {
444     lang = "sr";
445   } else if (lang.startsWith("ko")) {
446     lang = "ko";
447   } else if (lang.startsWith("da")) {
448     lang = "da";
449   } else if (lang.startsWith("oc")) {
450     lang = "oc";
451   } else if (lang.startsWith("hr")) {
452     lang = "hr";
453   } else if (lang.startsWith("th")) {
454     lang = "th";
455   } else {
456     lang = "en";
457   }
458   return lang;
459 }
460
461 export function setTheme(theme: string, forceReload = false) {
462   if (!isBrowser()) {
463     return;
464   }
465   if (theme === "browser" && !forceReload) {
466     return;
467   }
468   // This is only run on a force reload
469   if (theme == "browser") {
470     theme = "darkly";
471   }
472
473   // Unload all the other themes
474   for (var i = 0; i < themes.length; i++) {
475     let styleSheet = document.getElementById(themes[i]);
476     if (styleSheet) {
477       styleSheet.setAttribute("disabled", "disabled");
478     }
479   }
480
481   document
482     .getElementById("default-light")
483     ?.setAttribute("disabled", "disabled");
484   document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
485
486   // Load the theme dynamically
487   let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
488   loadCss(theme, cssLoc);
489   document.getElementById(theme).removeAttribute("disabled");
490 }
491
492 export function loadCss(id: string, loc: string) {
493   if (!document.getElementById(id)) {
494     var head = document.getElementsByTagName("head")[0];
495     var link = document.createElement("link");
496     link.id = id;
497     link.rel = "stylesheet";
498     link.type = "text/css";
499     link.href = loc;
500     link.media = "all";
501     head.appendChild(link);
502   }
503 }
504
505 export function objectFlip(obj: any) {
506   const ret = {};
507   Object.keys(obj).forEach(key => {
508     ret[obj[key]] = key;
509   });
510   return ret;
511 }
512
513 export function showAvatars(): boolean {
514   return (
515     UserService.Instance.localUserView?.local_user.show_avatars ||
516     !UserService.Instance.localUserView
517   );
518 }
519
520 export function isCakeDay(published: string): boolean {
521   // moment(undefined) or moment.utc(undefined) returns the current date/time
522   // moment(null) or moment.utc(null) returns null
523   const createDate = moment.utc(published || null).local();
524   const currentDate = moment(new Date());
525
526   return (
527     createDate.date() === currentDate.date() &&
528     createDate.month() === currentDate.month() &&
529     createDate.year() !== currentDate.year()
530   );
531 }
532
533 export function toast(text: string, background = "success") {
534   if (isBrowser()) {
535     let backgroundColor = `var(--${background})`;
536     Toastify({
537       text: text,
538       backgroundColor: backgroundColor,
539       gravity: "bottom",
540       position: "left",
541     }).showToast();
542   }
543 }
544
545 export function pictrsDeleteToast(
546   clickToDeleteText: string,
547   deletePictureText: string,
548   deleteUrl: string
549 ) {
550   if (isBrowser()) {
551     let backgroundColor = `var(--light)`;
552     let toast = Toastify({
553       text: clickToDeleteText,
554       backgroundColor: backgroundColor,
555       gravity: "top",
556       position: "right",
557       duration: 10000,
558       onClick: () => {
559         if (toast) {
560           window.location.replace(deleteUrl);
561           alert(deletePictureText);
562           toast.hideToast();
563         }
564       },
565       close: true,
566     }).showToast();
567   }
568 }
569
570 interface NotifyInfo {
571   name: string;
572   icon?: string;
573   link: string;
574   body: string;
575 }
576
577 export function messageToastify(info: NotifyInfo, router: any) {
578   if (isBrowser()) {
579     let htmlBody = info.body ? md.render(info.body) : "";
580     let backgroundColor = `var(--light)`;
581
582     let toast = Toastify({
583       text: `${htmlBody}<br />${info.name}`,
584       avatar: info.icon ? info.icon : null,
585       backgroundColor: backgroundColor,
586       className: "text-dark",
587       close: true,
588       gravity: "top",
589       position: "right",
590       duration: 5000,
591       onClick: () => {
592         if (toast) {
593           toast.hideToast();
594           router.history.push(info.link);
595         }
596       },
597     }).showToast();
598   }
599 }
600
601 export function notifyPost(post_view: PostView, router: any) {
602   let info: NotifyInfo = {
603     name: post_view.community.name,
604     icon: post_view.community.icon,
605     link: `/post/${post_view.post.id}`,
606     body: post_view.post.name,
607   };
608   notify(info, router);
609 }
610
611 export function notifyComment(comment_view: CommentView, router: any) {
612   let info: NotifyInfo = {
613     name: comment_view.creator.name,
614     icon: comment_view.creator.avatar,
615     link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
616     body: comment_view.comment.content,
617   };
618   notify(info, router);
619 }
620
621 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
622   let info: NotifyInfo = {
623     name: pmv.creator.name,
624     icon: pmv.creator.avatar,
625     link: `/inbox`,
626     body: pmv.private_message.content,
627   };
628   notify(info, router);
629 }
630
631 function notify(info: NotifyInfo, router: any) {
632   messageToastify(info, router);
633
634   if (Notification.permission !== "granted") Notification.requestPermission();
635   else {
636     var notification = new Notification(info.name, {
637       icon: info.icon,
638       body: info.body,
639     });
640
641     notification.onclick = (ev: Event): any => {
642       ev.preventDefault();
643       router.history.push(info.link);
644     };
645   }
646 }
647
648 export function setupTribute() {
649   return new Tribute({
650     noMatchTemplate: function () {
651       return "";
652     },
653     collection: [
654       // Emojis
655       {
656         trigger: ":",
657         menuItemTemplate: (item: any) => {
658           let shortName = `:${item.original.key}:`;
659           return `${item.original.val} ${shortName}`;
660         },
661         selectTemplate: (item: any) => {
662           return `${item.original.val}`;
663         },
664         values: Object.entries(emojiShortName).map(e => {
665           return { key: e[1], val: e[0] };
666         }),
667         allowSpaces: false,
668         autocompleteMode: true,
669         // TODO
670         // menuItemLimit: mentionDropdownFetchLimit,
671         menuShowMinLength: 2,
672       },
673       // Persons
674       {
675         trigger: "@",
676         selectTemplate: (item: any) => {
677           let it: PersonTribute = item.original;
678           return `[${it.key}](${it.view.person.actor_id})`;
679         },
680         values: (text: string, cb: (persons: PersonTribute[]) => any) => {
681           personSearch(text, (persons: PersonTribute[]) => cb(persons));
682         },
683         allowSpaces: false,
684         autocompleteMode: true,
685         // TODO
686         // menuItemLimit: mentionDropdownFetchLimit,
687         menuShowMinLength: 2,
688       },
689
690       // Communities
691       {
692         trigger: "!",
693         selectTemplate: (item: any) => {
694           let it: CommunityTribute = item.original;
695           return `[${it.key}](${it.view.community.actor_id})`;
696         },
697         values: (text: string, cb: any) => {
698           communitySearch(text, (communities: CommunityTribute[]) =>
699             cb(communities)
700           );
701         },
702         allowSpaces: false,
703         autocompleteMode: true,
704         // TODO
705         // menuItemLimit: mentionDropdownFetchLimit,
706         menuShowMinLength: 2,
707       },
708     ],
709   });
710 }
711
712 var tippyInstance: any;
713 if (isBrowser()) {
714   tippyInstance = tippy("[data-tippy-content]");
715 }
716
717 export function setupTippy() {
718   if (isBrowser()) {
719     tippyInstance.forEach((e: any) => e.destroy());
720     tippyInstance = tippy("[data-tippy-content]", {
721       delay: [500, 0],
722       // Display on "long press"
723       touch: ["hold", 500],
724     });
725   }
726 }
727
728 interface PersonTribute {
729   key: string;
730   view: PersonViewSafe;
731 }
732
733 function personSearch(text: string, cb: (persons: PersonTribute[]) => any) {
734   if (text) {
735     let form: Search = {
736       q: text,
737       type_: SearchType.Users,
738       sort: SortType.TopAll,
739       page: 1,
740       limit: mentionDropdownFetchLimit,
741       auth: authField(false),
742     };
743
744     WebSocketService.Instance.send(wsClient.search(form));
745
746     let personSub = WebSocketService.Instance.subject.subscribe(
747       msg => {
748         let res = wsJsonToRes(msg);
749         if (res.op == UserOperation.Search) {
750           let data = res.data as SearchResponse;
751           let persons: PersonTribute[] = data.users.map(pv => {
752             let tribute: PersonTribute = {
753               key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
754               view: pv,
755             };
756             return tribute;
757           });
758           cb(persons);
759           personSub.unsubscribe();
760         }
761       },
762       err => console.error(err),
763       () => console.log("complete")
764     );
765   } else {
766     cb([]);
767   }
768 }
769
770 interface CommunityTribute {
771   key: string;
772   view: CommunityView;
773 }
774
775 function communitySearch(
776   text: string,
777   cb: (communities: CommunityTribute[]) => any
778 ) {
779   if (text) {
780     let form: Search = {
781       q: text,
782       type_: SearchType.Communities,
783       sort: SortType.TopAll,
784       page: 1,
785       limit: mentionDropdownFetchLimit,
786       auth: authField(false),
787     };
788
789     WebSocketService.Instance.send(wsClient.search(form));
790
791     let communitySub = WebSocketService.Instance.subject.subscribe(
792       msg => {
793         let res = wsJsonToRes(msg);
794         if (res.op == UserOperation.Search) {
795           let data = res.data as SearchResponse;
796           let communities: CommunityTribute[] = data.communities.map(cv => {
797             let tribute: CommunityTribute = {
798               key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
799               view: cv,
800             };
801             return tribute;
802           });
803           cb(communities);
804           communitySub.unsubscribe();
805         }
806       },
807       err => console.error(err),
808       () => console.log("complete")
809     );
810   } else {
811     cb([]);
812   }
813 }
814
815 export function getListingTypeFromProps(props: any): ListingType {
816   return props.match.params.listing_type
817     ? routeListingTypeToEnum(props.match.params.listing_type)
818     : UserService.Instance.localUserView
819     ? Object.values(ListingType)[
820         UserService.Instance.localUserView.local_user.default_listing_type
821       ]
822     : ListingType.Local;
823 }
824
825 // TODO might need to add a user setting for this too
826 export function getDataTypeFromProps(props: any): DataType {
827   return props.match.params.data_type
828     ? routeDataTypeToEnum(props.match.params.data_type)
829     : DataType.Post;
830 }
831
832 export function getSortTypeFromProps(props: any): SortType {
833   return props.match.params.sort
834     ? routeSortTypeToEnum(props.match.params.sort)
835     : UserService.Instance.localUserView
836     ? Object.values(SortType)[
837         UserService.Instance.localUserView.local_user.default_sort_type
838       ]
839     : SortType.Active;
840 }
841
842 export function getPageFromProps(props: any): number {
843   return props.match.params.page ? Number(props.match.params.page) : 1;
844 }
845
846 export function getRecipientIdFromProps(props: any): number {
847   return props.match.params.recipient_id
848     ? Number(props.match.params.recipient_id)
849     : 1;
850 }
851
852 export function getIdFromProps(props: any): number {
853   return Number(props.match.params.id);
854 }
855
856 export function getCommentIdFromProps(props: any): number {
857   return Number(props.match.params.comment_id);
858 }
859
860 export function getUsernameFromProps(props: any): string {
861   return props.match.params.username;
862 }
863
864 export function editCommentRes(data: CommentView, comments: CommentView[]) {
865   let found = comments.find(c => c.comment.id == data.comment.id);
866   if (found) {
867     found.comment.content = data.comment.content;
868     found.comment.updated = data.comment.updated;
869     found.comment.removed = data.comment.removed;
870     found.comment.deleted = data.comment.deleted;
871     found.counts.upvotes = data.counts.upvotes;
872     found.counts.downvotes = data.counts.downvotes;
873     found.counts.score = data.counts.score;
874   }
875 }
876
877 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
878   let found = comments.find(c => c.comment.id == data.comment.id);
879   if (found) {
880     found.saved = data.saved;
881   }
882 }
883
884 export function createCommentLikeRes(
885   data: CommentView,
886   comments: CommentView[]
887 ) {
888   let found = comments.find(c => c.comment.id === data.comment.id);
889   if (found) {
890     found.counts.score = data.counts.score;
891     found.counts.upvotes = data.counts.upvotes;
892     found.counts.downvotes = data.counts.downvotes;
893     if (data.my_vote !== null) {
894       found.my_vote = data.my_vote;
895     }
896   }
897 }
898
899 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
900   let found = posts.find(p => p.post.id == data.post.id);
901   if (found) {
902     createPostLikeRes(data, found);
903   }
904 }
905
906 export function createPostLikeRes(data: PostView, post_view: PostView) {
907   if (post_view) {
908     post_view.counts.score = data.counts.score;
909     post_view.counts.upvotes = data.counts.upvotes;
910     post_view.counts.downvotes = data.counts.downvotes;
911     if (data.my_vote !== null) {
912       post_view.my_vote = data.my_vote;
913     }
914   }
915 }
916
917 export function editPostFindRes(data: PostView, posts: PostView[]) {
918   let found = posts.find(p => p.post.id == data.post.id);
919   if (found) {
920     editPostRes(data, found);
921   }
922 }
923
924 export function editPostRes(data: PostView, post: PostView) {
925   if (post) {
926     post.post.url = data.post.url;
927     post.post.name = data.post.name;
928     post.post.nsfw = data.post.nsfw;
929     post.post.deleted = data.post.deleted;
930     post.post.removed = data.post.removed;
931     post.post.stickied = data.post.stickied;
932     post.post.body = data.post.body;
933     post.post.locked = data.post.locked;
934     post.saved = data.saved;
935   }
936 }
937
938 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
939   let nodes: CommentNodeI[] = [];
940   for (let comment of comments) {
941     nodes.push({ comment_view: comment });
942   }
943   return nodes;
944 }
945
946 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
947   // First, put removed and deleted comments at the bottom, then do your other sorts
948   if (sort == CommentSortType.Top) {
949     tree.sort(
950       (a, b) =>
951         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
952         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
953         b.comment_view.counts.score - a.comment_view.counts.score
954     );
955   } else if (sort == CommentSortType.New) {
956     tree.sort(
957       (a, b) =>
958         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
959         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
960         b.comment_view.comment.published.localeCompare(
961           a.comment_view.comment.published
962         )
963     );
964   } else if (sort == CommentSortType.Old) {
965     tree.sort(
966       (a, b) =>
967         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
968         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
969         a.comment_view.comment.published.localeCompare(
970           b.comment_view.comment.published
971         )
972     );
973   } else if (sort == CommentSortType.Hot) {
974     tree.sort(
975       (a, b) =>
976         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
977         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
978         hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
979     );
980   }
981
982   // Go through the children recursively
983   for (let node of tree) {
984     if (node.children) {
985       commentSort(node.children, sort);
986     }
987   }
988 }
989
990 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
991   commentSort(tree, convertCommentSortType(sort));
992 }
993
994 function convertCommentSortType(sort: SortType): CommentSortType {
995   if (
996     sort == SortType.TopAll ||
997     sort == SortType.TopDay ||
998     sort == SortType.TopWeek ||
999     sort == SortType.TopMonth ||
1000     sort == SortType.TopYear
1001   ) {
1002     return CommentSortType.Top;
1003   } else if (sort == SortType.New) {
1004     return CommentSortType.New;
1005   } else if (sort == SortType.Hot || sort == SortType.Active) {
1006     return CommentSortType.Hot;
1007   } else {
1008     return CommentSortType.Hot;
1009   }
1010 }
1011
1012 export function buildCommentsTree(
1013   comments: CommentView[],
1014   commentSortType: CommentSortType
1015 ): CommentNodeI[] {
1016   let map = new Map<number, CommentNodeI>();
1017   for (let comment_view of comments) {
1018     let node: CommentNodeI = {
1019       comment_view: comment_view,
1020       children: [],
1021     };
1022     map.set(comment_view.comment.id, { ...node });
1023   }
1024   let tree: CommentNodeI[] = [];
1025   for (let comment_view of comments) {
1026     let child = map.get(comment_view.comment.id);
1027     if (comment_view.comment.parent_id) {
1028       let parent_ = map.get(comment_view.comment.parent_id);
1029       parent_.children.push(child);
1030     } else {
1031       tree.push(child);
1032     }
1033
1034     setDepth(child);
1035   }
1036
1037   commentSort(tree, commentSortType);
1038
1039   return tree;
1040 }
1041
1042 function setDepth(node: CommentNodeI, i = 0) {
1043   for (let child of node.children) {
1044     child.depth = i;
1045     setDepth(child, i + 1);
1046   }
1047 }
1048
1049 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1050   // Building a fake node to be used for later
1051   let node: CommentNodeI = {
1052     comment_view: cv,
1053     children: [],
1054     depth: 0,
1055   };
1056
1057   if (cv.comment.parent_id) {
1058     let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1059     if (parentComment) {
1060       node.depth = parentComment.depth + 1;
1061       parentComment.children.unshift(node);
1062     }
1063   } else {
1064     tree.unshift(node);
1065   }
1066 }
1067
1068 export function searchCommentTree(
1069   tree: CommentNodeI[],
1070   id: number
1071 ): CommentNodeI {
1072   for (let node of tree) {
1073     if (node.comment_view.comment.id === id) {
1074       return node;
1075     }
1076
1077     for (const child of node.children) {
1078       const res = searchCommentTree([child], id);
1079
1080       if (res) {
1081         return res;
1082       }
1083     }
1084   }
1085   return null;
1086 }
1087
1088 export const colorList: string[] = [
1089   hsl(0),
1090   hsl(100),
1091   hsl(150),
1092   hsl(200),
1093   hsl(250),
1094   hsl(300),
1095 ];
1096
1097 function hsl(num: number) {
1098   return `hsla(${num}, 35%, 50%, 1)`;
1099 }
1100
1101 export function previewLines(
1102   text: string,
1103   maxChars = 300,
1104   maxLines = 1
1105 ): string {
1106   return (
1107     text
1108       .slice(0, maxChars)
1109       .split("\n")
1110       // Use lines * 2 because markdown requires 2 lines
1111       .slice(0, maxLines * 2)
1112       .join("\n") + "..."
1113   );
1114 }
1115
1116 export function hostname(url: string): string {
1117   let cUrl = new URL(url);
1118   return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1119 }
1120
1121 export function validTitle(title?: string): boolean {
1122   // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1123   if (title === null || title.length < 3) return true;
1124
1125   const regex = new RegExp(/.*\S.*/, "g");
1126
1127   return regex.test(title);
1128 }
1129
1130 export function siteBannerCss(banner: string): string {
1131   return ` \
1132     background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1133     background-attachment: fixed; \
1134     background-position: top; \
1135     background-repeat: no-repeat; \
1136     background-size: 100% cover; \
1137
1138     width: 100%; \
1139     max-height: 100vh; \
1140     `;
1141 }
1142
1143 export function isBrowser() {
1144   return typeof window !== "undefined";
1145 }
1146
1147 export function setIsoData(context: any): IsoData {
1148   let isoData: IsoData = isBrowser()
1149     ? window.isoData
1150     : context.router.staticContext;
1151   return isoData;
1152 }
1153
1154 export function wsSubscribe(parseMessage: any): Subscription {
1155   if (isBrowser()) {
1156     return WebSocketService.Instance.subject
1157       .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1158       .subscribe(
1159         msg => parseMessage(msg),
1160         err => console.error(err),
1161         () => console.log("complete")
1162       );
1163   } else {
1164     return null;
1165   }
1166 }
1167
1168 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1169   if (auth) {
1170     obj.auth = auth;
1171   }
1172 }
1173
1174 export function authField(
1175   throwErr = true,
1176   auth = UserService.Instance.auth
1177 ): string {
1178   if (auth == null && throwErr) {
1179     toast(i18n.t("not_logged_in"), "danger");
1180     throw "Not logged in";
1181   } else {
1182     return auth;
1183   }
1184 }
1185
1186 moment.updateLocale("en", {
1187   relativeTime: {
1188     future: "in %s",
1189     past: "%s ago",
1190     s: "<1m",
1191     ss: "%ds",
1192     m: "1m",
1193     mm: "%dm",
1194     h: "1h",
1195     hh: "%dh",
1196     d: "1d",
1197     dd: "%dd",
1198     w: "1w",
1199     ww: "%dw",
1200     M: "1M",
1201     MM: "%dM",
1202     y: "1Y",
1203     yy: "%dY",
1204   },
1205 });
1206
1207 export function saveScrollPosition(context: any) {
1208   let path: string = context.router.route.location.pathname;
1209   let y = window.scrollY;
1210   sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1211 }
1212
1213 export function restoreScrollPosition(context: any) {
1214   let path: string = context.router.route.location.pathname;
1215   let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1216   window.scrollTo(0, y);
1217 }