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