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