]> Untitled Git - lemmy-ui.git/blob - src/shared/utils.ts
Handle error when site not returned
[lemmy-ui.git] / src / shared / utils.ts
1 import { Picker } from "emoji-mart";
2 import emojiShortName from "emoji-short-name";
3 import {
4   BlockCommunityResponse,
5   BlockPersonResponse,
6   Comment as CommentI,
7   CommentReportView,
8   CommentSortType,
9   CommentView,
10   CommunityModeratorView,
11   CommunityView,
12   CustomEmojiView,
13   GetSiteMetadata,
14   GetSiteResponse,
15   Language,
16   LemmyHttp,
17   LemmyWebsocket,
18   MyUserInfo,
19   Person,
20   PersonView,
21   PostReportView,
22   PostView,
23   PrivateMessageReportView,
24   PrivateMessageView,
25   RegistrationApplicationView,
26   Search,
27   SortType,
28   UploadImageResponse,
29 } from "lemmy-js-client";
30 import { default as MarkdownIt } from "markdown-it";
31 import markdown_it_container from "markdown-it-container";
32 import markdown_it_emoji from "markdown-it-emoji/bare";
33 import markdown_it_footnote from "markdown-it-footnote";
34 import markdown_it_html5_embed from "markdown-it-html5-embed";
35 import markdown_it_sub from "markdown-it-sub";
36 import markdown_it_sup from "markdown-it-sup";
37 import Renderer from "markdown-it/lib/renderer";
38 import Token from "markdown-it/lib/token";
39 import moment from "moment";
40 import { Subscription } from "rxjs";
41 import { delay, retryWhen, take } from "rxjs/operators";
42 import tippy from "tippy.js";
43 import Toastify from "toastify-js";
44 import { getHttpBase } from "./env";
45 import { i18n, languages } from "./i18next";
46 import { CommentNodeI, DataType, IsoData } from "./interfaces";
47 import { UserService, WebSocketService } from "./services";
48
49 let Tribute: any;
50 if (isBrowser()) {
51   Tribute = require("tributejs");
52 }
53
54 export const wsClient = new LemmyWebsocket();
55
56 export const favIconUrl = "/static/assets/icons/favicon.svg";
57 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
58 // TODO
59 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
60 export const repoUrl = "https://github.com/LemmyNet";
61 export const joinLemmyUrl = "https://join-lemmy.org";
62 export const donateLemmyUrl = `${joinLemmyUrl}/donate`;
63 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
64 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/users/01-getting-started.html`; // TODO find a way to redirect to the non-en folder
65 export const markdownHelpUrl = `${joinLemmyUrl}/docs/en/users/02-media.html`;
66 export const sortingHelpUrl = `${helpGuideUrl}/docs/en/users/03-votes-and-ranking.html`;
67 export const archiveTodayUrl = "https://archive.today";
68 export const ghostArchiveUrl = "https://ghostarchive.org";
69 export const webArchiveUrl = "https://web.archive.org";
70 export const elementUrl = "https://element.io";
71
72 export const postRefetchSeconds: number = 60 * 1000;
73 export const fetchLimit = 40n;
74 export const trendingFetchLimit = 6n;
75 export const mentionDropdownFetchLimit = 10;
76 export const commentTreeMaxDepth = 8;
77 export const markdownFieldCharacterLimit = 50000;
78 export const maxUploadImages = 20n;
79 export const concurrentImageUpload = 4;
80
81 export const relTags = "noopener nofollow";
82
83 export const emDash = "\u2014";
84
85 export type ThemeColor =
86   | "primary"
87   | "secondary"
88   | "light"
89   | "dark"
90   | "success"
91   | "danger"
92   | "warning"
93   | "info"
94   | "blue"
95   | "indigo"
96   | "purple"
97   | "pink"
98   | "red"
99   | "orange"
100   | "yellow"
101   | "green"
102   | "teal"
103   | "cyan"
104   | "white"
105   | "gray"
106   | "gray-dark";
107
108 export interface ErrorPageData {
109   type: "error";
110   error?: string;
111   adminMatrixIds?: string[];
112 }
113
114 let customEmojis: EmojiMartCategory[] = [];
115 export let customEmojisLookup: Map<string, CustomEmojiView> = new Map<
116   string,
117   CustomEmojiView
118 >();
119
120 const DEFAULT_ALPHABET =
121   "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
122
123 function getRandomCharFromAlphabet(alphabet: string): string {
124   return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
125 }
126
127 export function getIdFromString(id?: string): number | undefined {
128   return id && id !== "0" && !Number.isNaN(Number(id)) ? Number(id) : undefined;
129 }
130
131 export function getPageFromString(page?: string): bigint {
132   return page && !Number.isNaN(Number(page)) ? BigInt(page) : BigInt(1);
133 }
134
135 export function randomStr(
136   idDesiredLength = 20,
137   alphabet = DEFAULT_ALPHABET
138 ): string {
139   /**
140    * Create n-long array and map it to random chars from given alphabet.
141    * Then join individual chars as string
142    */
143   return Array.from({ length: idDesiredLength })
144     .map(() => {
145       return getRandomCharFromAlphabet(alphabet);
146     })
147     .join("");
148 }
149
150 const html5EmbedConfig = {
151   html5embed: {
152     useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
153     attributes: {
154       audio: 'controls preload="metadata"',
155       video: 'width="100%" max-height="100%" controls loop preload="metadata"',
156     },
157   },
158 };
159
160 const spoilerConfig = {
161   validate: (params: string) => {
162     return params.trim().match(/^spoiler\s+(.*)$/);
163   },
164
165   render: (tokens: any, idx: any) => {
166     var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
167
168     if (tokens[idx].nesting === 1) {
169       // opening tag
170       return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
171     } else {
172       // closing tag
173       return "</details>\n";
174     }
175   },
176 };
177
178 export let md: MarkdownIt = new MarkdownIt();
179
180 export let mdNoImages: MarkdownIt = new MarkdownIt();
181
182 export function hotRankComment(comment_view: CommentView): number {
183   return hotRank(comment_view.counts.score, comment_view.comment.published);
184 }
185
186 export function hotRankActivePost(post_view: PostView): number {
187   return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
188 }
189
190 export function hotRankPost(post_view: PostView): number {
191   return hotRank(post_view.counts.score, post_view.post.published);
192 }
193
194 export function hotRank(score: bigint, timeStr: string): number {
195   // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
196   let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
197   let now: Date = new Date();
198   let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
199
200   let rank =
201     (10000 * Math.log10(Math.max(1, Number(3n + score)))) /
202     Math.pow(hoursElapsed + 2, 1.8);
203
204   // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
205
206   return rank;
207 }
208
209 export function mdToHtml(text: string) {
210   return { __html: md.render(text) };
211 }
212
213 export function mdToHtmlNoImages(text: string) {
214   return { __html: mdNoImages.render(text) };
215 }
216
217 export function mdToHtmlInline(text: string) {
218   return { __html: md.renderInline(text) };
219 }
220
221 export function getUnixTime(text?: string): bigint | undefined {
222   return text ? BigInt(new Date(text).getTime() / 1000) : undefined;
223 }
224
225 export function futureDaysToUnixTime(days?: number): bigint | undefined {
226   return days
227     ? BigInt(
228         Math.trunc(
229           new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
230         )
231       )
232     : undefined;
233 }
234
235 export function canMod(
236   creator_id: number,
237   mods?: CommunityModeratorView[],
238   admins?: PersonView[],
239   myUserInfo = UserService.Instance.myUserInfo,
240   onSelf = false
241 ): boolean {
242   // You can do moderator actions only on the mods added after you.
243   let adminsThenMods =
244     admins
245       ?.map(a => a.person.id)
246       .concat(mods?.map(m => m.moderator.id) ?? []) ?? [];
247
248   if (myUserInfo) {
249     let myIndex = adminsThenMods.findIndex(
250       id => id == myUserInfo.local_user_view.person.id
251     );
252     if (myIndex == -1) {
253       return false;
254     } else {
255       // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
256       adminsThenMods = adminsThenMods.slice(0, myIndex + (onSelf ? 0 : 1));
257       return !adminsThenMods.includes(creator_id);
258     }
259   } else {
260     return false;
261   }
262 }
263
264 export function canAdmin(
265   creatorId: number,
266   admins?: PersonView[],
267   myUserInfo = UserService.Instance.myUserInfo,
268   onSelf = false
269 ): boolean {
270   return canMod(creatorId, undefined, admins, myUserInfo, onSelf);
271 }
272
273 export function isMod(
274   creatorId: number,
275   mods?: CommunityModeratorView[]
276 ): boolean {
277   return mods?.map(m => m.moderator.id).includes(creatorId) ?? false;
278 }
279
280 export function amMod(
281   mods?: CommunityModeratorView[],
282   myUserInfo = UserService.Instance.myUserInfo
283 ): boolean {
284   return myUserInfo ? isMod(myUserInfo.local_user_view.person.id, mods) : false;
285 }
286
287 export function isAdmin(creatorId: number, admins?: PersonView[]): boolean {
288   return admins?.map(a => a.person.id).includes(creatorId) ?? false;
289 }
290
291 export function amAdmin(myUserInfo = UserService.Instance.myUserInfo): boolean {
292   return myUserInfo?.local_user_view.person.admin ?? false;
293 }
294
295 export function amCommunityCreator(
296   creator_id: number,
297   mods?: CommunityModeratorView[],
298   myUserInfo = UserService.Instance.myUserInfo
299 ): boolean {
300   let myId = myUserInfo?.local_user_view.person.id;
301   // Don't allow mod actions on yourself
302   return myId == mods?.at(0)?.moderator.id && myId != creator_id;
303 }
304
305 export function amSiteCreator(
306   creator_id: number,
307   admins?: PersonView[],
308   myUserInfo = UserService.Instance.myUserInfo
309 ): boolean {
310   let myId = myUserInfo?.local_user_view.person.id;
311   return myId == admins?.at(0)?.person.id && myId != creator_id;
312 }
313
314 export function amTopMod(
315   mods: CommunityModeratorView[],
316   myUserInfo = UserService.Instance.myUserInfo
317 ): boolean {
318   return mods.at(0)?.moderator.id == myUserInfo?.local_user_view.person.id;
319 }
320
321 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
322 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
323
324 export function isImage(url: string) {
325   return imageRegex.test(url);
326 }
327
328 export function isVideo(url: string) {
329   return videoRegex.test(url);
330 }
331
332 export function validURL(str: string) {
333   return !!new URL(str);
334 }
335
336 export function communityRSSUrl(actorId: string, sort: string): string {
337   let url = new URL(actorId);
338   return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
339 }
340
341 export function validEmail(email: string) {
342   let re =
343     /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
344   return re.test(String(email).toLowerCase());
345 }
346
347 export function capitalizeFirstLetter(str: string): string {
348   return str.charAt(0).toUpperCase() + str.slice(1);
349 }
350
351 export async function getSiteMetadata(url: string) {
352   let form: GetSiteMetadata = { url };
353   let client = new LemmyHttp(getHttpBase());
354   return client.getSiteMetadata(form);
355 }
356
357 export function getDataTypeString(dt: DataType) {
358   return dt === DataType.Post ? "Post" : "Comment";
359 }
360
361 export function debounce<T extends any[], R>(
362   func: (...e: T) => R,
363   wait = 1000,
364   immediate = false
365 ) {
366   // 'private' variable for instance
367   // The returned function will be able to reference this due to closure.
368   // Each call to the returned function will share this common timer.
369   let timeout: NodeJS.Timeout | null;
370
371   // Calling debounce returns a new anonymous function
372   return function () {
373     // reference the context and args for the setTimeout function
374     const args = arguments;
375
376     // Should the function be called now? If immediate is true
377     //   and not already in a timeout then the answer is: Yes
378     const callNow = immediate && !timeout;
379
380     // This is the basic debounce behavior where you can call this
381     //   function several times, but it will only execute once
382     //   [before or after imposing a delay].
383     //   Each time the returned function is called, the timer starts over.
384     clearTimeout(timeout ?? undefined);
385
386     // Set the new timeout
387     timeout = setTimeout(function () {
388       // Inside the timeout function, clear the timeout variable
389       // which will let the next execution run when in 'immediate' mode
390       timeout = null;
391
392       // Check if the function already ran with the immediate flag
393       if (!immediate) {
394         // Call the original function with apply
395         // apply lets you define the 'this' object as well as the arguments
396         //    (both captured before setTimeout)
397         func.apply(this, args);
398       }
399     }, wait);
400
401     // Immediate mode and no wait timer? Execute the function..
402     if (callNow) func.apply(this, args);
403   } as (...e: T) => R;
404 }
405
406 export function getLanguages(
407   override?: string,
408   myUserInfo = UserService.Instance.myUserInfo
409 ): string[] {
410   let myLang = myUserInfo?.local_user_view.local_user.interface_language;
411   let lang = override || myLang || "browser";
412
413   if (lang == "browser" && isBrowser()) {
414     return getBrowserLanguages();
415   } else {
416     return [lang];
417   }
418 }
419
420 function getBrowserLanguages(): string[] {
421   // Intersect lemmy's langs, with the browser langs
422   let langs = languages ? languages.map(l => l.code) : ["en"];
423
424   // NOTE, mobile browsers seem to be missing this list, so append en
425   let allowedLangs = navigator.languages
426     .concat("en")
427     .filter(v => langs.includes(v));
428   return allowedLangs;
429 }
430
431 export async function fetchThemeList(): Promise<string[]> {
432   return fetch("/css/themelist").then(res => res.json());
433 }
434
435 export async function setTheme(theme: string, forceReload = false) {
436   if (!isBrowser()) {
437     return;
438   }
439   if (theme === "browser" && !forceReload) {
440     return;
441   }
442   // This is only run on a force reload
443   if (theme == "browser") {
444     theme = "darkly";
445   }
446
447   let themeList = await fetchThemeList();
448
449   // Unload all the other themes
450   for (var i = 0; i < themeList.length; i++) {
451     let styleSheet = document.getElementById(themeList[i]);
452     if (styleSheet) {
453       styleSheet.setAttribute("disabled", "disabled");
454     }
455   }
456
457   document
458     .getElementById("default-light")
459     ?.setAttribute("disabled", "disabled");
460   document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
461
462   // Load the theme dynamically
463   let cssLoc = `/css/themes/${theme}.css`;
464
465   loadCss(theme, cssLoc);
466   document.getElementById(theme)?.removeAttribute("disabled");
467 }
468
469 export function loadCss(id: string, loc: string) {
470   if (!document.getElementById(id)) {
471     var head = document.getElementsByTagName("head")[0];
472     var link = document.createElement("link");
473     link.id = id;
474     link.rel = "stylesheet";
475     link.type = "text/css";
476     link.href = loc;
477     link.media = "all";
478     head.appendChild(link);
479   }
480 }
481
482 export function objectFlip(obj: any) {
483   const ret = {};
484   Object.keys(obj).forEach(key => {
485     ret[obj[key]] = key;
486   });
487   return ret;
488 }
489
490 export function showAvatars(
491   myUserInfo = UserService.Instance.myUserInfo
492 ): boolean {
493   return myUserInfo?.local_user_view.local_user.show_avatars ?? true;
494 }
495
496 export function showScores(
497   myUserInfo = UserService.Instance.myUserInfo
498 ): boolean {
499   return myUserInfo?.local_user_view.local_user.show_scores ?? true;
500 }
501
502 export function isCakeDay(published: string): boolean {
503   // moment(undefined) or moment.utc(undefined) returns the current date/time
504   // moment(null) or moment.utc(null) returns null
505   const createDate = moment.utc(published).local();
506   const currentDate = moment(new Date());
507
508   return (
509     createDate.date() === currentDate.date() &&
510     createDate.month() === currentDate.month() &&
511     createDate.year() !== currentDate.year()
512   );
513 }
514
515 export function toast(text: string, background: ThemeColor = "success") {
516   if (isBrowser()) {
517     const backgroundColor = `var(--${background})`;
518     Toastify({
519       text: text,
520       backgroundColor: backgroundColor,
521       gravity: "bottom",
522       position: "left",
523       duration: 5000,
524     }).showToast();
525   }
526 }
527
528 export function pictrsDeleteToast(filename: string, deleteUrl: string) {
529   if (isBrowser()) {
530     const clickToDeleteText = i18n.t("click_to_delete_picture", { filename });
531     const deletePictureText = i18n.t("picture_deleted", {
532       filename,
533     });
534     const failedDeletePictureText = i18n.t("failed_to_delete_picture", {
535       filename,
536     });
537
538     const backgroundColor = `var(--light)`;
539
540     const toast = Toastify({
541       text: clickToDeleteText,
542       backgroundColor: backgroundColor,
543       gravity: "top",
544       position: "right",
545       duration: 10000,
546       onClick: () => {
547         if (toast) {
548           fetch(deleteUrl).then(res => {
549             toast.hideToast();
550             if (res.ok === true) {
551               alert(deletePictureText);
552             } else {
553               alert(failedDeletePictureText);
554             }
555           });
556         }
557       },
558       close: true,
559     });
560
561     toast.showToast();
562   }
563 }
564
565 interface NotifyInfo {
566   name: string;
567   icon?: string;
568   link: string;
569   body?: string;
570 }
571
572 export function messageToastify(info: NotifyInfo, router: any) {
573   if (isBrowser()) {
574     let htmlBody = info.body ? md.render(info.body) : "";
575     let backgroundColor = `var(--light)`;
576
577     let toast = Toastify({
578       text: `${htmlBody}<br />${info.name}`,
579       avatar: info.icon,
580       backgroundColor: backgroundColor,
581       className: "text-dark",
582       close: true,
583       gravity: "top",
584       position: "right",
585       duration: 5000,
586       escapeMarkup: false,
587       onClick: () => {
588         if (toast) {
589           toast.hideToast();
590           router.history.push(info.link);
591         }
592       },
593     });
594     toast.showToast();
595   }
596 }
597
598 export function notifyPost(post_view: PostView, router: any) {
599   let info: NotifyInfo = {
600     name: post_view.community.name,
601     icon: post_view.community.icon,
602     link: `/post/${post_view.post.id}`,
603     body: post_view.post.name,
604   };
605   notify(info, router);
606 }
607
608 export function notifyComment(comment_view: CommentView, router: any) {
609   let info: NotifyInfo = {
610     name: comment_view.creator.name,
611     icon: comment_view.creator.avatar,
612     link: `/comment/${comment_view.comment.id}`,
613     body: comment_view.comment.content,
614   };
615   notify(info, router);
616 }
617
618 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
619   let info: NotifyInfo = {
620     name: pmv.creator.name,
621     icon: pmv.creator.avatar,
622     link: `/inbox`,
623     body: pmv.private_message.content,
624   };
625   notify(info, router);
626 }
627
628 function notify(info: NotifyInfo, router: any) {
629   messageToastify(info, router);
630
631   if (Notification.permission !== "granted") Notification.requestPermission();
632   else {
633     var notification = new Notification(info.name, {
634       ...{ body: info.body },
635       ...(info.icon && { icon: info.icon }),
636     });
637
638     notification.onclick = (ev: Event): any => {
639       ev.preventDefault();
640       router.history.push(info.link);
641     };
642   }
643 }
644
645 export function setupTribute() {
646   return new Tribute({
647     noMatchTemplate: function () {
648       return "";
649     },
650     collection: [
651       // Emojis
652       {
653         trigger: ":",
654         menuItemTemplate: (item: any) => {
655           let shortName = `:${item.original.key}:`;
656           return `${item.original.val} ${shortName}`;
657         },
658         selectTemplate: (item: any) => {
659           let customEmoji = customEmojisLookup.get(
660             item.original.key
661           )?.custom_emoji;
662           if (customEmoji == undefined) return `${item.original.val}`;
663           else
664             return `![${customEmoji.alt_text}](${customEmoji.image_url} "${customEmoji.shortcode}")`;
665         },
666         values: Object.entries(emojiShortName)
667           .map(e => {
668             return { key: e[1], val: e[0] };
669           })
670           .concat(
671             Array.from(customEmojisLookup.entries()).map(k => ({
672               key: k[0],
673               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}" />`,
674             }))
675           ),
676         allowSpaces: false,
677         autocompleteMode: true,
678         // TODO
679         // menuItemLimit: mentionDropdownFetchLimit,
680         menuShowMinLength: 2,
681       },
682       // Persons
683       {
684         trigger: "@",
685         selectTemplate: (item: any) => {
686           let it: PersonTribute = item.original;
687           return `[${it.key}](${it.view.person.actor_id})`;
688         },
689         values: debounce(async (text: string, cb: any) => {
690           cb(await personSearch(text));
691         }),
692         allowSpaces: false,
693         autocompleteMode: true,
694         // TODO
695         // menuItemLimit: mentionDropdownFetchLimit,
696         menuShowMinLength: 2,
697       },
698
699       // Communities
700       {
701         trigger: "!",
702         selectTemplate: (item: any) => {
703           let it: CommunityTribute = item.original;
704           return `[${it.key}](${it.view.community.actor_id})`;
705         },
706         values: debounce(async (text: string, cb: any) => {
707           cb(await communitySearch(text));
708         }),
709         allowSpaces: false,
710         autocompleteMode: true,
711         // TODO
712         // menuItemLimit: mentionDropdownFetchLimit,
713         menuShowMinLength: 2,
714       },
715     ],
716   });
717 }
718
719 function setupEmojiDataModel(custom_emoji_views: CustomEmojiView[]) {
720   let groupedEmojis = groupBy(custom_emoji_views, x => x.custom_emoji.category);
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   let 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     let 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 (let 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   let users = (await fetchUsers(text)).users;
879   let persons: PersonTribute[] = users.map(pv => {
880     let 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   let comms = (await fetchCommunities(text)).communities;
896   let communities: CommunityTribute[] = comms.map(cv => {
897     let 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   let id = props.match.params.post_id;
914   return id ? Number(id) : undefined;
915 }
916
917 export function getCommentIdFromProps(props: any): number | undefined {
918   let id = props.match.params.comment_id;
919   return id ? Number(id) : undefined;
920 }
921
922 export function editCommentRes(data: CommentView, comments?: CommentView[]) {
923   let 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   let 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   let 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   let 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   let 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   let 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   let 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   let 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   let found = reports?.find(c => c.comment_report.id == data.comment_report.id);
1056   if (found) {
1057     found.comment_report = data.comment_report;
1058   }
1059 }
1060
1061 export function updatePrivateMessageReportRes(
1062   data: PrivateMessageReportView,
1063   reports?: PrivateMessageReportView[]
1064 ) {
1065   let found = reports?.find(
1066     c => c.private_message_report.id == data.private_message_report.id
1067   );
1068   if (found) {
1069     found.private_message_report = data.private_message_report;
1070   }
1071 }
1072
1073 export function updateRegistrationApplicationRes(
1074   data: RegistrationApplicationView,
1075   applications?: RegistrationApplicationView[]
1076 ) {
1077   let found = applications?.find(
1078     ra => ra.registration_application.id == data.registration_application.id
1079   );
1080   if (found) {
1081     found.registration_application = data.registration_application;
1082     found.admin = data.admin;
1083     found.creator_local_user = data.creator_local_user;
1084   }
1085 }
1086
1087 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
1088   let nodes: CommentNodeI[] = [];
1089   for (let comment of comments) {
1090     nodes.push({ comment_view: comment, children: [], depth: 0 });
1091   }
1092   return nodes;
1093 }
1094
1095 export function convertCommentSortType(sort: SortType): CommentSortType {
1096   if (
1097     sort == "TopAll" ||
1098     sort == "TopDay" ||
1099     sort == "TopWeek" ||
1100     sort == "TopMonth" ||
1101     sort == "TopYear"
1102   ) {
1103     return "Top";
1104   } else if (sort == "New") {
1105     return "New";
1106   } else if (sort == "Hot" || sort == "Active") {
1107     return "Hot";
1108   } else {
1109     return "Hot";
1110   }
1111 }
1112
1113 export function buildCommentsTree(
1114   comments: CommentView[],
1115   parentComment: boolean
1116 ): CommentNodeI[] {
1117   let map = new Map<number, CommentNodeI>();
1118   let depthOffset = !parentComment
1119     ? 0
1120     : getDepthFromComment(comments[0].comment) ?? 0;
1121
1122   for (let comment_view of comments) {
1123     let depthI = getDepthFromComment(comment_view.comment) ?? 0;
1124     let depth = depthI ? depthI - depthOffset : 0;
1125     let node: CommentNodeI = {
1126       comment_view,
1127       children: [],
1128       depth,
1129     };
1130     map.set(comment_view.comment.id, { ...node });
1131   }
1132
1133   let tree: CommentNodeI[] = [];
1134
1135   // if its a parent comment fetch, then push the first comment to the top node.
1136   if (parentComment) {
1137     let cNode = map.get(comments[0].comment.id);
1138     if (cNode) {
1139       tree.push(cNode);
1140     }
1141   }
1142
1143   for (let comment_view of comments) {
1144     let child = map.get(comment_view.comment.id);
1145     if (child) {
1146       let parent_id = getCommentParentId(comment_view.comment);
1147       if (parent_id) {
1148         let parent = map.get(parent_id);
1149         // Necessary because blocked comment might not exist
1150         if (parent) {
1151           parent.children.push(child);
1152         }
1153       } else {
1154         if (!parentComment) {
1155           tree.push(child);
1156         }
1157       }
1158     }
1159   }
1160
1161   return tree;
1162 }
1163
1164 export function getCommentParentId(comment?: CommentI): number | undefined {
1165   let split = comment?.path.split(".");
1166   // remove the 0
1167   split?.shift();
1168
1169   return split && split.length > 1
1170     ? Number(split.at(split.length - 2))
1171     : undefined;
1172 }
1173
1174 export function getDepthFromComment(comment?: CommentI): number | undefined {
1175   let len = comment?.path.split(".").length;
1176   return len ? len - 2 : undefined;
1177 }
1178
1179 export function insertCommentIntoTree(
1180   tree: CommentNodeI[],
1181   cv: CommentView,
1182   parentComment: boolean
1183 ) {
1184   // Building a fake node to be used for later
1185   let node: CommentNodeI = {
1186     comment_view: cv,
1187     children: [],
1188     depth: 0,
1189   };
1190
1191   let parentId = getCommentParentId(cv.comment);
1192   if (parentId) {
1193     let parent_comment = searchCommentTree(tree, parentId);
1194     if (parent_comment) {
1195       node.depth = parent_comment.depth + 1;
1196       parent_comment.children.unshift(node);
1197     }
1198   } else if (!parentComment) {
1199     tree.unshift(node);
1200   }
1201 }
1202
1203 export function searchCommentTree(
1204   tree: CommentNodeI[],
1205   id: number
1206 ): CommentNodeI | undefined {
1207   for (let node of tree) {
1208     if (node.comment_view.comment.id === id) {
1209       return node;
1210     }
1211
1212     for (const child of node.children) {
1213       let res = searchCommentTree([child], id);
1214
1215       if (res) {
1216         return res;
1217       }
1218     }
1219   }
1220   return undefined;
1221 }
1222
1223 export const colorList: string[] = [
1224   hsl(0),
1225   hsl(50),
1226   hsl(100),
1227   hsl(150),
1228   hsl(200),
1229   hsl(250),
1230   hsl(300),
1231 ];
1232
1233 function hsl(num: number) {
1234   return `hsla(${num}, 35%, 50%, 1)`;
1235 }
1236
1237 export function hostname(url: string): string {
1238   let cUrl = new URL(url);
1239   return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1240 }
1241
1242 export function validTitle(title?: string): boolean {
1243   // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1244   if (!title || title.length < 3) return true;
1245
1246   const regex = new RegExp(/.*\S.*/, "g");
1247
1248   return regex.test(title);
1249 }
1250
1251 export function siteBannerCss(banner: string): string {
1252   return ` \
1253     background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1254     background-attachment: fixed; \
1255     background-position: top; \
1256     background-repeat: no-repeat; \
1257     background-size: 100% cover; \
1258
1259     width: 100%; \
1260     max-height: 100vh; \
1261     `;
1262 }
1263
1264 export function isBrowser() {
1265   return typeof window !== "undefined";
1266 }
1267
1268 export function setIsoData(context: any): IsoData {
1269   // If its the browser, you need to deserialize the data from the window
1270   if (isBrowser()) {
1271     let json = window.isoData;
1272     let routeData = json.routeData;
1273     let site_res = json.site_res;
1274
1275     let isoData: IsoData = {
1276       path: json.path,
1277       site_res,
1278       routeData,
1279     };
1280     return isoData;
1281   } else return context.router.staticContext;
1282 }
1283
1284 export function wsSubscribe(parseMessage: any): Subscription | undefined {
1285   if (isBrowser()) {
1286     return WebSocketService.Instance.subject
1287       .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1288       .subscribe(
1289         msg => parseMessage(msg),
1290         err => console.error(err),
1291         () => console.log("complete")
1292       );
1293   } else {
1294     return undefined;
1295   }
1296 }
1297
1298 moment.updateLocale("en", {
1299   relativeTime: {
1300     future: "in %s",
1301     past: "%s ago",
1302     s: "<1m",
1303     ss: "%ds",
1304     m: "1m",
1305     mm: "%dm",
1306     h: "1h",
1307     hh: "%dh",
1308     d: "1d",
1309     dd: "%dd",
1310     w: "1w",
1311     ww: "%dw",
1312     M: "1M",
1313     MM: "%dM",
1314     y: "1Y",
1315     yy: "%dY",
1316   },
1317 });
1318
1319 export function saveScrollPosition(context: any) {
1320   let path: string = context.router.route.location.pathname;
1321   let y = window.scrollY;
1322   sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1323 }
1324
1325 export function restoreScrollPosition(context: any) {
1326   let path: string = context.router.route.location.pathname;
1327   let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1328   window.scrollTo(0, y);
1329 }
1330
1331 export function showLocal(isoData: IsoData): boolean {
1332   return isoData.site_res.site_view.local_site.federation_enabled;
1333 }
1334
1335 export interface Choice {
1336   value: string;
1337   label: string;
1338   disabled?: boolean;
1339 }
1340
1341 export function getUpdatedSearchId(id?: number | null, urlId?: number | null) {
1342   return id === null
1343     ? undefined
1344     : ((id ?? urlId) === 0 ? undefined : id ?? urlId)?.toString();
1345 }
1346
1347 export function communityToChoice(cv: CommunityView): Choice {
1348   return {
1349     value: cv.community.id.toString(),
1350     label: communitySelectName(cv),
1351   };
1352 }
1353
1354 export function personToChoice(pvs: PersonView): Choice {
1355   return {
1356     value: pvs.person.id.toString(),
1357     label: personSelectName(pvs),
1358   };
1359 }
1360
1361 export async function fetchCommunities(q: string) {
1362   let form: Search = {
1363     q,
1364     type_: "Communities",
1365     sort: "TopAll",
1366     listing_type: "All",
1367     page: 1n,
1368     limit: fetchLimit,
1369     auth: myAuth(false),
1370   };
1371   let client = new LemmyHttp(getHttpBase());
1372   return client.search(form);
1373 }
1374
1375 export async function fetchUsers(q: string) {
1376   let form: Search = {
1377     q,
1378     type_: "Users",
1379     sort: "TopAll",
1380     listing_type: "All",
1381     page: 1n,
1382     limit: fetchLimit,
1383     auth: myAuth(false),
1384   };
1385   let client = new LemmyHttp(getHttpBase());
1386   return client.search(form);
1387 }
1388
1389 export function communitySelectName(cv: CommunityView): string {
1390   return cv.community.local
1391     ? cv.community.title
1392     : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1393 }
1394
1395 export function personSelectName({
1396   person: { display_name, name, local, actor_id },
1397 }: PersonView): string {
1398   const pName = display_name ?? name;
1399   return local ? pName : `${hostname(actor_id)}/${pName}`;
1400 }
1401
1402 export function initializeSite(site?: GetSiteResponse) {
1403   UserService.Instance.myUserInfo = site?.my_user;
1404   i18n.changeLanguage(getLanguages()[0]);
1405   if (site) {
1406     setupEmojiDataModel(site.custom_emojis);
1407   }
1408   setupMarkdown();
1409 }
1410
1411 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1412   maximumSignificantDigits: 3,
1413   //@ts-ignore
1414   notation: "compact",
1415   compactDisplay: "short",
1416 });
1417
1418 export function numToSI(value: bigint): string {
1419   return SHORTNUM_SI_FORMAT.format(value);
1420 }
1421
1422 export function isBanned(ps: Person): boolean {
1423   let expires = ps.ban_expires;
1424   // Add Z to convert from UTC date
1425   // TODO this check probably isn't necessary anymore
1426   if (expires) {
1427     if (ps.banned && new Date(expires + "Z") > new Date()) {
1428       return true;
1429     } else {
1430       return false;
1431     }
1432   } else {
1433     return ps.banned;
1434   }
1435 }
1436
1437 export function myAuth(throwErr = true): string | undefined {
1438   return UserService.Instance.auth(throwErr);
1439 }
1440
1441 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1442   return siteRes.site_view.local_site.enable_downvotes;
1443 }
1444
1445 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1446   return siteRes.site_view.local_site.enable_nsfw;
1447 }
1448
1449 export function postToCommentSortType(sort: SortType): CommentSortType {
1450   switch (sort) {
1451     case "Active":
1452     case "Hot":
1453       return "Hot";
1454     case "New":
1455     case "NewComments":
1456       return "New";
1457     case "Old":
1458       return "Old";
1459     default:
1460       return "Top";
1461   }
1462 }
1463
1464 export function canCreateCommunity(
1465   siteRes: GetSiteResponse,
1466   myUserInfo = UserService.Instance.myUserInfo
1467 ): boolean {
1468   const adminOnly = siteRes.site_view.local_site.community_creation_admin_only;
1469   // TODO: Make this check if user is logged on as well
1470   return !adminOnly || amAdmin(myUserInfo);
1471 }
1472
1473 export function isPostBlocked(
1474   pv: PostView,
1475   myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
1476 ): boolean {
1477   return (
1478     (myUserInfo?.community_blocks
1479       .map(c => c.community.id)
1480       .includes(pv.community.id) ||
1481       myUserInfo?.person_blocks
1482         .map(p => p.target.id)
1483         .includes(pv.creator.id)) ??
1484     false
1485   );
1486 }
1487
1488 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1489 export function nsfwCheck(
1490   pv: PostView,
1491   myUserInfo = UserService.Instance.myUserInfo
1492 ): boolean {
1493   let nsfw = pv.post.nsfw || pv.community.nsfw;
1494   let myShowNsfw = myUserInfo?.local_user_view.local_user.show_nsfw ?? false;
1495   return !nsfw || (nsfw && myShowNsfw);
1496 }
1497
1498 export function getRandomFromList<T>(list: T[]): T | undefined {
1499   return list.length == 0
1500     ? undefined
1501     : list.at(Math.floor(Math.random() * list.length));
1502 }
1503
1504 /**
1505  * This shows what language you can select
1506  *
1507  * Use showAll for the site form
1508  * Use showSite for the profile and community forms
1509  * Use false for both those to filter on your profile and site ones
1510  */
1511 export function selectableLanguages(
1512   allLanguages: Language[],
1513   siteLanguages: number[],
1514   showAll?: boolean,
1515   showSite?: boolean,
1516   myUserInfo = UserService.Instance.myUserInfo
1517 ): Language[] {
1518   let allLangIds = allLanguages.map(l => l.id);
1519   let myLangs = myUserInfo?.discussion_languages ?? allLangIds;
1520   myLangs = myLangs.length == 0 ? allLangIds : myLangs;
1521   let siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages;
1522
1523   if (showAll) {
1524     return allLanguages;
1525   } else {
1526     if (showSite) {
1527       return allLanguages.filter(x => siteLangs.includes(x.id));
1528     } else {
1529       return allLanguages
1530         .filter(x => siteLangs.includes(x.id))
1531         .filter(x => myLangs.includes(x.id));
1532     }
1533   }
1534 }
1535
1536 export function uploadImage(image: File): Promise<UploadImageResponse> {
1537   const client = new LemmyHttp(getHttpBase());
1538
1539   return client.uploadImage({ image });
1540 }
1541
1542 interface EmojiMartCategory {
1543   id: string;
1544   name: string;
1545   emojis: EmojiMartCustomEmoji[];
1546 }
1547
1548 interface EmojiMartCustomEmoji {
1549   id: string;
1550   name: string;
1551   keywords: string[];
1552   skins: EmojiMartSkin[];
1553 }
1554
1555 interface EmojiMartSkin {
1556   src: string;
1557 }
1558
1559 const groupBy = <T>(
1560   array: T[],
1561   predicate: (value: T, index: number, array: T[]) => string
1562 ) =>
1563   array.reduce((acc, value, index, array) => {
1564     (acc[predicate(value, index, array)] ||= []).push(value);
1565     return acc;
1566   }, {} as { [key: string]: T[] });
1567
1568 export type QueryParams<T extends Record<string, any>> = {
1569   [key in keyof T]?: string;
1570 };
1571
1572 export function getQueryParams<T extends Record<string, any>>(processors: {
1573   [K in keyof T]: (param: string) => T[K];
1574 }): T {
1575   if (isBrowser()) {
1576     const searchParams = new URLSearchParams(window.location.search);
1577
1578     return Array.from(Object.entries(processors)).reduce(
1579       (acc, [key, process]) => ({
1580         ...acc,
1581         [key]: process(searchParams.get(key)),
1582       }),
1583       {} as T
1584     );
1585   }
1586
1587   return {} as T;
1588 }
1589
1590 export function getQueryString<T extends Record<string, string | undefined>>(
1591   obj: T
1592 ) {
1593   return Object.entries(obj)
1594     .filter(([, val]) => val !== undefined && val !== null)
1595     .reduce(
1596       (acc, [key, val], index) => `${acc}${index > 0 ? "&" : ""}${key}=${val}`,
1597       "?"
1598     );
1599 }
1600
1601 export function isAuthPath(pathname: string) {
1602   return /create_.*|inbox|settings|setup|admin|reports|registration_applications/g.test(
1603     pathname
1604   );
1605 }