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