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