]> Untitled Git - lemmy-ui.git/blob - src/shared/utils.ts
ab3f87929c45ba4092134b3e06fa00eaf5fc8cf6
[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   CommentReportView,
8   CommentView,
9   CommunityBlockView,
10   CommunityModeratorView,
11   CommunityView,
12   GetSiteMetadata,
13   GetSiteResponse,
14   LemmyHttp,
15   LemmyWebsocket,
16   ListingType,
17   MyUserInfo,
18   PersonBlockView,
19   PersonSafe,
20   PersonViewSafe,
21   PostReportView,
22   PostView,
23   PrivateMessageView,
24   RegistrationApplicationView,
25   Search,
26   SearchType,
27   SortType,
28 } from "lemmy-js-client";
29 import markdown_it from "markdown-it";
30 import markdown_it_container from "markdown-it-container";
31 import markdown_it_footnote from "markdown-it-footnote";
32 import markdown_it_html5_embed from "markdown-it-html5-embed";
33 import markdown_it_sub from "markdown-it-sub";
34 import markdown_it_sup from "markdown-it-sup";
35 import moment from "moment";
36 import { Subscription } from "rxjs";
37 import { delay, retryWhen, take } from "rxjs/operators";
38 import tippy from "tippy.js";
39 import Toastify from "toastify-js";
40 import { httpBase } from "./env";
41 import { i18n, languages } from "./i18next";
42 import {
43   CommentNode as CommentNodeI,
44   CommentSortType,
45   DataType,
46   IsoData,
47 } from "./interfaces";
48 import { UserService, WebSocketService } from "./services";
49
50 var Tribute: any;
51 if (isBrowser()) {
52   Tribute = require("tributejs");
53 }
54
55 export const wsClient = new LemmyWebsocket();
56
57 export const favIconUrl = "/static/assets/icons/favicon.svg";
58 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
59 // TODO
60 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
61 export const repoUrl = "https://github.com/LemmyNet";
62 export const joinLemmyUrl = "https://join-lemmy.org";
63 export const donateLemmyUrl = `${joinLemmyUrl}/donate`;
64 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
65 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/about/guide.html`; // TODO find a way to redirect to the non-en folder
66 export const markdownHelpUrl = `${helpGuideUrl}#using-markdown`;
67 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
68 export const archiveTodayUrl = "https://archive.today";
69 export const ghostArchiveUrl = "https://ghostarchive.org";
70 export const webArchiveUrl = "https://web.archive.org";
71 export const elementUrl = "https://element.io";
72
73 export const postRefetchSeconds: number = 60 * 1000;
74 export const fetchLimit = 20;
75 export const trendingFetchLimit = 6;
76 export const mentionDropdownFetchLimit = 10;
77
78 export const relTags = "noopener nofollow";
79
80 const DEFAULT_ALPHABET =
81   "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
82
83 function getRandomCharFromAlphabet(alphabet: string): string {
84   return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
85 }
86
87 export function randomStr(
88   idDesiredLength = 20,
89   alphabet = DEFAULT_ALPHABET
90 ): string {
91   /**
92    * Create n-long array and map it to random chars from given alphabet.
93    * Then join individual chars as string
94    */
95   return Array.from({ length: idDesiredLength })
96     .map(() => {
97       return getRandomCharFromAlphabet(alphabet);
98     })
99     .join("");
100 }
101
102 export const md = new markdown_it({
103   html: false,
104   linkify: true,
105   typographer: true,
106 })
107   .use(markdown_it_sub)
108   .use(markdown_it_sup)
109   .use(markdown_it_footnote)
110   .use(markdown_it_html5_embed, {
111     html5embed: {
112       useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
113       attributes: {
114         audio: 'controls preload="metadata"',
115         video:
116           'width="100%" max-height="100%" controls loop preload="metadata"',
117       },
118     },
119   })
120   .use(markdown_it_container, "spoiler", {
121     validate: function (params: any) {
122       return params.trim().match(/^spoiler\s+(.*)$/);
123     },
124
125     render: function (tokens: any, idx: any) {
126       var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
127
128       if (tokens[idx].nesting === 1) {
129         // opening tag
130         return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
131       } else {
132         // closing tag
133         return "</details>\n";
134       }
135     },
136   });
137
138 export function hotRankComment(comment_view: CommentView): number {
139   return hotRank(comment_view.counts.score, comment_view.comment.published);
140 }
141
142 export function hotRankActivePost(post_view: PostView): number {
143   return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
144 }
145
146 export function hotRankPost(post_view: PostView): number {
147   return hotRank(post_view.counts.score, post_view.post.published);
148 }
149
150 export function hotRank(score: number, timeStr: string): number {
151   // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
152   let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
153   let now: Date = new Date();
154   let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
155
156   let rank =
157     (10000 * Math.log10(Math.max(1, 3 + score))) /
158     Math.pow(hoursElapsed + 2, 1.8);
159
160   // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
161
162   return rank;
163 }
164
165 export function mdToHtml(text: string) {
166   return { __html: md.render(text) };
167 }
168
169 export function getUnixTime(text: string): number {
170   return text ? new Date(text).getTime() / 1000 : undefined;
171 }
172
173 export function futureDaysToUnixTime(days: number): number {
174   return days
175     ? Math.trunc(
176         new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
177       )
178     : undefined;
179 }
180
181 export function canMod(
182   mods: Option<CommunityModeratorView[]>,
183   admins: Option<PersonViewSafe[]>,
184   creator_id: number,
185   myUserInfo = UserService.Instance.myUserInfo,
186   onSelf = false
187 ): boolean {
188   // You can do moderator actions only on the mods added after you.
189   let adminsThenMods = admins
190     .unwrapOr([])
191     .map(a => a.person.id)
192     .concat(mods.unwrapOr([]).map(m => m.moderator.id));
193
194   return myUserInfo.match({
195     some: me => {
196       let myIndex = adminsThenMods.findIndex(
197         id => id == me.local_user_view.person.id
198       );
199       if (myIndex == -1) {
200         return false;
201       } else {
202         // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
203         adminsThenMods = adminsThenMods.slice(0, myIndex + (onSelf ? 0 : 1));
204         return !adminsThenMods.includes(creator_id);
205       }
206     },
207     none: false,
208   });
209 }
210
211 export function canAdmin(
212   admins: Option<PersonViewSafe[]>,
213   creator_id: number,
214   myUserInfo = UserService.Instance.myUserInfo
215 ): boolean {
216   return canMod(None, admins, creator_id, myUserInfo);
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: `/post/${comment_view.post.id}/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): number {
817   return Number(props.match.params.id);
818 }
819
820 export function getCommentIdFromProps(props: any): number {
821   return Number(props.match.params.comment_id);
822 }
823
824 export function getUsernameFromProps(props: any): string {
825   return props.match.params.username;
826 }
827
828 export function editCommentRes(data: CommentView, comments: CommentView[]) {
829   let found = comments.find(c => c.comment.id == data.comment.id);
830   if (found) {
831     found.comment.content = data.comment.content;
832     found.comment.updated = data.comment.updated;
833     found.comment.removed = data.comment.removed;
834     found.comment.deleted = data.comment.deleted;
835     found.counts.upvotes = data.counts.upvotes;
836     found.counts.downvotes = data.counts.downvotes;
837     found.counts.score = data.counts.score;
838   }
839 }
840
841 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
842   let found = comments.find(c => c.comment.id == data.comment.id);
843   if (found) {
844     found.saved = data.saved;
845   }
846 }
847
848 // TODO Should only use the return now, no state?
849 export function updatePersonBlock(
850   data: BlockPersonResponse,
851   myUserInfo = UserService.Instance.myUserInfo
852 ): Option<PersonBlockView[]> {
853   return myUserInfo.match({
854     some: (mui: MyUserInfo) => {
855       if (data.blocked) {
856         mui.person_blocks.push({
857           person: mui.local_user_view.person,
858           target: data.person_view.person,
859         });
860         toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
861       } else {
862         mui.person_blocks = mui.person_blocks.filter(
863           i => i.target.id != data.person_view.person.id
864         );
865         toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
866       }
867       return Some(mui.person_blocks);
868     },
869     none: None,
870   });
871 }
872
873 export function updateCommunityBlock(
874   data: BlockCommunityResponse,
875   myUserInfo = UserService.Instance.myUserInfo
876 ): Option<CommunityBlockView[]> {
877   return myUserInfo.match({
878     some: (mui: MyUserInfo) => {
879       if (data.blocked) {
880         mui.community_blocks.push({
881           person: mui.local_user_view.person,
882           community: data.community_view.community,
883         });
884         toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
885       } else {
886         mui.community_blocks = mui.community_blocks.filter(
887           i => i.community.id != data.community_view.community.id
888         );
889         toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
890       }
891       return Some(mui.community_blocks);
892     },
893     none: None,
894   });
895 }
896
897 export function createCommentLikeRes(
898   data: CommentView,
899   comments: CommentView[]
900 ) {
901   let found = comments.find(c => c.comment.id === data.comment.id);
902   if (found) {
903     found.counts.score = data.counts.score;
904     found.counts.upvotes = data.counts.upvotes;
905     found.counts.downvotes = data.counts.downvotes;
906     if (data.my_vote !== null) {
907       found.my_vote = data.my_vote;
908     }
909   }
910 }
911
912 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
913   let found = posts.find(p => p.post.id == data.post.id);
914   if (found) {
915     createPostLikeRes(data, found);
916   }
917 }
918
919 export function createPostLikeRes(data: PostView, post_view: PostView) {
920   if (post_view) {
921     post_view.counts.score = data.counts.score;
922     post_view.counts.upvotes = data.counts.upvotes;
923     post_view.counts.downvotes = data.counts.downvotes;
924     if (data.my_vote !== null) {
925       post_view.my_vote = data.my_vote;
926     }
927   }
928 }
929
930 export function editPostFindRes(data: PostView, posts: PostView[]) {
931   let found = posts.find(p => p.post.id == data.post.id);
932   if (found) {
933     editPostRes(data, found);
934   }
935 }
936
937 export function editPostRes(data: PostView, post: PostView) {
938   if (post) {
939     post.post.url = data.post.url;
940     post.post.name = data.post.name;
941     post.post.nsfw = data.post.nsfw;
942     post.post.deleted = data.post.deleted;
943     post.post.removed = data.post.removed;
944     post.post.stickied = data.post.stickied;
945     post.post.body = data.post.body;
946     post.post.locked = data.post.locked;
947     post.saved = data.saved;
948   }
949 }
950
951 export function updatePostReportRes(
952   data: PostReportView,
953   reports: PostReportView[]
954 ) {
955   let found = reports.find(p => p.post_report.id == data.post_report.id);
956   if (found) {
957     found.post_report = data.post_report;
958   }
959 }
960
961 export function updateCommentReportRes(
962   data: CommentReportView,
963   reports: CommentReportView[]
964 ) {
965   let found = reports.find(c => c.comment_report.id == data.comment_report.id);
966   if (found) {
967     found.comment_report = data.comment_report;
968   }
969 }
970
971 export function updateRegistrationApplicationRes(
972   data: RegistrationApplicationView,
973   applications: RegistrationApplicationView[]
974 ) {
975   let found = applications.find(
976     ra => ra.registration_application.id == data.registration_application.id
977   );
978   if (found) {
979     found.registration_application = data.registration_application;
980     found.admin = data.admin;
981     found.creator_local_user = data.creator_local_user;
982   }
983 }
984
985 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
986   let nodes: CommentNodeI[] = [];
987   for (let comment of comments) {
988     nodes.push({ comment_view: comment });
989   }
990   return nodes;
991 }
992
993 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
994   // First, put removed and deleted comments at the bottom, then do your other sorts
995   if (sort == CommentSortType.Top) {
996     tree.sort(
997       (a, b) =>
998         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
999         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1000         b.comment_view.counts.score - a.comment_view.counts.score
1001     );
1002   } else if (sort == CommentSortType.New) {
1003     tree.sort(
1004       (a, b) =>
1005         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1006         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1007         b.comment_view.comment.published.localeCompare(
1008           a.comment_view.comment.published
1009         )
1010     );
1011   } else if (sort == CommentSortType.Old) {
1012     tree.sort(
1013       (a, b) =>
1014         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1015         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1016         a.comment_view.comment.published.localeCompare(
1017           b.comment_view.comment.published
1018         )
1019     );
1020   } else if (sort == CommentSortType.Hot) {
1021     tree.sort(
1022       (a, b) =>
1023         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1024         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1025         hotRankComment(b.comment_view as CommentView) -
1026           hotRankComment(a.comment_view as CommentView)
1027     );
1028   }
1029
1030   // Go through the children recursively
1031   for (let node of tree) {
1032     if (node.children) {
1033       commentSort(node.children, sort);
1034     }
1035   }
1036 }
1037
1038 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
1039   commentSort(tree, convertCommentSortType(sort));
1040 }
1041
1042 function convertCommentSortType(sort: SortType): CommentSortType {
1043   if (
1044     sort == SortType.TopAll ||
1045     sort == SortType.TopDay ||
1046     sort == SortType.TopWeek ||
1047     sort == SortType.TopMonth ||
1048     sort == SortType.TopYear
1049   ) {
1050     return CommentSortType.Top;
1051   } else if (sort == SortType.New) {
1052     return CommentSortType.New;
1053   } else if (sort == SortType.Hot || sort == SortType.Active) {
1054     return CommentSortType.Hot;
1055   } else {
1056     return CommentSortType.Hot;
1057   }
1058 }
1059
1060 export function buildCommentsTree(
1061   comments: CommentView[],
1062   commentSortType: CommentSortType
1063 ): CommentNodeI[] {
1064   let map = new Map<number, CommentNodeI>();
1065   for (let comment_view of comments) {
1066     let node: CommentNodeI = {
1067       comment_view: comment_view,
1068       children: [],
1069       depth: 0,
1070     };
1071     map.set(comment_view.comment.id, { ...node });
1072   }
1073   let tree: CommentNodeI[] = [];
1074   for (let comment_view of comments) {
1075     let child = map.get(comment_view.comment.id);
1076     let parent_id = comment_view.comment.parent_id;
1077     parent_id.match({
1078       some: parentId => {
1079         let parent = map.get(parentId);
1080         // Necessary because blocked comment might not exist
1081         if (parent) {
1082           parent.children.push(child);
1083         }
1084       },
1085       none: () => {
1086         tree.push(child);
1087       },
1088     });
1089
1090     setDepth(child);
1091   }
1092
1093   commentSort(tree, commentSortType);
1094
1095   return tree;
1096 }
1097
1098 function setDepth(node: CommentNodeI, i = 0) {
1099   for (let child of node.children) {
1100     child.depth = i;
1101     setDepth(child, i + 1);
1102   }
1103 }
1104
1105 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1106   // Building a fake node to be used for later
1107   let node: CommentNodeI = {
1108     comment_view: cv,
1109     children: [],
1110     depth: 0,
1111   };
1112
1113   cv.comment.parent_id.match({
1114     some: parentId => {
1115       let parentComment = searchCommentTree(tree, parentId);
1116       parentComment.match({
1117         some: pComment => {
1118           node.depth = pComment.depth + 1;
1119           pComment.children.unshift(node);
1120         },
1121         none: void 0,
1122       });
1123     },
1124     none: () => {
1125       tree.unshift(node);
1126     },
1127   });
1128 }
1129
1130 export function searchCommentTree(
1131   tree: CommentNodeI[],
1132   id: number
1133 ): Option<CommentNodeI> {
1134   for (let node of tree) {
1135     if (node.comment_view.comment.id === id) {
1136       return Some(node);
1137     }
1138
1139     for (const child of node.children) {
1140       let res = searchCommentTree([child], id);
1141
1142       if (res.isSome()) {
1143         return res;
1144       }
1145     }
1146   }
1147   return None;
1148 }
1149
1150 export const colorList: string[] = [
1151   hsl(0),
1152   hsl(100),
1153   hsl(150),
1154   hsl(200),
1155   hsl(250),
1156   hsl(300),
1157 ];
1158
1159 function hsl(num: number) {
1160   return `hsla(${num}, 35%, 50%, 1)`;
1161 }
1162
1163 export function hostname(url: string): string {
1164   let cUrl = new URL(url);
1165   return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1166 }
1167
1168 export function validTitle(title?: string): boolean {
1169   // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1170   if (!title || title.length < 3) return true;
1171
1172   const regex = new RegExp(/.*\S.*/, "g");
1173
1174   return regex.test(title);
1175 }
1176
1177 export function siteBannerCss(banner: string): string {
1178   return ` \
1179     background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1180     background-attachment: fixed; \
1181     background-position: top; \
1182     background-repeat: no-repeat; \
1183     background-size: 100% cover; \
1184
1185     width: 100%; \
1186     max-height: 100vh; \
1187     `;
1188 }
1189
1190 export function isBrowser() {
1191   return typeof window !== "undefined";
1192 }
1193
1194 export function setIsoData<Type1, Type2, Type3, Type4, Type5>(
1195   context: any,
1196   cls1?: ClassConstructor<Type1>,
1197   cls2?: ClassConstructor<Type2>,
1198   cls3?: ClassConstructor<Type3>,
1199   cls4?: ClassConstructor<Type4>,
1200   cls5?: ClassConstructor<Type5>
1201 ): IsoData {
1202   // If its the browser, you need to deserialize the data from the window
1203   if (isBrowser()) {
1204     let json = window.isoData;
1205     let routeData = json.routeData;
1206     let routeDataOut: any[] = [];
1207
1208     // Can't do array looping because of specific type constructor required
1209     if (routeData[0]) {
1210       routeDataOut[0] = convertWindowJson(cls1, routeData[0]);
1211     }
1212     if (routeData[1]) {
1213       routeDataOut[1] = convertWindowJson(cls2, routeData[1]);
1214     }
1215     if (routeData[2]) {
1216       routeDataOut[2] = convertWindowJson(cls3, routeData[2]);
1217     }
1218     if (routeData[3]) {
1219       routeDataOut[3] = convertWindowJson(cls4, routeData[3]);
1220     }
1221     if (routeData[4]) {
1222       routeDataOut[4] = convertWindowJson(cls5, routeData[4]);
1223     }
1224     let site_res = convertWindowJson(GetSiteResponse, json.site_res);
1225
1226     let isoData: IsoData = {
1227       path: json.path,
1228       site_res,
1229       routeData: routeDataOut,
1230     };
1231     return isoData;
1232   } else return context.router.staticContext;
1233 }
1234
1235 /**
1236  * Necessary since window ISOData can't store function types like Option
1237  */
1238 export function convertWindowJson<T>(cls: ClassConstructor<T>, data: any): T {
1239   return deserialize(cls, serialize(data));
1240 }
1241
1242 export function wsSubscribe(parseMessage: any): Subscription {
1243   if (isBrowser()) {
1244     return WebSocketService.Instance.subject
1245       .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1246       .subscribe(
1247         msg => parseMessage(msg),
1248         err => console.error(err),
1249         () => console.log("complete")
1250       );
1251   } else {
1252     return null;
1253   }
1254 }
1255
1256 moment.updateLocale("en", {
1257   relativeTime: {
1258     future: "in %s",
1259     past: "%s ago",
1260     s: "<1m",
1261     ss: "%ds",
1262     m: "1m",
1263     mm: "%dm",
1264     h: "1h",
1265     hh: "%dh",
1266     d: "1d",
1267     dd: "%dd",
1268     w: "1w",
1269     ww: "%dw",
1270     M: "1M",
1271     MM: "%dM",
1272     y: "1Y",
1273     yy: "%dY",
1274   },
1275 });
1276
1277 export function saveScrollPosition(context: any) {
1278   let path: string = context.router.route.location.pathname;
1279   let y = window.scrollY;
1280   sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1281 }
1282
1283 export function restoreScrollPosition(context: any) {
1284   let path: string = context.router.route.location.pathname;
1285   let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1286   window.scrollTo(0, y);
1287 }
1288
1289 export function showLocal(isoData: IsoData): boolean {
1290   return isoData.site_res.federated_instances
1291     .map(f => f.linked.length > 0)
1292     .unwrapOr(false);
1293 }
1294
1295 export interface ChoicesValue {
1296   value: string;
1297   label: string;
1298 }
1299
1300 export function communityToChoice(cv: CommunityView): ChoicesValue {
1301   let choice: ChoicesValue = {
1302     value: cv.community.id.toString(),
1303     label: communitySelectName(cv),
1304   };
1305   return choice;
1306 }
1307
1308 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1309   let choice: ChoicesValue = {
1310     value: pvs.person.id.toString(),
1311     label: personSelectName(pvs),
1312   };
1313   return choice;
1314 }
1315
1316 export async function fetchCommunities(q: string) {
1317   let form = new Search({
1318     q,
1319     type_: Some(SearchType.Communities),
1320     sort: Some(SortType.TopAll),
1321     listing_type: Some(ListingType.All),
1322     page: Some(1),
1323     limit: Some(fetchLimit),
1324     community_id: None,
1325     community_name: None,
1326     creator_id: None,
1327     auth: auth(false).ok(),
1328   });
1329   let client = new LemmyHttp(httpBase);
1330   return client.search(form);
1331 }
1332
1333 export async function fetchUsers(q: string) {
1334   let form = new Search({
1335     q,
1336     type_: Some(SearchType.Users),
1337     sort: Some(SortType.TopAll),
1338     listing_type: Some(ListingType.All),
1339     page: Some(1),
1340     limit: Some(fetchLimit),
1341     community_id: None,
1342     community_name: None,
1343     creator_id: None,
1344     auth: auth(false).ok(),
1345   });
1346   let client = new LemmyHttp(httpBase);
1347   return client.search(form);
1348 }
1349
1350 export const choicesConfig = {
1351   shouldSort: false,
1352   searchResultLimit: fetchLimit,
1353   classNames: {
1354     containerOuter: "choices",
1355     containerInner: "choices__inner bg-secondary border-0",
1356     input: "form-control",
1357     inputCloned: "choices__input--cloned",
1358     list: "choices__list",
1359     listItems: "choices__list--multiple",
1360     listSingle: "choices__list--single",
1361     listDropdown: "choices__list--dropdown",
1362     item: "choices__item bg-secondary",
1363     itemSelectable: "choices__item--selectable",
1364     itemDisabled: "choices__item--disabled",
1365     itemChoice: "choices__item--choice",
1366     placeholder: "choices__placeholder",
1367     group: "choices__group",
1368     groupHeading: "choices__heading",
1369     button: "choices__button",
1370     activeState: "is-active",
1371     focusState: "is-focused",
1372     openState: "is-open",
1373     disabledState: "is-disabled",
1374     highlightedState: "text-info",
1375     selectedState: "text-info",
1376     flippedState: "is-flipped",
1377     loadingState: "is-loading",
1378     noResults: "has-no-results",
1379     noChoices: "has-no-choices",
1380   },
1381 };
1382
1383 export const choicesModLogConfig = {
1384   shouldSort: false,
1385   searchResultLimit: fetchLimit,
1386   classNames: {
1387     containerOuter: "choices mb-2 custom-select col-4 px-0",
1388     containerInner: "choices__inner bg-secondary border-0 py-0 modlog-choices-font-size",
1389     input: "form-control",
1390     inputCloned: "choices__input--cloned w-100",
1391     list: "choices__list",
1392     listItems: "choices__list--multiple",
1393     listSingle: "choices__list--single py-0",
1394     listDropdown: "choices__list--dropdown",
1395     item: "choices__item bg-secondary",
1396     itemSelectable: "choices__item--selectable",
1397     itemDisabled: "choices__item--disabled",
1398     itemChoice: "choices__item--choice",
1399     placeholder: "choices__placeholder",
1400     group: "choices__group",
1401     groupHeading: "choices__heading",
1402     button: "choices__button",
1403     activeState: "is-active",
1404     focusState: "is-focused",
1405     openState: "is-open",
1406     disabledState: "is-disabled",
1407     highlightedState: "text-info",
1408     selectedState: "text-info",
1409     flippedState: "is-flipped",
1410     loadingState: "is-loading",
1411     noResults: "has-no-results",
1412     noChoices: "has-no-choices",
1413   },
1414 };
1415
1416 export function communitySelectName(cv: CommunityView): string {
1417   return cv.community.local
1418     ? cv.community.title
1419     : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1420 }
1421
1422 export function personSelectName(pvs: PersonViewSafe): string {
1423   let pName = pvs.person.display_name.unwrapOr(pvs.person.name);
1424   return pvs.person.local ? pName : `${hostname(pvs.person.actor_id)}/${pName}`;
1425 }
1426
1427 export function initializeSite(site: GetSiteResponse) {
1428   UserService.Instance.myUserInfo = site.my_user;
1429   i18n.changeLanguage(getLanguages()[0]);
1430 }
1431
1432 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1433   maximumSignificantDigits: 3,
1434   //@ts-ignore
1435   notation: "compact",
1436   compactDisplay: "short",
1437 });
1438
1439 export function numToSI(value: number): string {
1440   return SHORTNUM_SI_FORMAT.format(value);
1441 }
1442
1443 export function isBanned(ps: PersonSafe): boolean {
1444   let expires = ps.ban_expires;
1445   // Add Z to convert from UTC date
1446   // TODO this check probably isn't necessary anymore
1447   if (expires.isSome()) {
1448     if (ps.banned && new Date(expires.unwrap() + "Z") > new Date()) {
1449       return true;
1450     } else {
1451       return false;
1452     }
1453   } else {
1454     return ps.banned;
1455   }
1456 }
1457
1458 export function pushNotNull(array: any[], new_item?: any) {
1459   if (new_item) {
1460     array.push(...new_item);
1461   }
1462 }
1463
1464 export function auth(throwErr = true): Result<string, string> {
1465   return UserService.Instance.auth(throwErr);
1466 }
1467
1468 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1469   return siteRes.site_view.map(s => s.site.enable_downvotes).unwrapOr(true);
1470 }
1471
1472 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1473   return siteRes.site_view.map(s => s.site.enable_nsfw).unwrapOr(false);
1474 }