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