]> Untitled Git - lemmy-ui.git/blob - src/shared/utils.ts
Dont render images in tippy. Fixes #776 (#864)
[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.stickied = data.post.stickied;
972     post.post.body = data.post.body;
973     post.post.locked = data.post.locked;
974     post.saved = data.saved;
975   }
976 }
977
978 // TODO possible to make these generic?
979 export function updatePostReportRes(
980   data: PostReportView,
981   reports: PostReportView[]
982 ) {
983   let found = reports.find(p => p.post_report.id == data.post_report.id);
984   if (found) {
985     found.post_report = data.post_report;
986   }
987 }
988
989 export function updateCommentReportRes(
990   data: CommentReportView,
991   reports: CommentReportView[]
992 ) {
993   let found = reports.find(c => c.comment_report.id == data.comment_report.id);
994   if (found) {
995     found.comment_report = data.comment_report;
996   }
997 }
998
999 export function updatePrivateMessageReportRes(
1000   data: PrivateMessageReportView,
1001   reports: PrivateMessageReportView[]
1002 ) {
1003   let found = reports.find(
1004     c => c.private_message_report.id == data.private_message_report.id
1005   );
1006   if (found) {
1007     found.private_message_report = data.private_message_report;
1008   }
1009 }
1010
1011 export function updateRegistrationApplicationRes(
1012   data: RegistrationApplicationView,
1013   applications: RegistrationApplicationView[]
1014 ) {
1015   let found = applications.find(
1016     ra => ra.registration_application.id == data.registration_application.id
1017   );
1018   if (found) {
1019     found.registration_application = data.registration_application;
1020     found.admin = data.admin;
1021     found.creator_local_user = data.creator_local_user;
1022   }
1023 }
1024
1025 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
1026   let nodes: CommentNodeI[] = [];
1027   for (let comment of comments) {
1028     nodes.push({ comment_view: comment, children: [], depth: 0 });
1029   }
1030   return nodes;
1031 }
1032
1033 export function convertCommentSortType(sort: SortType): CommentSortType {
1034   if (
1035     sort == SortType.TopAll ||
1036     sort == SortType.TopDay ||
1037     sort == SortType.TopWeek ||
1038     sort == SortType.TopMonth ||
1039     sort == SortType.TopYear
1040   ) {
1041     return CommentSortType.Top;
1042   } else if (sort == SortType.New) {
1043     return CommentSortType.New;
1044   } else if (sort == SortType.Hot || sort == SortType.Active) {
1045     return CommentSortType.Hot;
1046   } else {
1047     return CommentSortType.Hot;
1048   }
1049 }
1050
1051 export function buildCommentsTree(
1052   comments: CommentView[],
1053   parentComment: boolean
1054 ): CommentNodeI[] {
1055   let map = new Map<number, CommentNodeI>();
1056   let depthOffset = !parentComment
1057     ? 0
1058     : getDepthFromComment(comments[0].comment);
1059
1060   for (let comment_view of comments) {
1061     let node: CommentNodeI = {
1062       comment_view: comment_view,
1063       children: [],
1064       depth: getDepthFromComment(comment_view.comment) - depthOffset,
1065     };
1066     map.set(comment_view.comment.id, { ...node });
1067   }
1068
1069   let tree: CommentNodeI[] = [];
1070
1071   // if its a parent comment fetch, then push the first comment to the top node.
1072   if (parentComment) {
1073     tree.push(map.get(comments[0].comment.id));
1074   }
1075
1076   for (let comment_view of comments) {
1077     let child = map.get(comment_view.comment.id);
1078     let parent_id = getCommentParentId(comment_view.comment);
1079     parent_id.match({
1080       some: parentId => {
1081         let parent = map.get(parentId);
1082         // Necessary because blocked comment might not exist
1083         if (parent) {
1084           parent.children.push(child);
1085         }
1086       },
1087       none: () => {
1088         if (!parentComment) {
1089           tree.push(child);
1090         }
1091       },
1092     });
1093   }
1094
1095   return tree;
1096 }
1097
1098 export function getCommentParentId(comment: CommentI): Option<number> {
1099   let split = comment.path.split(".");
1100   // remove the 0
1101   split.shift();
1102
1103   if (split.length > 1) {
1104     return Some(Number(split[split.length - 2]));
1105   } else {
1106     return None;
1107   }
1108 }
1109
1110 export function getDepthFromComment(comment: CommentI): number {
1111   return comment.path.split(".").length - 2;
1112 }
1113
1114 export function insertCommentIntoTree(
1115   tree: CommentNodeI[],
1116   cv: CommentView,
1117   parentComment: boolean
1118 ) {
1119   // Building a fake node to be used for later
1120   let node: CommentNodeI = {
1121     comment_view: cv,
1122     children: [],
1123     depth: 0,
1124   };
1125
1126   getCommentParentId(cv.comment).match({
1127     some: parentId => {
1128       let parentComment = searchCommentTree(tree, parentId);
1129       parentComment.match({
1130         some: pComment => {
1131           node.depth = pComment.depth + 1;
1132           pComment.children.unshift(node);
1133         },
1134         none: void 0,
1135       });
1136     },
1137     none: () => {
1138       if (!parentComment) {
1139         tree.unshift(node);
1140       }
1141     },
1142   });
1143 }
1144
1145 export function searchCommentTree(
1146   tree: CommentNodeI[],
1147   id: number
1148 ): Option<CommentNodeI> {
1149   for (let node of tree) {
1150     if (node.comment_view.comment.id === id) {
1151       return Some(node);
1152     }
1153
1154     for (const child of node.children) {
1155       let res = searchCommentTree([child], id);
1156
1157       if (res.isSome()) {
1158         return res;
1159       }
1160     }
1161   }
1162   return None;
1163 }
1164
1165 export const colorList: string[] = [
1166   hsl(0),
1167   hsl(50),
1168   hsl(100),
1169   hsl(150),
1170   hsl(200),
1171   hsl(250),
1172   hsl(300),
1173 ];
1174
1175 function hsl(num: number) {
1176   return `hsla(${num}, 35%, 50%, 1)`;
1177 }
1178
1179 export function hostname(url: string): string {
1180   let cUrl = new URL(url);
1181   return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1182 }
1183
1184 export function validTitle(title?: string): boolean {
1185   // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1186   if (!title || title.length < 3) return true;
1187
1188   const regex = new RegExp(/.*\S.*/, "g");
1189
1190   return regex.test(title);
1191 }
1192
1193 export function siteBannerCss(banner: string): string {
1194   return ` \
1195     background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1196     background-attachment: fixed; \
1197     background-position: top; \
1198     background-repeat: no-repeat; \
1199     background-size: 100% cover; \
1200
1201     width: 100%; \
1202     max-height: 100vh; \
1203     `;
1204 }
1205
1206 export function isBrowser() {
1207   return typeof window !== "undefined";
1208 }
1209
1210 export function setIsoData<Type1, Type2, Type3, Type4, Type5>(
1211   context: any,
1212   cls1?: ClassConstructor<Type1>,
1213   cls2?: ClassConstructor<Type2>,
1214   cls3?: ClassConstructor<Type3>,
1215   cls4?: ClassConstructor<Type4>,
1216   cls5?: ClassConstructor<Type5>
1217 ): IsoData {
1218   // If its the browser, you need to deserialize the data from the window
1219   if (isBrowser()) {
1220     let json = window.isoData;
1221     let routeData = json.routeData;
1222     let routeDataOut: any[] = [];
1223
1224     // Can't do array looping because of specific type constructor required
1225     if (routeData[0]) {
1226       routeDataOut[0] = convertWindowJson(cls1, routeData[0]);
1227     }
1228     if (routeData[1]) {
1229       routeDataOut[1] = convertWindowJson(cls2, routeData[1]);
1230     }
1231     if (routeData[2]) {
1232       routeDataOut[2] = convertWindowJson(cls3, routeData[2]);
1233     }
1234     if (routeData[3]) {
1235       routeDataOut[3] = convertWindowJson(cls4, routeData[3]);
1236     }
1237     if (routeData[4]) {
1238       routeDataOut[4] = convertWindowJson(cls5, routeData[4]);
1239     }
1240     let site_res = convertWindowJson(GetSiteResponse, json.site_res);
1241
1242     let isoData: IsoData = {
1243       path: json.path,
1244       site_res,
1245       routeData: routeDataOut,
1246     };
1247     return isoData;
1248   } else return context.router.staticContext;
1249 }
1250
1251 /**
1252  * Necessary since window ISOData can't store function types like Option
1253  */
1254 export function convertWindowJson<T>(cls: ClassConstructor<T>, data: any): T {
1255   return deserialize(cls, serialize(data));
1256 }
1257
1258 export function wsSubscribe(parseMessage: any): Subscription {
1259   if (isBrowser()) {
1260     return WebSocketService.Instance.subject
1261       .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1262       .subscribe(
1263         msg => parseMessage(msg),
1264         err => console.error(err),
1265         () => console.log("complete")
1266       );
1267   } else {
1268     return null;
1269   }
1270 }
1271
1272 moment.updateLocale("en", {
1273   relativeTime: {
1274     future: "in %s",
1275     past: "%s ago",
1276     s: "<1m",
1277     ss: "%ds",
1278     m: "1m",
1279     mm: "%dm",
1280     h: "1h",
1281     hh: "%dh",
1282     d: "1d",
1283     dd: "%dd",
1284     w: "1w",
1285     ww: "%dw",
1286     M: "1M",
1287     MM: "%dM",
1288     y: "1Y",
1289     yy: "%dY",
1290   },
1291 });
1292
1293 export function saveScrollPosition(context: any) {
1294   let path: string = context.router.route.location.pathname;
1295   let y = window.scrollY;
1296   sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1297 }
1298
1299 export function restoreScrollPosition(context: any) {
1300   let path: string = context.router.route.location.pathname;
1301   let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1302   window.scrollTo(0, y);
1303 }
1304
1305 export function showLocal(isoData: IsoData): boolean {
1306   return isoData.site_res.federated_instances
1307     .map(f => f.linked.length > 0)
1308     .unwrapOr(false);
1309 }
1310
1311 export interface ChoicesValue {
1312   value: string;
1313   label: string;
1314 }
1315
1316 export function communityToChoice(cv: CommunityView): ChoicesValue {
1317   let choice: ChoicesValue = {
1318     value: cv.community.id.toString(),
1319     label: communitySelectName(cv),
1320   };
1321   return choice;
1322 }
1323
1324 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1325   let choice: ChoicesValue = {
1326     value: pvs.person.id.toString(),
1327     label: personSelectName(pvs),
1328   };
1329   return choice;
1330 }
1331
1332 export async function fetchCommunities(q: string) {
1333   let form = new Search({
1334     q,
1335     type_: Some(SearchType.Communities),
1336     sort: Some(SortType.TopAll),
1337     listing_type: Some(ListingType.All),
1338     page: Some(1),
1339     limit: Some(fetchLimit),
1340     community_id: None,
1341     community_name: None,
1342     creator_id: None,
1343     auth: auth(false).ok(),
1344   });
1345   let client = new LemmyHttp(httpBase);
1346   return client.search(form);
1347 }
1348
1349 export async function fetchUsers(q: string) {
1350   let form = new Search({
1351     q,
1352     type_: Some(SearchType.Users),
1353     sort: Some(SortType.TopAll),
1354     listing_type: Some(ListingType.All),
1355     page: Some(1),
1356     limit: Some(fetchLimit),
1357     community_id: None,
1358     community_name: None,
1359     creator_id: None,
1360     auth: auth(false).ok(),
1361   });
1362   let client = new LemmyHttp(httpBase);
1363   return client.search(form);
1364 }
1365
1366 export const choicesConfig = {
1367   shouldSort: false,
1368   searchResultLimit: fetchLimit,
1369   classNames: {
1370     containerOuter: "choices custom-select px-0",
1371     containerInner:
1372       "choices__inner bg-secondary border-0 py-0 modlog-choices-font-size",
1373     input: "form-control",
1374     inputCloned: "choices__input--cloned",
1375     list: "choices__list",
1376     listItems: "choices__list--multiple",
1377     listSingle: "choices__list--single py-0",
1378     listDropdown: "choices__list--dropdown",
1379     item: "choices__item bg-secondary",
1380     itemSelectable: "choices__item--selectable",
1381     itemDisabled: "choices__item--disabled",
1382     itemChoice: "choices__item--choice",
1383     placeholder: "choices__placeholder",
1384     group: "choices__group",
1385     groupHeading: "choices__heading",
1386     button: "choices__button",
1387     activeState: "is-active",
1388     focusState: "is-focused",
1389     openState: "is-open",
1390     disabledState: "is-disabled",
1391     highlightedState: "text-info",
1392     selectedState: "text-info",
1393     flippedState: "is-flipped",
1394     loadingState: "is-loading",
1395     noResults: "has-no-results",
1396     noChoices: "has-no-choices",
1397   },
1398 };
1399
1400 export function communitySelectName(cv: CommunityView): string {
1401   return cv.community.local
1402     ? cv.community.title
1403     : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1404 }
1405
1406 export function personSelectName(pvs: PersonViewSafe): string {
1407   let pName = pvs.person.display_name.unwrapOr(pvs.person.name);
1408   return pvs.person.local ? pName : `${hostname(pvs.person.actor_id)}/${pName}`;
1409 }
1410
1411 export function initializeSite(site: GetSiteResponse) {
1412   UserService.Instance.myUserInfo = site.my_user;
1413   i18n.changeLanguage(getLanguages()[0]);
1414 }
1415
1416 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1417   maximumSignificantDigits: 3,
1418   //@ts-ignore
1419   notation: "compact",
1420   compactDisplay: "short",
1421 });
1422
1423 export function numToSI(value: number): string {
1424   return SHORTNUM_SI_FORMAT.format(value);
1425 }
1426
1427 export function isBanned(ps: PersonSafe): boolean {
1428   let expires = ps.ban_expires;
1429   // Add Z to convert from UTC date
1430   // TODO this check probably isn't necessary anymore
1431   if (expires.isSome()) {
1432     if (ps.banned && new Date(expires.unwrap() + "Z") > new Date()) {
1433       return true;
1434     } else {
1435       return false;
1436     }
1437   } else {
1438     return ps.banned;
1439   }
1440 }
1441
1442 export function pushNotNull(array: any[], new_item?: any) {
1443   if (new_item) {
1444     array.push(...new_item);
1445   }
1446 }
1447
1448 export function auth(throwErr = true): Result<string, string> {
1449   return UserService.Instance.auth(throwErr);
1450 }
1451
1452 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1453   return siteRes.site_view.local_site.enable_downvotes;
1454 }
1455
1456 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1457   return siteRes.site_view.local_site.enable_nsfw;
1458 }
1459
1460 export function postToCommentSortType(sort: SortType): CommentSortType {
1461   if ([SortType.Active, SortType.Hot].includes(sort)) {
1462     return CommentSortType.Hot;
1463   } else if ([SortType.New, SortType.NewComments].includes(sort)) {
1464     return CommentSortType.New;
1465   } else if (sort == SortType.Old) {
1466     return CommentSortType.Old;
1467   } else {
1468     return CommentSortType.Top;
1469   }
1470 }
1471
1472 export function arrayGet<T>(arr: Array<T>, index: number): Result<T, string> {
1473   let out = arr.at(index);
1474   if (out == undefined) {
1475     return Err("Index undefined");
1476   } else {
1477     return Ok(out);
1478   }
1479 }
1480
1481 export function myFirstDiscussionLanguageId(
1482   myUserInfo = UserService.Instance.myUserInfo
1483 ): Option<number> {
1484   return myUserInfo.andThen(mui =>
1485     arrayGet(mui.discussion_languages, 0)
1486       .ok()
1487       .map(i => i.id)
1488   );
1489 }
1490
1491 export function canCreateCommunity(
1492   siteRes: GetSiteResponse,
1493   myUserInfo = UserService.Instance.myUserInfo
1494 ): boolean {
1495   let adminOnly = siteRes.site_view.local_site.community_creation_admin_only;
1496   return !adminOnly || amAdmin(myUserInfo);
1497 }
1498
1499 export function isPostBlocked(
1500   pv: PostView,
1501   myUserInfo = UserService.Instance.myUserInfo
1502 ): boolean {
1503   return myUserInfo
1504     .map(
1505       mui =>
1506         mui.community_blocks
1507           .map(c => c.community.id)
1508           .includes(pv.community.id) ||
1509         mui.person_blocks.map(p => p.target.id).includes(pv.creator.id)
1510     )
1511     .unwrapOr(false);
1512 }
1513
1514 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1515 export function nsfwCheck(
1516   pv: PostView,
1517   myUserInfo = UserService.Instance.myUserInfo
1518 ): boolean {
1519   let nsfw = pv.post.nsfw || pv.community.nsfw;
1520   return (
1521     !nsfw ||
1522     (nsfw &&
1523       myUserInfo
1524         .map(m => m.local_user_view.local_user.show_nsfw)
1525         .unwrapOr(false))
1526   );
1527 }