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