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