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