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