]> Untitled Git - lemmy-ui.git/blob - src/shared/utils.ts
Adding listing_type to search. #143 (#264)
[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.ml";
84 export const supportLemmyUrl = "https://join.lemmy.ml/support";
85 export const docsUrl = "https://join.lemmy.ml/docs/en/index.html";
86 export const helpGuideUrl = "https://join.lemmy.ml/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 = /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
294   return re.test(String(email).toLowerCase());
295 }
296
297 export function capitalizeFirstLetter(str: string): string {
298   return str.charAt(0).toUpperCase() + str.slice(1);
299 }
300
301 export function routeSortTypeToEnum(sort: string): SortType {
302   return SortType[sort];
303 }
304
305 export function listingTypeFromNum(type_: number): ListingType {
306   return Object.values(ListingType)[type_];
307 }
308
309 export function sortTypeFromNum(type_: number): SortType {
310   return Object.values(SortType)[type_];
311 }
312
313 export function routeListingTypeToEnum(type: string): ListingType {
314   return ListingType[type];
315 }
316
317 export function routeDataTypeToEnum(type: string): DataType {
318   return DataType[capitalizeFirstLetter(type)];
319 }
320
321 export function routeSearchTypeToEnum(type: string): SearchType {
322   return SearchType[type];
323 }
324
325 export async function getPageTitle(url: string) {
326   let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
327   let title = await res.title;
328   return title;
329 }
330
331 export function debounce(func: any, wait = 1000, immediate = false) {
332   // 'private' variable for instance
333   // The returned function will be able to reference this due to closure.
334   // Each call to the returned function will share this common timer.
335   let timeout: any;
336
337   // Calling debounce returns a new anonymous function
338   return function () {
339     // reference the context and args for the setTimeout function
340     var args = arguments;
341
342     // Should the function be called now? If immediate is true
343     //   and not already in a timeout then the answer is: Yes
344     var callNow = immediate && !timeout;
345
346     // This is the basic debounce behaviour where you can call this
347     //   function several times, but it will only execute once
348     //   [before or after imposing a delay].
349     //   Each time the returned function is called, the timer starts over.
350     clearTimeout(timeout);
351
352     // Set the new timeout
353     timeout = setTimeout(function () {
354       // Inside the timeout function, clear the timeout variable
355       // which will let the next execution run when in 'immediate' mode
356       timeout = null;
357
358       // Check if the function already ran with the immediate flag
359       if (!immediate) {
360         // Call the original function with apply
361         // apply lets you define the 'this' object as well as the arguments
362         //    (both captured before setTimeout)
363         func.apply(this, args);
364       }
365     }, wait);
366
367     // Immediate mode and no wait timer? Execute the function..
368     if (callNow) func.apply(this, args);
369   };
370 }
371
372 // TODO
373 export function getLanguage(override?: string): string {
374   let localUserView = UserService.Instance.localUserView;
375   let lang =
376     override ||
377     (localUserView?.local_user.lang
378       ? localUserView.local_user.lang
379       : "browser");
380
381   if (lang == "browser" && isBrowser()) {
382     return getBrowserLanguage();
383   } else {
384     return lang;
385   }
386 }
387
388 export function getBrowserLanguage(): string {
389   return navigator.language;
390 }
391
392 export function getMomentLanguage(): string {
393   let lang = getLanguage();
394   if (lang.startsWith("zh")) {
395     lang = "zh-cn";
396   } else if (lang.startsWith("sv")) {
397     lang = "sv";
398   } else if (lang.startsWith("fr")) {
399     lang = "fr";
400   } else if (lang.startsWith("de")) {
401     lang = "de";
402   } else if (lang.startsWith("ru")) {
403     lang = "ru";
404   } else if (lang.startsWith("es")) {
405     lang = "es";
406   } else if (lang.startsWith("eo")) {
407     lang = "eo";
408   } else if (lang.startsWith("nl")) {
409     lang = "nl";
410   } else if (lang.startsWith("it")) {
411     lang = "it";
412   } else if (lang.startsWith("fi")) {
413     lang = "fi";
414   } else if (lang.startsWith("ca")) {
415     lang = "ca";
416   } else if (lang.startsWith("fa")) {
417     lang = "fa";
418   } else if (lang.startsWith("pl")) {
419     lang = "pl";
420   } else if (lang.startsWith("pt")) {
421     lang = "pt-br";
422   } else if (lang.startsWith("ja")) {
423     lang = "ja";
424   } else if (lang.startsWith("ka")) {
425     lang = "ka";
426   } else if (lang.startsWith("hi")) {
427     lang = "hi";
428   } else if (lang.startsWith("el")) {
429     lang = "el";
430   } else if (lang.startsWith("eu")) {
431     lang = "eu";
432   } else if (lang.startsWith("gl")) {
433     lang = "gl";
434   } else if (lang.startsWith("tr")) {
435     lang = "tr";
436   } else if (lang.startsWith("hu")) {
437     lang = "hu";
438   } else if (lang.startsWith("uk")) {
439     lang = "uk";
440   } else if (lang.startsWith("sq")) {
441     lang = "sq";
442   } else if (lang.startsWith("km")) {
443     lang = "km";
444   } else if (lang.startsWith("ga")) {
445     lang = "ga";
446   } else if (lang.startsWith("sr")) {
447     lang = "sr";
448   } else if (lang.startsWith("ko")) {
449     lang = "ko";
450   } else if (lang.startsWith("da")) {
451     lang = "da";
452   } else if (lang.startsWith("oc")) {
453     lang = "oc";
454   } else if (lang.startsWith("hr")) {
455     lang = "hr";
456   } else if (lang.startsWith("th")) {
457     lang = "th";
458   } else if (lang.startsWith("bg")) {
459     lang = "bg";
460   } else {
461     lang = "en";
462   }
463   return lang;
464 }
465
466 export function setTheme(theme: string, forceReload = false) {
467   if (!isBrowser()) {
468     return;
469   }
470   if (theme === "browser" && !forceReload) {
471     return;
472   }
473   // This is only run on a force reload
474   if (theme == "browser") {
475     theme = "darkly";
476   }
477
478   // Unload all the other themes
479   for (var i = 0; i < themes.length; i++) {
480     let styleSheet = document.getElementById(themes[i]);
481     if (styleSheet) {
482       styleSheet.setAttribute("disabled", "disabled");
483     }
484   }
485
486   document
487     .getElementById("default-light")
488     ?.setAttribute("disabled", "disabled");
489   document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
490
491   // Load the theme dynamically
492   let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
493   loadCss(theme, cssLoc);
494   document.getElementById(theme).removeAttribute("disabled");
495 }
496
497 export function loadCss(id: string, loc: string) {
498   if (!document.getElementById(id)) {
499     var head = document.getElementsByTagName("head")[0];
500     var link = document.createElement("link");
501     link.id = id;
502     link.rel = "stylesheet";
503     link.type = "text/css";
504     link.href = loc;
505     link.media = "all";
506     head.appendChild(link);
507   }
508 }
509
510 export function objectFlip(obj: any) {
511   const ret = {};
512   Object.keys(obj).forEach(key => {
513     ret[obj[key]] = key;
514   });
515   return ret;
516 }
517
518 export function showAvatars(): boolean {
519   return (
520     UserService.Instance.localUserView?.local_user.show_avatars ||
521     !UserService.Instance.localUserView
522   );
523 }
524
525 export function showScores(): boolean {
526   return (
527     UserService.Instance.localUserView?.local_user.show_scores ||
528     !UserService.Instance.localUserView
529   );
530 }
531
532 export function isCakeDay(published: string): boolean {
533   // moment(undefined) or moment.utc(undefined) returns the current date/time
534   // moment(null) or moment.utc(null) returns null
535   const createDate = moment.utc(published || null).local();
536   const currentDate = moment(new Date());
537
538   return (
539     createDate.date() === currentDate.date() &&
540     createDate.month() === currentDate.month() &&
541     createDate.year() !== currentDate.year()
542   );
543 }
544
545 export function toast(text: string, background = "success") {
546   if (isBrowser()) {
547     let backgroundColor = `var(--${background})`;
548     Toastify({
549       text: text,
550       backgroundColor: backgroundColor,
551       gravity: "bottom",
552       position: "left",
553     }).showToast();
554   }
555 }
556
557 export function pictrsDeleteToast(
558   clickToDeleteText: string,
559   deletePictureText: string,
560   deleteUrl: string
561 ) {
562   if (isBrowser()) {
563     let backgroundColor = `var(--light)`;
564     let toast = Toastify({
565       text: clickToDeleteText,
566       backgroundColor: backgroundColor,
567       gravity: "top",
568       position: "right",
569       duration: 10000,
570       onClick: () => {
571         if (toast) {
572           window.location.replace(deleteUrl);
573           alert(deletePictureText);
574           toast.hideToast();
575         }
576       },
577       close: true,
578     }).showToast();
579   }
580 }
581
582 interface NotifyInfo {
583   name: string;
584   icon?: string;
585   link: string;
586   body: string;
587 }
588
589 export function messageToastify(info: NotifyInfo, router: any) {
590   if (isBrowser()) {
591     let htmlBody = info.body ? md.render(info.body) : "";
592     let backgroundColor = `var(--light)`;
593
594     let toast = Toastify({
595       text: `${htmlBody}<br />${info.name}`,
596       avatar: info.icon ? info.icon : null,
597       backgroundColor: backgroundColor,
598       className: "text-dark",
599       close: true,
600       gravity: "top",
601       position: "right",
602       duration: 5000,
603       escapeMarkup: false,
604       onClick: () => {
605         if (toast) {
606           toast.hideToast();
607           router.history.push(info.link);
608         }
609       },
610     }).showToast();
611   }
612 }
613
614 export function notifyPost(post_view: PostView, router: any) {
615   let info: NotifyInfo = {
616     name: post_view.community.name,
617     icon: post_view.community.icon,
618     link: `/post/${post_view.post.id}`,
619     body: post_view.post.name,
620   };
621   notify(info, router);
622 }
623
624 export function notifyComment(comment_view: CommentView, router: any) {
625   let info: NotifyInfo = {
626     name: comment_view.creator.name,
627     icon: comment_view.creator.avatar,
628     link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
629     body: comment_view.comment.content,
630   };
631   notify(info, router);
632 }
633
634 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
635   let info: NotifyInfo = {
636     name: pmv.creator.name,
637     icon: pmv.creator.avatar,
638     link: `/inbox`,
639     body: pmv.private_message.content,
640   };
641   notify(info, router);
642 }
643
644 function notify(info: NotifyInfo, router: any) {
645   messageToastify(info, router);
646
647   if (Notification.permission !== "granted") Notification.requestPermission();
648   else {
649     var notification = new Notification(info.name, {
650       icon: info.icon,
651       body: info.body,
652     });
653
654     notification.onclick = (ev: Event): any => {
655       ev.preventDefault();
656       router.history.push(info.link);
657     };
658   }
659 }
660
661 export function setupTribute() {
662   return new Tribute({
663     noMatchTemplate: function () {
664       return "";
665     },
666     collection: [
667       // Emojis
668       {
669         trigger: ":",
670         menuItemTemplate: (item: any) => {
671           let shortName = `:${item.original.key}:`;
672           return `${item.original.val} ${shortName}`;
673         },
674         selectTemplate: (item: any) => {
675           return `${item.original.val}`;
676         },
677         values: Object.entries(emojiShortName).map(e => {
678           return { key: e[1], val: e[0] };
679         }),
680         allowSpaces: false,
681         autocompleteMode: true,
682         // TODO
683         // menuItemLimit: mentionDropdownFetchLimit,
684         menuShowMinLength: 2,
685       },
686       // Persons
687       {
688         trigger: "@",
689         selectTemplate: (item: any) => {
690           let it: PersonTribute = item.original;
691           return `[${it.key}](${it.view.person.actor_id})`;
692         },
693         values: (text: string, cb: (persons: PersonTribute[]) => any) => {
694           personSearch(text, (persons: PersonTribute[]) => cb(persons));
695         },
696         allowSpaces: false,
697         autocompleteMode: true,
698         // TODO
699         // menuItemLimit: mentionDropdownFetchLimit,
700         menuShowMinLength: 2,
701       },
702
703       // Communities
704       {
705         trigger: "!",
706         selectTemplate: (item: any) => {
707           let it: CommunityTribute = item.original;
708           return `[${it.key}](${it.view.community.actor_id})`;
709         },
710         values: (text: string, cb: any) => {
711           communitySearch(text, (communities: CommunityTribute[]) =>
712             cb(communities)
713           );
714         },
715         allowSpaces: false,
716         autocompleteMode: true,
717         // TODO
718         // menuItemLimit: mentionDropdownFetchLimit,
719         menuShowMinLength: 2,
720       },
721     ],
722   });
723 }
724
725 var tippyInstance: any;
726 if (isBrowser()) {
727   tippyInstance = tippy("[data-tippy-content]");
728 }
729
730 export function setupTippy() {
731   if (isBrowser()) {
732     tippyInstance.forEach((e: any) => e.destroy());
733     tippyInstance = tippy("[data-tippy-content]", {
734       delay: [500, 0],
735       // Display on "long press"
736       touch: ["hold", 500],
737     });
738   }
739 }
740
741 interface PersonTribute {
742   key: string;
743   view: PersonViewSafe;
744 }
745
746 function personSearch(text: string, cb: (persons: PersonTribute[]) => any) {
747   if (text) {
748     let form: Search = {
749       q: text,
750       type_: SearchType.Users,
751       sort: SortType.TopAll,
752       listing_type: ListingType.All,
753       page: 1,
754       limit: mentionDropdownFetchLimit,
755       auth: authField(false),
756     };
757
758     WebSocketService.Instance.send(wsClient.search(form));
759
760     let personSub = WebSocketService.Instance.subject.subscribe(
761       msg => {
762         let res = wsJsonToRes(msg);
763         if (res.op == UserOperation.Search) {
764           let data = res.data as SearchResponse;
765           let persons: PersonTribute[] = data.users.map(pv => {
766             let tribute: PersonTribute = {
767               key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
768               view: pv,
769             };
770             return tribute;
771           });
772           cb(persons);
773           personSub.unsubscribe();
774         }
775       },
776       err => console.error(err),
777       () => console.log("complete")
778     );
779   } else {
780     cb([]);
781   }
782 }
783
784 interface CommunityTribute {
785   key: string;
786   view: CommunityView;
787 }
788
789 function communitySearch(
790   text: string,
791   cb: (communities: CommunityTribute[]) => any
792 ) {
793   if (text) {
794     let form: Search = {
795       q: text,
796       type_: SearchType.Communities,
797       sort: SortType.TopAll,
798       listing_type: ListingType.All,
799       page: 1,
800       limit: mentionDropdownFetchLimit,
801       auth: authField(false),
802     };
803
804     WebSocketService.Instance.send(wsClient.search(form));
805
806     let communitySub = WebSocketService.Instance.subject.subscribe(
807       msg => {
808         let res = wsJsonToRes(msg);
809         if (res.op == UserOperation.Search) {
810           let data = res.data as SearchResponse;
811           let communities: CommunityTribute[] = data.communities.map(cv => {
812             let tribute: CommunityTribute = {
813               key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
814               view: cv,
815             };
816             return tribute;
817           });
818           cb(communities);
819           communitySub.unsubscribe();
820         }
821       },
822       err => console.error(err),
823       () => console.log("complete")
824     );
825   } else {
826     cb([]);
827   }
828 }
829
830 export function getListingTypeFromProps(props: any): ListingType {
831   return props.match.params.listing_type
832     ? routeListingTypeToEnum(props.match.params.listing_type)
833     : UserService.Instance.localUserView
834     ? Object.values(ListingType)[
835         UserService.Instance.localUserView.local_user.default_listing_type
836       ]
837     : ListingType.Local;
838 }
839
840 // TODO might need to add a user setting for this too
841 export function getDataTypeFromProps(props: any): DataType {
842   return props.match.params.data_type
843     ? routeDataTypeToEnum(props.match.params.data_type)
844     : DataType.Post;
845 }
846
847 export function getSortTypeFromProps(props: any): SortType {
848   return props.match.params.sort
849     ? routeSortTypeToEnum(props.match.params.sort)
850     : UserService.Instance.localUserView
851     ? Object.values(SortType)[
852         UserService.Instance.localUserView.local_user.default_sort_type
853       ]
854     : SortType.Active;
855 }
856
857 export function getPageFromProps(props: any): number {
858   return props.match.params.page ? Number(props.match.params.page) : 1;
859 }
860
861 export function getRecipientIdFromProps(props: any): number {
862   return props.match.params.recipient_id
863     ? Number(props.match.params.recipient_id)
864     : 1;
865 }
866
867 export function getIdFromProps(props: any): number {
868   return Number(props.match.params.id);
869 }
870
871 export function getCommentIdFromProps(props: any): number {
872   return Number(props.match.params.comment_id);
873 }
874
875 export function getUsernameFromProps(props: any): string {
876   return props.match.params.username;
877 }
878
879 export function editCommentRes(data: CommentView, comments: CommentView[]) {
880   let found = comments.find(c => c.comment.id == data.comment.id);
881   if (found) {
882     found.comment.content = data.comment.content;
883     found.comment.updated = data.comment.updated;
884     found.comment.removed = data.comment.removed;
885     found.comment.deleted = data.comment.deleted;
886     found.counts.upvotes = data.counts.upvotes;
887     found.counts.downvotes = data.counts.downvotes;
888     found.counts.score = data.counts.score;
889   }
890 }
891
892 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
893   let found = comments.find(c => c.comment.id == data.comment.id);
894   if (found) {
895     found.saved = data.saved;
896   }
897 }
898
899 export function createCommentLikeRes(
900   data: CommentView,
901   comments: CommentView[]
902 ) {
903   let found = comments.find(c => c.comment.id === data.comment.id);
904   if (found) {
905     found.counts.score = data.counts.score;
906     found.counts.upvotes = data.counts.upvotes;
907     found.counts.downvotes = data.counts.downvotes;
908     if (data.my_vote !== null) {
909       found.my_vote = data.my_vote;
910     }
911   }
912 }
913
914 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
915   let found = posts.find(p => p.post.id == data.post.id);
916   if (found) {
917     createPostLikeRes(data, found);
918   }
919 }
920
921 export function createPostLikeRes(data: PostView, post_view: PostView) {
922   if (post_view) {
923     post_view.counts.score = data.counts.score;
924     post_view.counts.upvotes = data.counts.upvotes;
925     post_view.counts.downvotes = data.counts.downvotes;
926     if (data.my_vote !== null) {
927       post_view.my_vote = data.my_vote;
928     }
929   }
930 }
931
932 export function editPostFindRes(data: PostView, posts: PostView[]) {
933   let found = posts.find(p => p.post.id == data.post.id);
934   if (found) {
935     editPostRes(data, found);
936   }
937 }
938
939 export function editPostRes(data: PostView, post: PostView) {
940   if (post) {
941     post.post.url = data.post.url;
942     post.post.name = data.post.name;
943     post.post.nsfw = data.post.nsfw;
944     post.post.deleted = data.post.deleted;
945     post.post.removed = data.post.removed;
946     post.post.stickied = data.post.stickied;
947     post.post.body = data.post.body;
948     post.post.locked = data.post.locked;
949     post.saved = data.saved;
950   }
951 }
952
953 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
954   let nodes: CommentNodeI[] = [];
955   for (let comment of comments) {
956     nodes.push({ comment_view: comment });
957   }
958   return nodes;
959 }
960
961 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
962   // First, put removed and deleted comments at the bottom, then do your other sorts
963   if (sort == CommentSortType.Top) {
964     tree.sort(
965       (a, b) =>
966         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
967         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
968         b.comment_view.counts.score - a.comment_view.counts.score
969     );
970   } else if (sort == CommentSortType.New) {
971     tree.sort(
972       (a, b) =>
973         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
974         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
975         b.comment_view.comment.published.localeCompare(
976           a.comment_view.comment.published
977         )
978     );
979   } else if (sort == CommentSortType.Old) {
980     tree.sort(
981       (a, b) =>
982         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
983         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
984         a.comment_view.comment.published.localeCompare(
985           b.comment_view.comment.published
986         )
987     );
988   } else if (sort == CommentSortType.Hot) {
989     tree.sort(
990       (a, b) =>
991         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
992         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
993         hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
994     );
995   }
996
997   // Go through the children recursively
998   for (let node of tree) {
999     if (node.children) {
1000       commentSort(node.children, sort);
1001     }
1002   }
1003 }
1004
1005 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
1006   commentSort(tree, convertCommentSortType(sort));
1007 }
1008
1009 function convertCommentSortType(sort: SortType): CommentSortType {
1010   if (
1011     sort == SortType.TopAll ||
1012     sort == SortType.TopDay ||
1013     sort == SortType.TopWeek ||
1014     sort == SortType.TopMonth ||
1015     sort == SortType.TopYear
1016   ) {
1017     return CommentSortType.Top;
1018   } else if (sort == SortType.New) {
1019     return CommentSortType.New;
1020   } else if (sort == SortType.Hot || sort == SortType.Active) {
1021     return CommentSortType.Hot;
1022   } else {
1023     return CommentSortType.Hot;
1024   }
1025 }
1026
1027 export function buildCommentsTree(
1028   comments: CommentView[],
1029   commentSortType: CommentSortType
1030 ): CommentNodeI[] {
1031   let map = new Map<number, CommentNodeI>();
1032   for (let comment_view of comments) {
1033     let node: CommentNodeI = {
1034       comment_view: comment_view,
1035       children: [],
1036     };
1037     map.set(comment_view.comment.id, { ...node });
1038   }
1039   let tree: CommentNodeI[] = [];
1040   for (let comment_view of comments) {
1041     let child = map.get(comment_view.comment.id);
1042     if (comment_view.comment.parent_id) {
1043       let parent_ = map.get(comment_view.comment.parent_id);
1044       parent_.children.push(child);
1045     } else {
1046       tree.push(child);
1047     }
1048
1049     setDepth(child);
1050   }
1051
1052   commentSort(tree, commentSortType);
1053
1054   return tree;
1055 }
1056
1057 function setDepth(node: CommentNodeI, i = 0) {
1058   for (let child of node.children) {
1059     child.depth = i;
1060     setDepth(child, i + 1);
1061   }
1062 }
1063
1064 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1065   // Building a fake node to be used for later
1066   let node: CommentNodeI = {
1067     comment_view: cv,
1068     children: [],
1069     depth: 0,
1070   };
1071
1072   if (cv.comment.parent_id) {
1073     let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1074     if (parentComment) {
1075       node.depth = parentComment.depth + 1;
1076       parentComment.children.unshift(node);
1077     }
1078   } else {
1079     tree.unshift(node);
1080   }
1081 }
1082
1083 export function searchCommentTree(
1084   tree: CommentNodeI[],
1085   id: number
1086 ): CommentNodeI {
1087   for (let node of tree) {
1088     if (node.comment_view.comment.id === id) {
1089       return node;
1090     }
1091
1092     for (const child of node.children) {
1093       const res = searchCommentTree([child], id);
1094
1095       if (res) {
1096         return res;
1097       }
1098     }
1099   }
1100   return null;
1101 }
1102
1103 export const colorList: string[] = [
1104   hsl(0),
1105   hsl(100),
1106   hsl(150),
1107   hsl(200),
1108   hsl(250),
1109   hsl(300),
1110 ];
1111
1112 function hsl(num: number) {
1113   return `hsla(${num}, 35%, 50%, 1)`;
1114 }
1115
1116 export function previewLines(
1117   text: string,
1118   maxChars = 300,
1119   maxLines = 1
1120 ): string {
1121   return (
1122     text
1123       .slice(0, maxChars)
1124       .split("\n")
1125       // Use lines * 2 because markdown requires 2 lines
1126       .slice(0, maxLines * 2)
1127       .join("\n") + "..."
1128   );
1129 }
1130
1131 export function hostname(url: string): string {
1132   let cUrl = new URL(url);
1133   return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1134 }
1135
1136 export function validTitle(title?: string): boolean {
1137   // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1138   if (title === null || title.length < 3) return true;
1139
1140   const regex = new RegExp(/.*\S.*/, "g");
1141
1142   return regex.test(title);
1143 }
1144
1145 export function siteBannerCss(banner: string): string {
1146   return ` \
1147     background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1148     background-attachment: fixed; \
1149     background-position: top; \
1150     background-repeat: no-repeat; \
1151     background-size: 100% cover; \
1152
1153     width: 100%; \
1154     max-height: 100vh; \
1155     `;
1156 }
1157
1158 export function isBrowser() {
1159   return typeof window !== "undefined";
1160 }
1161
1162 export function setIsoData(context: any): IsoData {
1163   let isoData: IsoData = isBrowser()
1164     ? window.isoData
1165     : context.router.staticContext;
1166   return isoData;
1167 }
1168
1169 export function wsSubscribe(parseMessage: any): Subscription {
1170   if (isBrowser()) {
1171     return WebSocketService.Instance.subject
1172       .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1173       .subscribe(
1174         msg => parseMessage(msg),
1175         err => console.error(err),
1176         () => console.log("complete")
1177       );
1178   } else {
1179     return null;
1180   }
1181 }
1182
1183 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1184   if (auth) {
1185     obj.auth = auth;
1186   }
1187 }
1188
1189 export function authField(
1190   throwErr = true,
1191   auth = UserService.Instance.auth
1192 ): string {
1193   if (auth == null && throwErr) {
1194     toast(i18n.t("not_logged_in"), "danger");
1195     throw "Not logged in";
1196   } else {
1197     return auth;
1198   }
1199 }
1200
1201 moment.updateLocale("en", {
1202   relativeTime: {
1203     future: "in %s",
1204     past: "%s ago",
1205     s: "<1m",
1206     ss: "%ds",
1207     m: "1m",
1208     mm: "%dm",
1209     h: "1h",
1210     hh: "%dh",
1211     d: "1d",
1212     dd: "%dd",
1213     w: "1w",
1214     ww: "%dw",
1215     M: "1M",
1216     MM: "%dM",
1217     y: "1Y",
1218     yy: "%dY",
1219   },
1220 });
1221
1222 export function saveScrollPosition(context: any) {
1223   let path: string = context.router.route.location.pathname;
1224   let y = window.scrollY;
1225   sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1226 }
1227
1228 export function restoreScrollPosition(context: any) {
1229   let path: string = context.router.route.location.pathname;
1230   let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1231   window.scrollTo(0, y);
1232 }
1233
1234 export function showLocal(isoData: IsoData): boolean {
1235   return isoData.site_res.federated_instances?.linked.length > 0;
1236 }
1237
1238 interface ChoicesValue {
1239   value: string;
1240   label: string;
1241 }
1242
1243 export function communityToChoice(cv: CommunityView): ChoicesValue {
1244   let choice: ChoicesValue = {
1245     value: cv.community.id.toString(),
1246     label: cv.community.name,
1247   };
1248   return choice;
1249 }
1250
1251 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1252   let choice: ChoicesValue = {
1253     value: pvs.person.id.toString(),
1254     label: pvs.person.name,
1255   };
1256   return choice;
1257 }
1258
1259 export async function fetchCommunities(q: string) {
1260   let form: Search = {
1261     q,
1262     type_: SearchType.Communities,
1263     sort: SortType.TopAll,
1264     listing_type: ListingType.All,
1265     page: 1,
1266     limit: fetchLimit,
1267     auth: authField(false),
1268   };
1269   let client = new LemmyHttp(httpBase);
1270   return client.search(form);
1271 }
1272
1273 export async function fetchUsers(q: string) {
1274   let form: Search = {
1275     q,
1276     type_: SearchType.Users,
1277     sort: SortType.TopAll,
1278     listing_type: ListingType.All,
1279     page: 1,
1280     limit: fetchLimit,
1281     auth: authField(false),
1282   };
1283   let client = new LemmyHttp(httpBase);
1284   return client.search(form);
1285 }
1286
1287 export const choicesConfig = {
1288   shouldSort: false,
1289   searchResultLimit: fetchLimit,
1290   classNames: {
1291     containerOuter: "choices",
1292     containerInner: "choices__inner bg-light border-0",
1293     input: "form-control",
1294     inputCloned: "choices__input--cloned",
1295     list: "choices__list",
1296     listItems: "choices__list--multiple",
1297     listSingle: "choices__list--single",
1298     listDropdown: "choices__list--dropdown",
1299     item: "choices__item bg-light",
1300     itemSelectable: "choices__item--selectable",
1301     itemDisabled: "choices__item--disabled",
1302     itemChoice: "choices__item--choice",
1303     placeholder: "choices__placeholder",
1304     group: "choices__group",
1305     groupHeading: "choices__heading",
1306     button: "choices__button",
1307     activeState: "is-active",
1308     focusState: "is-focused",
1309     openState: "is-open",
1310     disabledState: "is-disabled",
1311     highlightedState: "text-info",
1312     selectedState: "text-info",
1313     flippedState: "is-flipped",
1314     loadingState: "is-loading",
1315     noResults: "has-no-results",
1316     noChoices: "has-no-choices",
1317   },
1318 };