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