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