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