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