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