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