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