]> Untitled Git - lemmy-ui.git/blob - src/shared/utils.ts
Merge branch 'main' into fix/1039
[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   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     const 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   const 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   const 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   const url = new URL(actorId);
335   return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
336 }
337
338 export function validEmail(email: string) {
339   const 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   const form: GetSiteMetadata = { url };
350   const 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   const myLang = myUserInfo?.local_user_view.local_user.interface_language;
408   const 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   const langs = languages ? languages.map(l => l.code) : ["en"];
420
421   // NOTE, mobile browsers seem to be missing this list, so append en
422   const 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   const themeList = await fetchThemeList();
445
446   // Unload all the other themes
447   for (var i = 0; i < themeList.length; i++) {
448     const 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   const 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     const htmlBody = info.body ? md.render(info.body) : "";
572     const backgroundColor = `var(--light)`;
573
574     const 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   const 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   const 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   const 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           const shortName = `:${item.original.key}:`;
653           return `${item.original.val} ${shortName}`;
654         },
655         selectTemplate: (item: any) => {
656           const 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           const 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           const 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   const groupedEmojis = groupBy(
718     custom_emoji_views,
719     x => x.custom_emoji.category
720   );
721   for (const [category, emojis] of Object.entries(groupedEmojis)) {
722     customEmojis.push({
723       id: category,
724       name: category,
725       emojis: emojis.map(emoji => ({
726         id: emoji.custom_emoji.shortcode,
727         name: emoji.custom_emoji.shortcode,
728         keywords: emoji.keywords.map(x => x.keyword),
729         skins: [{ src: emoji.custom_emoji.image_url }],
730       })),
731     });
732   }
733   customEmojisLookup = new Map(
734     custom_emoji_views.map(view => [view.custom_emoji.shortcode, view])
735   );
736 }
737
738 export function updateEmojiDataModel(custom_emoji_view: CustomEmojiView) {
739   const emoji: EmojiMartCustomEmoji = {
740     id: custom_emoji_view.custom_emoji.shortcode,
741     name: custom_emoji_view.custom_emoji.shortcode,
742     keywords: custom_emoji_view.keywords.map(x => x.keyword),
743     skins: [{ src: custom_emoji_view.custom_emoji.image_url }],
744   };
745   const categoryIndex = customEmojis.findIndex(
746     x => x.id == custom_emoji_view.custom_emoji.category
747   );
748   if (categoryIndex == -1) {
749     customEmojis.push({
750       id: custom_emoji_view.custom_emoji.category,
751       name: custom_emoji_view.custom_emoji.category,
752       emojis: [emoji],
753     });
754   } else {
755     const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
756       x => x.id == custom_emoji_view.custom_emoji.shortcode
757     );
758     if (emojiIndex == -1) {
759       customEmojis[categoryIndex].emojis.push(emoji);
760     } else {
761       customEmojis[categoryIndex].emojis[emojiIndex] = emoji;
762     }
763   }
764   customEmojisLookup.set(
765     custom_emoji_view.custom_emoji.shortcode,
766     custom_emoji_view
767   );
768 }
769
770 export function removeFromEmojiDataModel(id: number) {
771   let view: CustomEmojiView | undefined;
772   for (const item of customEmojisLookup.values()) {
773     if (item.custom_emoji.id === id) {
774       view = item;
775       break;
776     }
777   }
778   if (!view) return;
779   const categoryIndex = customEmojis.findIndex(
780     x => x.id == view?.custom_emoji.category
781   );
782   const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
783     x => x.id == view?.custom_emoji.shortcode
784   );
785   customEmojis[categoryIndex].emojis = customEmojis[
786     categoryIndex
787   ].emojis.splice(emojiIndex, 1);
788
789   customEmojisLookup.delete(view?.custom_emoji.shortcode);
790 }
791
792 function setupMarkdown() {
793   const markdownItConfig: MarkdownIt.Options = {
794     html: false,
795     linkify: true,
796     typographer: true,
797   };
798
799   const emojiDefs = Array.from(customEmojisLookup.entries()).reduce(
800     (main, [key, value]) => ({ ...main, [key]: value }),
801     {}
802   );
803   md = new MarkdownIt(markdownItConfig)
804     .use(markdown_it_sub)
805     .use(markdown_it_sup)
806     .use(markdown_it_footnote)
807     .use(markdown_it_html5_embed, html5EmbedConfig)
808     .use(markdown_it_container, "spoiler", spoilerConfig)
809     .use(markdown_it_emoji, {
810       defs: emojiDefs,
811     });
812
813   mdNoImages = new MarkdownIt(markdownItConfig)
814     .use(markdown_it_sub)
815     .use(markdown_it_sup)
816     .use(markdown_it_footnote)
817     .use(markdown_it_html5_embed, html5EmbedConfig)
818     .use(markdown_it_container, "spoiler", spoilerConfig)
819     .use(markdown_it_emoji, {
820       defs: emojiDefs,
821     })
822     .disable("image");
823   var defaultRenderer = md.renderer.rules.image;
824   md.renderer.rules.image = function (
825     tokens: Token[],
826     idx: number,
827     options: MarkdownIt.Options,
828     env: any,
829     self: Renderer
830   ) {
831     //Provide custom renderer for our emojis to allow us to add a css class and force size dimensions on them.
832     const item = tokens[idx] as any;
833     const title = item.attrs.length >= 3 ? item.attrs[2][1] : "";
834     const src: string = item.attrs[0][1];
835     const isCustomEmoji = customEmojisLookup.get(title) != undefined;
836     if (!isCustomEmoji) {
837       return defaultRenderer?.(tokens, idx, options, env, self) ?? "";
838     }
839     const alt_text = item.content;
840     return `<img class="icon icon-emoji" src="${src}" title="${title}" alt="${alt_text}"/>`;
841   };
842 }
843
844 export function getEmojiMart(
845   onEmojiSelect: (e: any) => void,
846   customPickerOptions: any = {}
847 ) {
848   const pickerOptions = {
849     ...customPickerOptions,
850     onEmojiSelect: onEmojiSelect,
851     custom: customEmojis,
852   };
853   return new Picker(pickerOptions);
854 }
855
856 var tippyInstance: any;
857 if (isBrowser()) {
858   tippyInstance = tippy("[data-tippy-content]");
859 }
860
861 export function setupTippy() {
862   if (isBrowser()) {
863     tippyInstance.forEach((e: any) => e.destroy());
864     tippyInstance = tippy("[data-tippy-content]", {
865       delay: [500, 0],
866       // Display on "long press"
867       touch: ["hold", 500],
868     });
869   }
870 }
871
872 interface PersonTribute {
873   key: string;
874   view: PersonView;
875 }
876
877 async function personSearch(text: string): Promise<PersonTribute[]> {
878   const users = (await fetchUsers(text)).users;
879   const persons: PersonTribute[] = users.map(pv => {
880     const tribute: PersonTribute = {
881       key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
882       view: pv,
883     };
884     return tribute;
885   });
886   return persons;
887 }
888
889 interface CommunityTribute {
890   key: string;
891   view: CommunityView;
892 }
893
894 async function communitySearch(text: string): Promise<CommunityTribute[]> {
895   const comms = (await fetchCommunities(text)).communities;
896   const communities: CommunityTribute[] = comms.map(cv => {
897     const tribute: CommunityTribute = {
898       key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
899       view: cv,
900     };
901     return tribute;
902   });
903   return communities;
904 }
905
906 export function getRecipientIdFromProps(props: any): number {
907   return props.match.params.recipient_id
908     ? Number(props.match.params.recipient_id)
909     : 1;
910 }
911
912 export function getIdFromProps(props: any): number | undefined {
913   const id = props.match.params.post_id;
914   return id ? Number(id) : undefined;
915 }
916
917 export function getCommentIdFromProps(props: any): number | undefined {
918   const id = props.match.params.comment_id;
919   return id ? Number(id) : undefined;
920 }
921
922 export function editCommentRes(data: CommentView, comments?: CommentView[]) {
923   const found = comments?.find(c => c.comment.id == data.comment.id);
924   if (found) {
925     found.comment.content = data.comment.content;
926     found.comment.distinguished = data.comment.distinguished;
927     found.comment.updated = data.comment.updated;
928     found.comment.removed = data.comment.removed;
929     found.comment.deleted = data.comment.deleted;
930     found.counts.upvotes = data.counts.upvotes;
931     found.counts.downvotes = data.counts.downvotes;
932     found.counts.score = data.counts.score;
933   }
934 }
935
936 export function saveCommentRes(data: CommentView, comments?: CommentView[]) {
937   const found = comments?.find(c => c.comment.id == data.comment.id);
938   if (found) {
939     found.saved = data.saved;
940   }
941 }
942
943 export function updatePersonBlock(
944   data: BlockPersonResponse,
945   myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
946 ) {
947   const mui = myUserInfo;
948   if (mui) {
949     if (data.blocked) {
950       mui.person_blocks.push({
951         person: mui.local_user_view.person,
952         target: data.person_view.person,
953       });
954       toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
955     } else {
956       mui.person_blocks = mui.person_blocks.filter(
957         i => i.target.id != data.person_view.person.id
958       );
959       toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
960     }
961   }
962 }
963
964 export function updateCommunityBlock(
965   data: BlockCommunityResponse,
966   myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
967 ) {
968   const mui = myUserInfo;
969   if (mui) {
970     if (data.blocked) {
971       mui.community_blocks.push({
972         person: mui.local_user_view.person,
973         community: data.community_view.community,
974       });
975       toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
976     } else {
977       mui.community_blocks = mui.community_blocks.filter(
978         i => i.community.id != data.community_view.community.id
979       );
980       toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
981     }
982   }
983 }
984
985 export function createCommentLikeRes(
986   data: CommentView,
987   comments?: CommentView[]
988 ) {
989   const found = comments?.find(c => c.comment.id === data.comment.id);
990   if (found) {
991     found.counts.score = data.counts.score;
992     found.counts.upvotes = data.counts.upvotes;
993     found.counts.downvotes = data.counts.downvotes;
994     if (data.my_vote !== null) {
995       found.my_vote = data.my_vote;
996     }
997   }
998 }
999
1000 export function createPostLikeFindRes(data: PostView, posts?: PostView[]) {
1001   const found = posts?.find(p => p.post.id == data.post.id);
1002   if (found) {
1003     createPostLikeRes(data, found);
1004   }
1005 }
1006
1007 export function createPostLikeRes(data: PostView, post_view?: PostView) {
1008   if (post_view) {
1009     post_view.counts.score = data.counts.score;
1010     post_view.counts.upvotes = data.counts.upvotes;
1011     post_view.counts.downvotes = data.counts.downvotes;
1012     if (data.my_vote !== null) {
1013       post_view.my_vote = data.my_vote;
1014     }
1015   }
1016 }
1017
1018 export function editPostFindRes(data: PostView, posts?: PostView[]) {
1019   const found = posts?.find(p => p.post.id == data.post.id);
1020   if (found) {
1021     editPostRes(data, found);
1022   }
1023 }
1024
1025 export function editPostRes(data: PostView, post: PostView) {
1026   if (post) {
1027     post.post.url = data.post.url;
1028     post.post.name = data.post.name;
1029     post.post.nsfw = data.post.nsfw;
1030     post.post.deleted = data.post.deleted;
1031     post.post.removed = data.post.removed;
1032     post.post.featured_community = data.post.featured_community;
1033     post.post.featured_local = data.post.featured_local;
1034     post.post.body = data.post.body;
1035     post.post.locked = data.post.locked;
1036     post.saved = data.saved;
1037   }
1038 }
1039
1040 // TODO possible to make these generic?
1041 export function updatePostReportRes(
1042   data: PostReportView,
1043   reports?: PostReportView[]
1044 ) {
1045   const found = reports?.find(p => p.post_report.id == data.post_report.id);
1046   if (found) {
1047     found.post_report = data.post_report;
1048   }
1049 }
1050
1051 export function updateCommentReportRes(
1052   data: CommentReportView,
1053   reports?: CommentReportView[]
1054 ) {
1055   const found = reports?.find(
1056     c => c.comment_report.id == data.comment_report.id
1057   );
1058   if (found) {
1059     found.comment_report = data.comment_report;
1060   }
1061 }
1062
1063 export function updatePrivateMessageReportRes(
1064   data: PrivateMessageReportView,
1065   reports?: PrivateMessageReportView[]
1066 ) {
1067   const found = reports?.find(
1068     c => c.private_message_report.id == data.private_message_report.id
1069   );
1070   if (found) {
1071     found.private_message_report = data.private_message_report;
1072   }
1073 }
1074
1075 export function updateRegistrationApplicationRes(
1076   data: RegistrationApplicationView,
1077   applications?: RegistrationApplicationView[]
1078 ) {
1079   const found = applications?.find(
1080     ra => ra.registration_application.id == data.registration_application.id
1081   );
1082   if (found) {
1083     found.registration_application = data.registration_application;
1084     found.admin = data.admin;
1085     found.creator_local_user = data.creator_local_user;
1086   }
1087 }
1088
1089 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
1090   const nodes: CommentNodeI[] = [];
1091   for (const comment of comments) {
1092     nodes.push({ comment_view: comment, children: [], depth: 0 });
1093   }
1094   return nodes;
1095 }
1096
1097 export function convertCommentSortType(sort: SortType): CommentSortType {
1098   if (
1099     sort == "TopAll" ||
1100     sort == "TopDay" ||
1101     sort == "TopWeek" ||
1102     sort == "TopMonth" ||
1103     sort == "TopYear"
1104   ) {
1105     return "Top";
1106   } else if (sort == "New") {
1107     return "New";
1108   } else if (sort == "Hot" || sort == "Active") {
1109     return "Hot";
1110   } else {
1111     return "Hot";
1112   }
1113 }
1114
1115 export function buildCommentsTree(
1116   comments: CommentView[],
1117   parentComment: boolean
1118 ): CommentNodeI[] {
1119   const map = new Map<number, CommentNodeI>();
1120   const depthOffset = !parentComment
1121     ? 0
1122     : getDepthFromComment(comments[0].comment) ?? 0;
1123
1124   for (const comment_view of comments) {
1125     const depthI = getDepthFromComment(comment_view.comment) ?? 0;
1126     const depth = depthI ? depthI - depthOffset : 0;
1127     const node: CommentNodeI = {
1128       comment_view,
1129       children: [],
1130       depth,
1131     };
1132     map.set(comment_view.comment.id, { ...node });
1133   }
1134
1135   const tree: CommentNodeI[] = [];
1136
1137   // if its a parent comment fetch, then push the first comment to the top node.
1138   if (parentComment) {
1139     const cNode = map.get(comments[0].comment.id);
1140     if (cNode) {
1141       tree.push(cNode);
1142     }
1143   }
1144
1145   for (const comment_view of comments) {
1146     const child = map.get(comment_view.comment.id);
1147     if (child) {
1148       const parent_id = getCommentParentId(comment_view.comment);
1149       if (parent_id) {
1150         const parent = map.get(parent_id);
1151         // Necessary because blocked comment might not exist
1152         if (parent) {
1153           parent.children.push(child);
1154         }
1155       } else {
1156         if (!parentComment) {
1157           tree.push(child);
1158         }
1159       }
1160     }
1161   }
1162
1163   return tree;
1164 }
1165
1166 export function getCommentParentId(comment?: CommentI): number | undefined {
1167   const split = comment?.path.split(".");
1168   // remove the 0
1169   split?.shift();
1170
1171   return split && split.length > 1
1172     ? Number(split.at(split.length - 2))
1173     : undefined;
1174 }
1175
1176 export function getDepthFromComment(comment?: CommentI): number | undefined {
1177   const len = comment?.path.split(".").length;
1178   return len ? len - 2 : undefined;
1179 }
1180
1181 export function insertCommentIntoTree(
1182   tree: CommentNodeI[],
1183   cv: CommentView,
1184   parentComment: boolean
1185 ) {
1186   // Building a fake node to be used for later
1187   const node: CommentNodeI = {
1188     comment_view: cv,
1189     children: [],
1190     depth: 0,
1191   };
1192
1193   const parentId = getCommentParentId(cv.comment);
1194   if (parentId) {
1195     const parent_comment = searchCommentTree(tree, parentId);
1196     if (parent_comment) {
1197       node.depth = parent_comment.depth + 1;
1198       parent_comment.children.unshift(node);
1199     }
1200   } else if (!parentComment) {
1201     tree.unshift(node);
1202   }
1203 }
1204
1205 export function searchCommentTree(
1206   tree: CommentNodeI[],
1207   id: number
1208 ): CommentNodeI | undefined {
1209   for (const node of tree) {
1210     if (node.comment_view.comment.id === id) {
1211       return node;
1212     }
1213
1214     for (const child of node.children) {
1215       const res = searchCommentTree([child], id);
1216
1217       if (res) {
1218         return res;
1219       }
1220     }
1221   }
1222   return undefined;
1223 }
1224
1225 export const colorList: string[] = [
1226   hsl(0),
1227   hsl(50),
1228   hsl(100),
1229   hsl(150),
1230   hsl(200),
1231   hsl(250),
1232   hsl(300),
1233 ];
1234
1235 function hsl(num: number) {
1236   return `hsla(${num}, 35%, 50%, 1)`;
1237 }
1238
1239 export function hostname(url: string): string {
1240   const cUrl = new URL(url);
1241   return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1242 }
1243
1244 export function validTitle(title?: string): boolean {
1245   // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1246   if (!title || title.length < 3) return true;
1247
1248   const regex = new RegExp(/.*\S.*/, "g");
1249
1250   return regex.test(title);
1251 }
1252
1253 export function siteBannerCss(banner: string): string {
1254   return ` \
1255     background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1256     background-attachment: fixed; \
1257     background-position: top; \
1258     background-repeat: no-repeat; \
1259     background-size: 100% cover; \
1260
1261     width: 100%; \
1262     max-height: 100vh; \
1263     `;
1264 }
1265
1266 export function isBrowser() {
1267   return typeof window !== "undefined";
1268 }
1269
1270 export function setIsoData(context: any): IsoData {
1271   // If its the browser, you need to deserialize the data from the window
1272   if (isBrowser()) {
1273     return window.isoData;
1274   } else return context.router.staticContext;
1275 }
1276
1277 export function wsSubscribe(parseMessage: any): Subscription | undefined {
1278   if (isBrowser()) {
1279     return WebSocketService.Instance.subject
1280       .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1281       .subscribe(
1282         msg => parseMessage(msg),
1283         err => console.error(err),
1284         () => console.log("complete")
1285       );
1286   } else {
1287     return undefined;
1288   }
1289 }
1290
1291 moment.updateLocale("en", {
1292   relativeTime: {
1293     future: "in %s",
1294     past: "%s ago",
1295     s: "<1m",
1296     ss: "%ds",
1297     m: "1m",
1298     mm: "%dm",
1299     h: "1h",
1300     hh: "%dh",
1301     d: "1d",
1302     dd: "%dd",
1303     w: "1w",
1304     ww: "%dw",
1305     M: "1M",
1306     MM: "%dM",
1307     y: "1Y",
1308     yy: "%dY",
1309   },
1310 });
1311
1312 export function saveScrollPosition(context: any) {
1313   const path: string = context.router.route.location.pathname;
1314   const y = window.scrollY;
1315   sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1316 }
1317
1318 export function restoreScrollPosition(context: any) {
1319   const path: string = context.router.route.location.pathname;
1320   const y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1321   window.scrollTo(0, y);
1322 }
1323
1324 export function showLocal(isoData: IsoData): boolean {
1325   return isoData.site_res.site_view.local_site.federation_enabled;
1326 }
1327
1328 export interface Choice {
1329   value: string;
1330   label: string;
1331   disabled?: boolean;
1332 }
1333
1334 export function getUpdatedSearchId(id?: number | null, urlId?: number | null) {
1335   return id === null
1336     ? undefined
1337     : ((id ?? urlId) === 0 ? undefined : id ?? urlId)?.toString();
1338 }
1339
1340 export function communityToChoice(cv: CommunityView): Choice {
1341   return {
1342     value: cv.community.id.toString(),
1343     label: communitySelectName(cv),
1344   };
1345 }
1346
1347 export function personToChoice(pvs: PersonView): Choice {
1348   return {
1349     value: pvs.person.id.toString(),
1350     label: personSelectName(pvs),
1351   };
1352 }
1353
1354 export async function fetchCommunities(q: string) {
1355   const form: Search = {
1356     q,
1357     type_: "Communities",
1358     sort: "TopAll",
1359     listing_type: "All",
1360     page: 1,
1361     limit: fetchLimit,
1362     auth: myAuth(false),
1363   };
1364   const client = new LemmyHttp(getHttpBase());
1365   return client.search(form);
1366 }
1367
1368 export async function fetchUsers(q: string) {
1369   const form: Search = {
1370     q,
1371     type_: "Users",
1372     sort: "TopAll",
1373     listing_type: "All",
1374     page: 1,
1375     limit: fetchLimit,
1376     auth: myAuth(false),
1377   };
1378   const client = new LemmyHttp(getHttpBase());
1379   return client.search(form);
1380 }
1381
1382 export function communitySelectName(cv: CommunityView): string {
1383   return cv.community.local
1384     ? cv.community.title
1385     : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1386 }
1387
1388 export function personSelectName({
1389   person: { display_name, name, local, actor_id },
1390 }: PersonView): string {
1391   const pName = display_name ?? name;
1392   return local ? pName : `${hostname(actor_id)}/${pName}`;
1393 }
1394
1395 export function initializeSite(site?: GetSiteResponse) {
1396   UserService.Instance.myUserInfo = site?.my_user;
1397   i18n.changeLanguage(getLanguages()[0]);
1398   if (site) {
1399     setupEmojiDataModel(site.custom_emojis);
1400   }
1401   setupMarkdown();
1402 }
1403
1404 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1405   maximumSignificantDigits: 3,
1406   //@ts-ignore
1407   notation: "compact",
1408   compactDisplay: "short",
1409 });
1410
1411 export function numToSI(value: number): string {
1412   return SHORTNUM_SI_FORMAT.format(value);
1413 }
1414
1415 export function isBanned(ps: Person): boolean {
1416   const expires = ps.ban_expires;
1417   // Add Z to convert from UTC date
1418   // TODO this check probably isn't necessary anymore
1419   if (expires) {
1420     if (ps.banned && new Date(expires + "Z") > new Date()) {
1421       return true;
1422     } else {
1423       return false;
1424     }
1425   } else {
1426     return ps.banned;
1427   }
1428 }
1429
1430 export function myAuth(throwErr = true): string | undefined {
1431   return UserService.Instance.auth(throwErr);
1432 }
1433
1434 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1435   return siteRes.site_view.local_site.enable_downvotes;
1436 }
1437
1438 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1439   return siteRes.site_view.local_site.enable_nsfw;
1440 }
1441
1442 export function postToCommentSortType(sort: SortType): CommentSortType {
1443   switch (sort) {
1444     case "Active":
1445     case "Hot":
1446       return "Hot";
1447     case "New":
1448     case "NewComments":
1449       return "New";
1450     case "Old":
1451       return "Old";
1452     default:
1453       return "Top";
1454   }
1455 }
1456
1457 export function canCreateCommunity(
1458   siteRes: GetSiteResponse,
1459   myUserInfo = UserService.Instance.myUserInfo
1460 ): boolean {
1461   const adminOnly = siteRes.site_view.local_site.community_creation_admin_only;
1462   // TODO: Make this check if user is logged on as well
1463   return !adminOnly || amAdmin(myUserInfo);
1464 }
1465
1466 export function isPostBlocked(
1467   pv: PostView,
1468   myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
1469 ): boolean {
1470   return (
1471     (myUserInfo?.community_blocks
1472       .map(c => c.community.id)
1473       .includes(pv.community.id) ||
1474       myUserInfo?.person_blocks
1475         .map(p => p.target.id)
1476         .includes(pv.creator.id)) ??
1477     false
1478   );
1479 }
1480
1481 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1482 export function nsfwCheck(
1483   pv: PostView,
1484   myUserInfo = UserService.Instance.myUserInfo
1485 ): boolean {
1486   const nsfw = pv.post.nsfw || pv.community.nsfw;
1487   const myShowNsfw = myUserInfo?.local_user_view.local_user.show_nsfw ?? false;
1488   return !nsfw || (nsfw && myShowNsfw);
1489 }
1490
1491 export function getRandomFromList<T>(list: T[]): T | undefined {
1492   return list.length == 0
1493     ? undefined
1494     : list.at(Math.floor(Math.random() * list.length));
1495 }
1496
1497 /**
1498  * This shows what language you can select
1499  *
1500  * Use showAll for the site form
1501  * Use showSite for the profile and community forms
1502  * Use false for both those to filter on your profile and site ones
1503  */
1504 export function selectableLanguages(
1505   allLanguages: Language[],
1506   siteLanguages: number[],
1507   showAll?: boolean,
1508   showSite?: boolean,
1509   myUserInfo = UserService.Instance.myUserInfo
1510 ): Language[] {
1511   const allLangIds = allLanguages.map(l => l.id);
1512   let myLangs = myUserInfo?.discussion_languages ?? allLangIds;
1513   myLangs = myLangs.length == 0 ? allLangIds : myLangs;
1514   const siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages;
1515
1516   if (showAll) {
1517     return allLanguages;
1518   } else {
1519     if (showSite) {
1520       return allLanguages.filter(x => siteLangs.includes(x.id));
1521     } else {
1522       return allLanguages
1523         .filter(x => siteLangs.includes(x.id))
1524         .filter(x => myLangs.includes(x.id));
1525     }
1526   }
1527 }
1528
1529 export function uploadImage(image: File): Promise<UploadImageResponse> {
1530   const client = new LemmyHttp(getHttpBase());
1531
1532   return client.uploadImage({ image });
1533 }
1534
1535 interface EmojiMartCategory {
1536   id: string;
1537   name: string;
1538   emojis: EmojiMartCustomEmoji[];
1539 }
1540
1541 interface EmojiMartCustomEmoji {
1542   id: string;
1543   name: string;
1544   keywords: string[];
1545   skins: EmojiMartSkin[];
1546 }
1547
1548 interface EmojiMartSkin {
1549   src: string;
1550 }
1551
1552 const groupBy = <T>(
1553   array: T[],
1554   predicate: (value: T, index: number, array: T[]) => string
1555 ) =>
1556   array.reduce((acc, value, index, array) => {
1557     (acc[predicate(value, index, array)] ||= []).push(value);
1558     return acc;
1559   }, {} as { [key: string]: T[] });
1560
1561 export type QueryParams<T extends Record<string, any>> = {
1562   [key in keyof T]?: string;
1563 };
1564
1565 export function getQueryParams<T extends Record<string, any>>(processors: {
1566   [K in keyof T]: (param: string) => T[K];
1567 }): T {
1568   if (isBrowser()) {
1569     const searchParams = new URLSearchParams(window.location.search);
1570
1571     return Array.from(Object.entries(processors)).reduce(
1572       (acc, [key, process]) => ({
1573         ...acc,
1574         [key]: process(searchParams.get(key)),
1575       }),
1576       {} as T
1577     );
1578   }
1579
1580   return {} as T;
1581 }
1582
1583 export function getQueryString<T extends Record<string, string | undefined>>(
1584   obj: T
1585 ) {
1586   return Object.entries(obj)
1587     .filter(([, val]) => val !== undefined && val !== null)
1588     .reduce(
1589       (acc, [key, val], index) => `${acc}${index > 0 ? "&" : ""}${key}=${val}`,
1590       "?"
1591     );
1592 }
1593
1594 export function isAuthPath(pathname: string) {
1595   return /create_.*|inbox|settings|setup|admin|reports|registration_applications/g.test(
1596     pathname
1597   );
1598 }
1599
1600 export function canShare() {
1601   return isBrowser() && !!navigator.canShare;
1602 }
1603
1604 export function share(shareData: ShareData) {
1605   if (isBrowser()) {
1606     navigator.share(shareData);
1607   }
1608 }