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