]> Untitled Git - lemmy-ui.git/blob - src/shared/utils.ts
Adding new site setup fields. (#840)
[lemmy-ui.git] / src / shared / utils.ts
1 import { Err, None, Ok, 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   PrivateMessageReportView,
27   PrivateMessageView,
28   RegistrationApplicationView,
29   Search,
30   SearchType,
31   SortType,
32 } from "lemmy-js-client";
33 import markdown_it from "markdown-it";
34 import markdown_it_container from "markdown-it-container";
35 import markdown_it_footnote from "markdown-it-footnote";
36 import markdown_it_html5_embed from "markdown-it-html5-embed";
37 import markdown_it_sub from "markdown-it-sub";
38 import markdown_it_sup from "markdown-it-sup";
39 import moment from "moment";
40 import { Subscription } from "rxjs";
41 import { delay, retryWhen, take } from "rxjs/operators";
42 import tippy from "tippy.js";
43 import Toastify from "toastify-js";
44 import { httpBase } from "./env";
45 import { i18n, languages } from "./i18next";
46 import { DataType, IsoData } from "./interfaces";
47 import { UserService, WebSocketService } from "./services";
48
49 var Tribute: any;
50 if (isBrowser()) {
51   Tribute = require("tributejs");
52 }
53
54 export const wsClient = new LemmyWebsocket();
55
56 export const favIconUrl = "/static/assets/icons/favicon.svg";
57 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
58 // TODO
59 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
60 export const repoUrl = "https://github.com/LemmyNet";
61 export const joinLemmyUrl = "https://join-lemmy.org";
62 export const donateLemmyUrl = `${joinLemmyUrl}/donate`;
63 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
64 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/about/guide.html`; // TODO find a way to redirect to the non-en folder
65 export const markdownHelpUrl = `${helpGuideUrl}#using-markdown`;
66 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
67 export const archiveTodayUrl = "https://archive.today";
68 export const ghostArchiveUrl = "https://ghostarchive.org";
69 export const webArchiveUrl = "https://web.archive.org";
70 export const elementUrl = "https://element.io";
71
72 export const postRefetchSeconds: number = 60 * 1000;
73 export const fetchLimit = 40;
74 export const trendingFetchLimit = 6;
75 export const mentionDropdownFetchLimit = 10;
76 export const commentTreeMaxDepth = 8;
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   onSelf = false
216 ): boolean {
217   return canMod(None, admins, creator_id, myUserInfo, onSelf);
218 }
219
220 export function isMod(
221   mods: Option<CommunityModeratorView[]>,
222   creator_id: number
223 ): boolean {
224   return mods.match({
225     some: mods => mods.map(m => m.moderator.id).includes(creator_id),
226     none: false,
227   });
228 }
229
230 export function amMod(
231   mods: Option<CommunityModeratorView[]>,
232   myUserInfo = UserService.Instance.myUserInfo
233 ): boolean {
234   return myUserInfo.match({
235     some: mui => isMod(mods, mui.local_user_view.person.id),
236     none: false,
237   });
238 }
239
240 export function isAdmin(
241   admins: Option<PersonViewSafe[]>,
242   creator_id: number
243 ): boolean {
244   return admins.match({
245     some: admins => admins.map(a => a.person.id).includes(creator_id),
246     none: false,
247   });
248 }
249
250 export function amAdmin(myUserInfo = UserService.Instance.myUserInfo): boolean {
251   return myUserInfo
252     .map(mui => mui.local_user_view.person.admin)
253     .unwrapOr(false);
254 }
255
256 export function amCommunityCreator(
257   mods: Option<CommunityModeratorView[]>,
258   creator_id: number,
259   myUserInfo = UserService.Instance.myUserInfo
260 ): boolean {
261   return mods.match({
262     some: mods =>
263       myUserInfo
264         .map(mui => mui.local_user_view.person.id)
265         .match({
266           some: myId =>
267             myId == mods[0].moderator.id &&
268             // Don't allow mod actions on yourself
269             myId != creator_id,
270           none: false,
271         }),
272     none: false,
273   });
274 }
275
276 export function amSiteCreator(
277   admins: Option<PersonViewSafe[]>,
278   creator_id: number,
279   myUserInfo = UserService.Instance.myUserInfo
280 ): boolean {
281   return admins.match({
282     some: admins =>
283       myUserInfo
284         .map(mui => mui.local_user_view.person.id)
285         .match({
286           some: myId =>
287             myId == admins[0].person.id &&
288             // Don't allow mod actions on yourself
289             myId != creator_id,
290           none: false,
291         }),
292     none: false,
293   });
294 }
295
296 export function amTopMod(
297   mods: Option<CommunityModeratorView[]>,
298   myUserInfo = UserService.Instance.myUserInfo
299 ): boolean {
300   return mods.match({
301     some: mods =>
302       myUserInfo.match({
303         some: mui => mods[0].moderator.id == mui.local_user_view.person.id,
304         none: false,
305       }),
306     none: false,
307   });
308 }
309
310 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
311 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
312
313 export function isImage(url: string) {
314   return imageRegex.test(url);
315 }
316
317 export function isVideo(url: string) {
318   return videoRegex.test(url);
319 }
320
321 export function validURL(str: string) {
322   return !!new URL(str);
323 }
324
325 export function communityRSSUrl(actorId: string, sort: string): string {
326   let url = new URL(actorId);
327   return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
328 }
329
330 export function validEmail(email: string) {
331   let re =
332     /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
333   return re.test(String(email).toLowerCase());
334 }
335
336 export function capitalizeFirstLetter(str: string): string {
337   return str.charAt(0).toUpperCase() + str.slice(1);
338 }
339
340 export function routeSortTypeToEnum(sort: string): SortType {
341   return SortType[sort];
342 }
343
344 export function listingTypeFromNum(type_: number): ListingType {
345   return Object.values(ListingType)[type_];
346 }
347
348 export function sortTypeFromNum(type_: number): SortType {
349   return Object.values(SortType)[type_];
350 }
351
352 export function routeListingTypeToEnum(type: string): ListingType {
353   return ListingType[type];
354 }
355
356 export function routeDataTypeToEnum(type: string): DataType {
357   return DataType[capitalizeFirstLetter(type)];
358 }
359
360 export function routeSearchTypeToEnum(type: string): SearchType {
361   return SearchType[type];
362 }
363
364 export async function getSiteMetadata(url: string) {
365   let form = new GetSiteMetadata({
366     url,
367   });
368   let client = new LemmyHttp(httpBase);
369   return client.getSiteMetadata(form);
370 }
371
372 export function debounce(func: any, wait = 1000, immediate = false) {
373   // 'private' variable for instance
374   // The returned function will be able to reference this due to closure.
375   // Each call to the returned function will share this common timer.
376   let timeout: any;
377
378   // Calling debounce returns a new anonymous function
379   return function () {
380     // reference the context and args for the setTimeout function
381     var args = arguments;
382
383     // Should the function be called now? If immediate is true
384     //   and not already in a timeout then the answer is: Yes
385     var callNow = immediate && !timeout;
386
387     // This is the basic debounce behaviour where you can call this
388     //   function several times, but it will only execute once
389     //   [before or after imposing a delay].
390     //   Each time the returned function is called, the timer starts over.
391     clearTimeout(timeout);
392
393     // Set the new timeout
394     timeout = setTimeout(function () {
395       // Inside the timeout function, clear the timeout variable
396       // which will let the next execution run when in 'immediate' mode
397       timeout = null;
398
399       // Check if the function already ran with the immediate flag
400       if (!immediate) {
401         // Call the original function with apply
402         // apply lets you define the 'this' object as well as the arguments
403         //    (both captured before setTimeout)
404         func.apply(this, args);
405       }
406     }, wait);
407
408     // Immediate mode and no wait timer? Execute the function..
409     if (callNow) func.apply(this, args);
410   };
411 }
412
413 export function getLanguages(
414   override?: string,
415   myUserInfo = UserService.Instance.myUserInfo
416 ): string[] {
417   let myLang = myUserInfo
418     .map(m => m.local_user_view.local_user.interface_language)
419     .unwrapOr("browser");
420   let lang = override || myLang;
421
422   if (lang == "browser" && isBrowser()) {
423     return getBrowserLanguages();
424   } else {
425     return [lang];
426   }
427 }
428
429 function getBrowserLanguages(): string[] {
430   // Intersect lemmy's langs, with the browser langs
431   let langs = languages ? languages.map(l => l.code) : ["en"];
432
433   // NOTE, mobile browsers seem to be missing this list, so append en
434   let allowedLangs = navigator.languages
435     .concat("en")
436     .filter(v => langs.includes(v));
437   return allowedLangs;
438 }
439
440 export async function fetchThemeList(): Promise<string[]> {
441   return fetch("/css/themelist").then(res => res.json());
442 }
443
444 export async function setTheme(theme: string, forceReload = false) {
445   if (!isBrowser()) {
446     return;
447   }
448   if (theme === "browser" && !forceReload) {
449     return;
450   }
451   // This is only run on a force reload
452   if (theme == "browser") {
453     theme = "darkly";
454   }
455
456   let themeList = await fetchThemeList();
457
458   // Unload all the other themes
459   for (var i = 0; i < themeList.length; i++) {
460     let styleSheet = document.getElementById(themeList[i]);
461     if (styleSheet) {
462       styleSheet.setAttribute("disabled", "disabled");
463     }
464   }
465
466   document
467     .getElementById("default-light")
468     ?.setAttribute("disabled", "disabled");
469   document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
470
471   // Load the theme dynamically
472   let cssLoc = `/css/themes/${theme}.css`;
473
474   loadCss(theme, cssLoc);
475   document.getElementById(theme).removeAttribute("disabled");
476 }
477
478 export function loadCss(id: string, loc: string) {
479   if (!document.getElementById(id)) {
480     var head = document.getElementsByTagName("head")[0];
481     var link = document.createElement("link");
482     link.id = id;
483     link.rel = "stylesheet";
484     link.type = "text/css";
485     link.href = loc;
486     link.media = "all";
487     head.appendChild(link);
488   }
489 }
490
491 export function objectFlip(obj: any) {
492   const ret = {};
493   Object.keys(obj).forEach(key => {
494     ret[obj[key]] = key;
495   });
496   return ret;
497 }
498
499 export function showAvatars(
500   myUserInfo: Option<MyUserInfo> = UserService.Instance.myUserInfo
501 ): boolean {
502   return myUserInfo
503     .map(m => m.local_user_view.local_user.show_avatars)
504     .unwrapOr(true);
505 }
506
507 export function showScores(
508   myUserInfo: Option<MyUserInfo> = UserService.Instance.myUserInfo
509 ): boolean {
510   return myUserInfo
511     .map(m => m.local_user_view.local_user.show_scores)
512     .unwrapOr(true);
513 }
514
515 export function isCakeDay(published: string): boolean {
516   // moment(undefined) or moment.utc(undefined) returns the current date/time
517   // moment(null) or moment.utc(null) returns null
518   const createDate = moment.utc(published).local();
519   const currentDate = moment(new Date());
520
521   return (
522     createDate.date() === currentDate.date() &&
523     createDate.month() === currentDate.month() &&
524     createDate.year() !== currentDate.year()
525   );
526 }
527
528 export function toast(text: string, background = "success") {
529   if (isBrowser()) {
530     let backgroundColor = `var(--${background})`;
531     Toastify({
532       text: text,
533       backgroundColor: backgroundColor,
534       gravity: "bottom",
535       position: "left",
536     }).showToast();
537   }
538 }
539
540 export function pictrsDeleteToast(
541   clickToDeleteText: string,
542   deletePictureText: string,
543   failedDeletePictureText: string,
544   deleteUrl: string
545 ) {
546   if (isBrowser()) {
547     let backgroundColor = `var(--light)`;
548     let toast = Toastify({
549       text: clickToDeleteText,
550       backgroundColor: backgroundColor,
551       gravity: "top",
552       position: "right",
553       duration: 10000,
554       onClick: () => {
555         if (toast) {
556           fetch(deleteUrl).then(res => {
557             toast.hideToast();
558             if (res.ok === true) {
559               alert(deletePictureText);
560             } else {
561               alert(failedDeletePictureText);
562             }
563           });
564         }
565       },
566       close: true,
567     }).showToast();
568   }
569 }
570
571 interface NotifyInfo {
572   name: string;
573   icon: Option<string>;
574   link: string;
575   body: string;
576 }
577
578 export function messageToastify(info: NotifyInfo, router: any) {
579   if (isBrowser()) {
580     let htmlBody = info.body ? md.render(info.body) : "";
581     let backgroundColor = `var(--light)`;
582
583     let toast = Toastify({
584       text: `${htmlBody}<br />${info.name}`,
585       avatar: info.icon,
586       backgroundColor: backgroundColor,
587       className: "text-dark",
588       close: true,
589       gravity: "top",
590       position: "right",
591       duration: 5000,
592       escapeMarkup: false,
593       onClick: () => {
594         if (toast) {
595           toast.hideToast();
596           router.history.push(info.link);
597         }
598       },
599     }).showToast();
600   }
601 }
602
603 export function notifyPost(post_view: PostView, router: any) {
604   let info: NotifyInfo = {
605     name: post_view.community.name,
606     icon: post_view.community.icon,
607     link: `/post/${post_view.post.id}`,
608     body: post_view.post.name,
609   };
610   notify(info, router);
611 }
612
613 export function notifyComment(comment_view: CommentView, router: any) {
614   let info: NotifyInfo = {
615     name: comment_view.creator.name,
616     icon: comment_view.creator.avatar,
617     link: `/comment/${comment_view.comment.id}`,
618     body: comment_view.comment.content,
619   };
620   notify(info, router);
621 }
622
623 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
624   let info: NotifyInfo = {
625     name: pmv.creator.name,
626     icon: pmv.creator.avatar,
627     link: `/inbox`,
628     body: pmv.private_message.content,
629   };
630   notify(info, router);
631 }
632
633 function notify(info: NotifyInfo, router: any) {
634   messageToastify(info, router);
635
636   if (Notification.permission !== "granted") Notification.requestPermission();
637   else {
638     var notification = new Notification(info.name, {
639       ...{ body: info.body },
640       ...(info.icon.isSome() && { icon: info.icon.unwrap() }),
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 export function getDataTypeFromProps(props: any): DataType {
785   return props.match.params.data_type
786     ? routeDataTypeToEnum(props.match.params.data_type)
787     : DataType.Post;
788 }
789
790 export function getSortTypeFromProps(
791   props: any,
792   myUserInfo = UserService.Instance.myUserInfo
793 ): SortType {
794   return props.match.params.sort
795     ? routeSortTypeToEnum(props.match.params.sort)
796     : myUserInfo.match({
797         some: mui =>
798           Object.values(SortType)[
799             mui.local_user_view.local_user.default_sort_type
800           ],
801         none: SortType.Active,
802       });
803 }
804
805 export function getPageFromProps(props: any): number {
806   return props.match.params.page ? Number(props.match.params.page) : 1;
807 }
808
809 export function getRecipientIdFromProps(props: any): number {
810   return props.match.params.recipient_id
811     ? Number(props.match.params.recipient_id)
812     : 1;
813 }
814
815 export function getIdFromProps(props: any): Option<number> {
816   let id: string = props.match.params.post_id;
817   return id ? Some(Number(id)) : None;
818 }
819
820 export function getCommentIdFromProps(props: any): Option<number> {
821   let id: string = props.match.params.comment_id;
822   return id ? Some(Number(id)) : None;
823 }
824
825 export function getUsernameFromProps(props: any): string {
826   return props.match.params.username;
827 }
828
829 export function editCommentRes(data: CommentView, comments: CommentView[]) {
830   let found = comments.find(c => c.comment.id == data.comment.id);
831   if (found) {
832     found.comment.content = data.comment.content;
833     found.comment.distinguished = data.comment.distinguished;
834     found.comment.updated = data.comment.updated;
835     found.comment.removed = data.comment.removed;
836     found.comment.deleted = data.comment.deleted;
837     found.counts.upvotes = data.counts.upvotes;
838     found.counts.downvotes = data.counts.downvotes;
839     found.counts.score = data.counts.score;
840   }
841 }
842
843 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
844   let found = comments.find(c => c.comment.id == data.comment.id);
845   if (found) {
846     found.saved = data.saved;
847   }
848 }
849
850 // TODO Should only use the return now, no state?
851 export function updatePersonBlock(
852   data: BlockPersonResponse,
853   myUserInfo = UserService.Instance.myUserInfo
854 ): Option<PersonBlockView[]> {
855   return myUserInfo.match({
856     some: (mui: MyUserInfo) => {
857       if (data.blocked) {
858         mui.person_blocks.push({
859           person: mui.local_user_view.person,
860           target: data.person_view.person,
861         });
862         toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
863       } else {
864         mui.person_blocks = mui.person_blocks.filter(
865           i => i.target.id != data.person_view.person.id
866         );
867         toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
868       }
869       return Some(mui.person_blocks);
870     },
871     none: None,
872   });
873 }
874
875 export function updateCommunityBlock(
876   data: BlockCommunityResponse,
877   myUserInfo = UserService.Instance.myUserInfo
878 ): Option<CommunityBlockView[]> {
879   return myUserInfo.match({
880     some: (mui: MyUserInfo) => {
881       if (data.blocked) {
882         mui.community_blocks.push({
883           person: mui.local_user_view.person,
884           community: data.community_view.community,
885         });
886         toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
887       } else {
888         mui.community_blocks = mui.community_blocks.filter(
889           i => i.community.id != data.community_view.community.id
890         );
891         toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
892       }
893       return Some(mui.community_blocks);
894     },
895     none: None,
896   });
897 }
898
899 export function createCommentLikeRes(
900   data: CommentView,
901   comments: CommentView[]
902 ) {
903   let found = comments.find(c => c.comment.id === data.comment.id);
904   if (found) {
905     found.counts.score = data.counts.score;
906     found.counts.upvotes = data.counts.upvotes;
907     found.counts.downvotes = data.counts.downvotes;
908     if (data.my_vote !== null) {
909       found.my_vote = data.my_vote;
910     }
911   }
912 }
913
914 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
915   let found = posts.find(p => p.post.id == data.post.id);
916   if (found) {
917     createPostLikeRes(data, found);
918   }
919 }
920
921 export function createPostLikeRes(data: PostView, post_view: PostView) {
922   if (post_view) {
923     post_view.counts.score = data.counts.score;
924     post_view.counts.upvotes = data.counts.upvotes;
925     post_view.counts.downvotes = data.counts.downvotes;
926     if (data.my_vote !== null) {
927       post_view.my_vote = data.my_vote;
928     }
929   }
930 }
931
932 export function editPostFindRes(data: PostView, posts: PostView[]) {
933   let found = posts.find(p => p.post.id == data.post.id);
934   if (found) {
935     editPostRes(data, found);
936   }
937 }
938
939 export function editPostRes(data: PostView, post: PostView) {
940   if (post) {
941     post.post.url = data.post.url;
942     post.post.name = data.post.name;
943     post.post.nsfw = data.post.nsfw;
944     post.post.deleted = data.post.deleted;
945     post.post.removed = data.post.removed;
946     post.post.stickied = data.post.stickied;
947     post.post.body = data.post.body;
948     post.post.locked = data.post.locked;
949     post.saved = data.saved;
950   }
951 }
952
953 // TODO possible to make these generic?
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 updatePrivateMessageReportRes(
975   data: PrivateMessageReportView,
976   reports: PrivateMessageReportView[]
977 ) {
978   let found = reports.find(
979     c => c.private_message_report.id == data.private_message_report.id
980   );
981   if (found) {
982     found.private_message_report = data.private_message_report;
983   }
984 }
985
986 export function updateRegistrationApplicationRes(
987   data: RegistrationApplicationView,
988   applications: RegistrationApplicationView[]
989 ) {
990   let found = applications.find(
991     ra => ra.registration_application.id == data.registration_application.id
992   );
993   if (found) {
994     found.registration_application = data.registration_application;
995     found.admin = data.admin;
996     found.creator_local_user = data.creator_local_user;
997   }
998 }
999
1000 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
1001   let nodes: CommentNodeI[] = [];
1002   for (let comment of comments) {
1003     nodes.push({ comment_view: comment, children: [], depth: 0 });
1004   }
1005   return nodes;
1006 }
1007
1008 export function convertCommentSortType(sort: SortType): CommentSortType {
1009   if (
1010     sort == SortType.TopAll ||
1011     sort == SortType.TopDay ||
1012     sort == SortType.TopWeek ||
1013     sort == SortType.TopMonth ||
1014     sort == SortType.TopYear
1015   ) {
1016     return CommentSortType.Top;
1017   } else if (sort == SortType.New) {
1018     return CommentSortType.New;
1019   } else if (sort == SortType.Hot || sort == SortType.Active) {
1020     return CommentSortType.Hot;
1021   } else {
1022     return CommentSortType.Hot;
1023   }
1024 }
1025
1026 export function buildCommentsTree(
1027   comments: CommentView[],
1028   parentComment: boolean
1029 ): CommentNodeI[] {
1030   let map = new Map<number, CommentNodeI>();
1031   let depthOffset = !parentComment
1032     ? 0
1033     : getDepthFromComment(comments[0].comment);
1034
1035   for (let comment_view of comments) {
1036     let node: CommentNodeI = {
1037       comment_view: comment_view,
1038       children: [],
1039       depth: getDepthFromComment(comment_view.comment) - depthOffset,
1040     };
1041     map.set(comment_view.comment.id, { ...node });
1042   }
1043
1044   let tree: CommentNodeI[] = [];
1045
1046   // if its a parent comment fetch, then push the first comment to the top node.
1047   if (parentComment) {
1048     tree.push(map.get(comments[0].comment.id));
1049   }
1050
1051   for (let comment_view of comments) {
1052     let child = map.get(comment_view.comment.id);
1053     let parent_id = getCommentParentId(comment_view.comment);
1054     parent_id.match({
1055       some: parentId => {
1056         let parent = map.get(parentId);
1057         // Necessary because blocked comment might not exist
1058         if (parent) {
1059           parent.children.push(child);
1060         }
1061       },
1062       none: () => {
1063         if (!parentComment) {
1064           tree.push(child);
1065         }
1066       },
1067     });
1068   }
1069
1070   return tree;
1071 }
1072
1073 export function getCommentParentId(comment: CommentI): Option<number> {
1074   let split = comment.path.split(".");
1075   // remove the 0
1076   split.shift();
1077
1078   if (split.length > 1) {
1079     return Some(Number(split[split.length - 2]));
1080   } else {
1081     return None;
1082   }
1083 }
1084
1085 export function getDepthFromComment(comment: CommentI): number {
1086   return comment.path.split(".").length - 2;
1087 }
1088
1089 export function insertCommentIntoTree(
1090   tree: CommentNodeI[],
1091   cv: CommentView,
1092   parentComment: boolean
1093 ) {
1094   // Building a fake node to be used for later
1095   let node: CommentNodeI = {
1096     comment_view: cv,
1097     children: [],
1098     depth: 0,
1099   };
1100
1101   getCommentParentId(cv.comment).match({
1102     some: parentId => {
1103       let parentComment = searchCommentTree(tree, parentId);
1104       parentComment.match({
1105         some: pComment => {
1106           node.depth = pComment.depth + 1;
1107           pComment.children.unshift(node);
1108         },
1109         none: void 0,
1110       });
1111     },
1112     none: () => {
1113       if (!parentComment) {
1114         tree.unshift(node);
1115       }
1116     },
1117   });
1118 }
1119
1120 export function searchCommentTree(
1121   tree: CommentNodeI[],
1122   id: number
1123 ): Option<CommentNodeI> {
1124   for (let node of tree) {
1125     if (node.comment_view.comment.id === id) {
1126       return Some(node);
1127     }
1128
1129     for (const child of node.children) {
1130       let res = searchCommentTree([child], id);
1131
1132       if (res.isSome()) {
1133         return res;
1134       }
1135     }
1136   }
1137   return None;
1138 }
1139
1140 export const colorList: string[] = [
1141   hsl(0),
1142   hsl(50),
1143   hsl(100),
1144   hsl(150),
1145   hsl(200),
1146   hsl(250),
1147   hsl(300),
1148 ];
1149
1150 function hsl(num: number) {
1151   return `hsla(${num}, 35%, 50%, 1)`;
1152 }
1153
1154 export function hostname(url: string): string {
1155   let cUrl = new URL(url);
1156   return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1157 }
1158
1159 export function validTitle(title?: string): boolean {
1160   // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1161   if (!title || title.length < 3) return true;
1162
1163   const regex = new RegExp(/.*\S.*/, "g");
1164
1165   return regex.test(title);
1166 }
1167
1168 export function siteBannerCss(banner: string): string {
1169   return ` \
1170     background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1171     background-attachment: fixed; \
1172     background-position: top; \
1173     background-repeat: no-repeat; \
1174     background-size: 100% cover; \
1175
1176     width: 100%; \
1177     max-height: 100vh; \
1178     `;
1179 }
1180
1181 export function isBrowser() {
1182   return typeof window !== "undefined";
1183 }
1184
1185 export function setIsoData<Type1, Type2, Type3, Type4, Type5>(
1186   context: any,
1187   cls1?: ClassConstructor<Type1>,
1188   cls2?: ClassConstructor<Type2>,
1189   cls3?: ClassConstructor<Type3>,
1190   cls4?: ClassConstructor<Type4>,
1191   cls5?: ClassConstructor<Type5>
1192 ): IsoData {
1193   // If its the browser, you need to deserialize the data from the window
1194   if (isBrowser()) {
1195     let json = window.isoData;
1196     let routeData = json.routeData;
1197     let routeDataOut: any[] = [];
1198
1199     // Can't do array looping because of specific type constructor required
1200     if (routeData[0]) {
1201       routeDataOut[0] = convertWindowJson(cls1, routeData[0]);
1202     }
1203     if (routeData[1]) {
1204       routeDataOut[1] = convertWindowJson(cls2, routeData[1]);
1205     }
1206     if (routeData[2]) {
1207       routeDataOut[2] = convertWindowJson(cls3, routeData[2]);
1208     }
1209     if (routeData[3]) {
1210       routeDataOut[3] = convertWindowJson(cls4, routeData[3]);
1211     }
1212     if (routeData[4]) {
1213       routeDataOut[4] = convertWindowJson(cls5, routeData[4]);
1214     }
1215     let site_res = convertWindowJson(GetSiteResponse, json.site_res);
1216
1217     let isoData: IsoData = {
1218       path: json.path,
1219       site_res,
1220       routeData: routeDataOut,
1221     };
1222     return isoData;
1223   } else return context.router.staticContext;
1224 }
1225
1226 /**
1227  * Necessary since window ISOData can't store function types like Option
1228  */
1229 export function convertWindowJson<T>(cls: ClassConstructor<T>, data: any): T {
1230   return deserialize(cls, serialize(data));
1231 }
1232
1233 export function wsSubscribe(parseMessage: any): Subscription {
1234   if (isBrowser()) {
1235     return WebSocketService.Instance.subject
1236       .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1237       .subscribe(
1238         msg => parseMessage(msg),
1239         err => console.error(err),
1240         () => console.log("complete")
1241       );
1242   } else {
1243     return null;
1244   }
1245 }
1246
1247 moment.updateLocale("en", {
1248   relativeTime: {
1249     future: "in %s",
1250     past: "%s ago",
1251     s: "<1m",
1252     ss: "%ds",
1253     m: "1m",
1254     mm: "%dm",
1255     h: "1h",
1256     hh: "%dh",
1257     d: "1d",
1258     dd: "%dd",
1259     w: "1w",
1260     ww: "%dw",
1261     M: "1M",
1262     MM: "%dM",
1263     y: "1Y",
1264     yy: "%dY",
1265   },
1266 });
1267
1268 export function saveScrollPosition(context: any) {
1269   let path: string = context.router.route.location.pathname;
1270   let y = window.scrollY;
1271   sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1272 }
1273
1274 export function restoreScrollPosition(context: any) {
1275   let path: string = context.router.route.location.pathname;
1276   let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1277   window.scrollTo(0, y);
1278 }
1279
1280 export function showLocal(isoData: IsoData): boolean {
1281   return isoData.site_res.federated_instances
1282     .map(f => f.linked.length > 0)
1283     .unwrapOr(false);
1284 }
1285
1286 export interface ChoicesValue {
1287   value: string;
1288   label: string;
1289 }
1290
1291 export function communityToChoice(cv: CommunityView): ChoicesValue {
1292   let choice: ChoicesValue = {
1293     value: cv.community.id.toString(),
1294     label: communitySelectName(cv),
1295   };
1296   return choice;
1297 }
1298
1299 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1300   let choice: ChoicesValue = {
1301     value: pvs.person.id.toString(),
1302     label: personSelectName(pvs),
1303   };
1304   return choice;
1305 }
1306
1307 export async function fetchCommunities(q: string) {
1308   let form = new Search({
1309     q,
1310     type_: Some(SearchType.Communities),
1311     sort: Some(SortType.TopAll),
1312     listing_type: Some(ListingType.All),
1313     page: Some(1),
1314     limit: Some(fetchLimit),
1315     community_id: None,
1316     community_name: None,
1317     creator_id: None,
1318     auth: auth(false).ok(),
1319   });
1320   let client = new LemmyHttp(httpBase);
1321   return client.search(form);
1322 }
1323
1324 export async function fetchUsers(q: string) {
1325   let form = new Search({
1326     q,
1327     type_: Some(SearchType.Users),
1328     sort: Some(SortType.TopAll),
1329     listing_type: Some(ListingType.All),
1330     page: Some(1),
1331     limit: Some(fetchLimit),
1332     community_id: None,
1333     community_name: None,
1334     creator_id: None,
1335     auth: auth(false).ok(),
1336   });
1337   let client = new LemmyHttp(httpBase);
1338   return client.search(form);
1339 }
1340
1341 export const choicesConfig = {
1342   shouldSort: false,
1343   searchResultLimit: fetchLimit,
1344   classNames: {
1345     containerOuter: "choices custom-select px-0",
1346     containerInner:
1347       "choices__inner bg-secondary border-0 py-0 modlog-choices-font-size",
1348     input: "form-control",
1349     inputCloned: "choices__input--cloned",
1350     list: "choices__list",
1351     listItems: "choices__list--multiple",
1352     listSingle: "choices__list--single py-0",
1353     listDropdown: "choices__list--dropdown",
1354     item: "choices__item bg-secondary",
1355     itemSelectable: "choices__item--selectable",
1356     itemDisabled: "choices__item--disabled",
1357     itemChoice: "choices__item--choice",
1358     placeholder: "choices__placeholder",
1359     group: "choices__group",
1360     groupHeading: "choices__heading",
1361     button: "choices__button",
1362     activeState: "is-active",
1363     focusState: "is-focused",
1364     openState: "is-open",
1365     disabledState: "is-disabled",
1366     highlightedState: "text-info",
1367     selectedState: "text-info",
1368     flippedState: "is-flipped",
1369     loadingState: "is-loading",
1370     noResults: "has-no-results",
1371     noChoices: "has-no-choices",
1372   },
1373 };
1374
1375 export function communitySelectName(cv: CommunityView): string {
1376   return cv.community.local
1377     ? cv.community.title
1378     : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1379 }
1380
1381 export function personSelectName(pvs: PersonViewSafe): string {
1382   let pName = pvs.person.display_name.unwrapOr(pvs.person.name);
1383   return pvs.person.local ? pName : `${hostname(pvs.person.actor_id)}/${pName}`;
1384 }
1385
1386 export function initializeSite(site: GetSiteResponse) {
1387   UserService.Instance.myUserInfo = site.my_user;
1388   i18n.changeLanguage(getLanguages()[0]);
1389 }
1390
1391 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1392   maximumSignificantDigits: 3,
1393   //@ts-ignore
1394   notation: "compact",
1395   compactDisplay: "short",
1396 });
1397
1398 export function numToSI(value: number): string {
1399   return SHORTNUM_SI_FORMAT.format(value);
1400 }
1401
1402 export function isBanned(ps: PersonSafe): boolean {
1403   let expires = ps.ban_expires;
1404   // Add Z to convert from UTC date
1405   // TODO this check probably isn't necessary anymore
1406   if (expires.isSome()) {
1407     if (ps.banned && new Date(expires.unwrap() + "Z") > new Date()) {
1408       return true;
1409     } else {
1410       return false;
1411     }
1412   } else {
1413     return ps.banned;
1414   }
1415 }
1416
1417 export function pushNotNull(array: any[], new_item?: any) {
1418   if (new_item) {
1419     array.push(...new_item);
1420   }
1421 }
1422
1423 export function auth(throwErr = true): Result<string, string> {
1424   return UserService.Instance.auth(throwErr);
1425 }
1426
1427 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1428   return siteRes.site_view.local_site.enable_downvotes;
1429 }
1430
1431 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1432   return siteRes.site_view.local_site.enable_nsfw;
1433 }
1434
1435 export function postToCommentSortType(sort: SortType): CommentSortType {
1436   if ([SortType.Active, SortType.Hot].includes(sort)) {
1437     return CommentSortType.Hot;
1438   } else if ([SortType.New, SortType.NewComments].includes(sort)) {
1439     return CommentSortType.New;
1440   } else if (sort == SortType.Old) {
1441     return CommentSortType.Old;
1442   } else {
1443     return CommentSortType.Top;
1444   }
1445 }
1446
1447 export function arrayGet<T>(arr: Array<T>, index: number): Result<T, string> {
1448   let out = arr.at(index);
1449   if (out == undefined) {
1450     return Err("Index undefined");
1451   } else {
1452     return Ok(out);
1453   }
1454 }
1455
1456 export function myFirstDiscussionLanguageId(
1457   myUserInfo = UserService.Instance.myUserInfo
1458 ): Option<number> {
1459   return myUserInfo.andThen(mui =>
1460     arrayGet(mui.discussion_languages, 0)
1461       .ok()
1462       .map(i => i.id)
1463   );
1464 }
1465
1466 export function canCreateCommunity(
1467   siteRes: GetSiteResponse,
1468   myUserInfo = UserService.Instance.myUserInfo
1469 ): boolean {
1470   let adminOnly = siteRes.site_view.local_site.community_creation_admin_only;
1471   return !adminOnly || amAdmin(myUserInfo);
1472 }
1473
1474 export function isPostBlocked(
1475   pv: PostView,
1476   myUserInfo = UserService.Instance.myUserInfo
1477 ): boolean {
1478   return myUserInfo
1479     .map(
1480       mui =>
1481         mui.community_blocks
1482           .map(c => c.community.id)
1483           .includes(pv.community.id) ||
1484         mui.person_blocks.map(p => p.target.id).includes(pv.creator.id)
1485     )
1486     .unwrapOr(false);
1487 }
1488
1489 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1490 export function nsfwCheck(
1491   pv: PostView,
1492   myUserInfo = UserService.Instance.myUserInfo
1493 ): boolean {
1494   let nsfw = pv.post.nsfw || pv.community.nsfw;
1495   return (
1496     !nsfw ||
1497     (nsfw &&
1498       myUserInfo
1499         .map(m => m.local_user_view.local_user.show_nsfw)
1500         .unwrapOr(false))
1501   );
1502 }