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