]> Untitled Git - lemmy-ui.git/blob - src/shared/utils.ts
Adding a few more 0.18.0 API changes. (#1324)
[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   return !!new URL(str);
331 }
332
333 export function validInstanceTLD(str: string) {
334   return tldRegex.test(str);
335 }
336
337 export function communityRSSUrl(actorId: string, sort: string): string {
338   const url = new URL(actorId);
339   return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
340 }
341
342 export function validEmail(email: string) {
343   const re =
344     /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
345   return re.test(String(email).toLowerCase());
346 }
347
348 export function capitalizeFirstLetter(str: string): string {
349   return str.charAt(0).toUpperCase() + str.slice(1);
350 }
351
352 export async function getSiteMetadata(url: string) {
353   const form: GetSiteMetadata = { url };
354   const client = new LemmyHttp(getHttpBase());
355   return client.getSiteMetadata(form);
356 }
357
358 export function getDataTypeString(dt: DataType) {
359   return dt === DataType.Post ? "Post" : "Comment";
360 }
361
362 export function debounce<T extends any[], R>(
363   func: (...e: T) => R,
364   wait = 1000,
365   immediate = false
366 ) {
367   // 'private' variable for instance
368   // The returned function will be able to reference this due to closure.
369   // Each call to the returned function will share this common timer.
370   let timeout: NodeJS.Timeout | null;
371
372   // Calling debounce returns a new anonymous function
373   return function () {
374     // reference the context and args for the setTimeout function
375     const args = arguments;
376
377     // Should the function be called now? If immediate is true
378     //   and not already in a timeout then the answer is: Yes
379     const callNow = immediate && !timeout;
380
381     // This is the basic debounce behavior where you can call this
382     //   function several times, but it will only execute once
383     //   [before or after imposing a delay].
384     //   Each time the returned function is called, the timer starts over.
385     clearTimeout(timeout ?? undefined);
386
387     // Set the new timeout
388     timeout = setTimeout(function () {
389       // Inside the timeout function, clear the timeout variable
390       // which will let the next execution run when in 'immediate' mode
391       timeout = null;
392
393       // Check if the function already ran with the immediate flag
394       if (!immediate) {
395         // Call the original function with apply
396         // apply lets you define the 'this' object as well as the arguments
397         //    (both captured before setTimeout)
398         func.apply(this, args);
399       }
400     }, wait);
401
402     // Immediate mode and no wait timer? Execute the function..
403     if (callNow) func.apply(this, args);
404   } as (...e: T) => R;
405 }
406
407 export async function fetchThemeList(): Promise<string[]> {
408   return fetch("/css/themelist").then(res => res.json());
409 }
410
411 export async function setTheme(theme: string, forceReload = false) {
412   if (!isBrowser()) {
413     return;
414   }
415   if (theme === "browser" && !forceReload) {
416     return;
417   }
418   // This is only run on a force reload
419   if (theme == "browser") {
420     theme = "darkly";
421   }
422
423   const themeList = await fetchThemeList();
424
425   // Unload all the other themes
426   for (var i = 0; i < themeList.length; i++) {
427     const styleSheet = document.getElementById(themeList[i]);
428     if (styleSheet) {
429       styleSheet.setAttribute("disabled", "disabled");
430     }
431   }
432
433   document
434     .getElementById("default-light")
435     ?.setAttribute("disabled", "disabled");
436   document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
437
438   // Load the theme dynamically
439   const cssLoc = `/css/themes/${theme}.css`;
440
441   loadCss(theme, cssLoc);
442   document.getElementById(theme)?.removeAttribute("disabled");
443 }
444
445 export function loadCss(id: string, loc: string) {
446   if (!document.getElementById(id)) {
447     var head = document.getElementsByTagName("head")[0];
448     var link = document.createElement("link");
449     link.id = id;
450     link.rel = "stylesheet";
451     link.type = "text/css";
452     link.href = loc;
453     link.media = "all";
454     head.appendChild(link);
455   }
456 }
457
458 export function objectFlip(obj: any) {
459   const ret = {};
460   Object.keys(obj).forEach(key => {
461     ret[obj[key]] = key;
462   });
463   return ret;
464 }
465
466 export function showAvatars(
467   myUserInfo = UserService.Instance.myUserInfo
468 ): boolean {
469   return myUserInfo?.local_user_view.local_user.show_avatars ?? true;
470 }
471
472 export function showScores(
473   myUserInfo = UserService.Instance.myUserInfo
474 ): boolean {
475   return myUserInfo?.local_user_view.local_user.show_scores ?? true;
476 }
477
478 export function isCakeDay(published: string): boolean {
479   // moment(undefined) or moment.utc(undefined) returns the current date/time
480   // moment(null) or moment.utc(null) returns null
481   const createDate = moment.utc(published).local();
482   const currentDate = moment(new Date());
483
484   return (
485     createDate.date() === currentDate.date() &&
486     createDate.month() === currentDate.month() &&
487     createDate.year() !== currentDate.year()
488   );
489 }
490
491 export function toast(text: string, background: ThemeColor = "success") {
492   if (isBrowser()) {
493     const backgroundColor = `var(--${background})`;
494     Toastify({
495       text: text,
496       backgroundColor: backgroundColor,
497       gravity: "bottom",
498       position: "left",
499       duration: 5000,
500     }).showToast();
501   }
502 }
503
504 export function pictrsDeleteToast(filename: string, deleteUrl: string) {
505   if (isBrowser()) {
506     const clickToDeleteText = i18n.t("click_to_delete_picture", { filename });
507     const deletePictureText = i18n.t("picture_deleted", {
508       filename,
509     });
510     const failedDeletePictureText = i18n.t("failed_to_delete_picture", {
511       filename,
512     });
513
514     const backgroundColor = `var(--light)`;
515
516     const toast = Toastify({
517       text: clickToDeleteText,
518       backgroundColor: backgroundColor,
519       gravity: "top",
520       position: "right",
521       duration: 10000,
522       onClick: () => {
523         if (toast) {
524           fetch(deleteUrl).then(res => {
525             toast.hideToast();
526             if (res.ok === true) {
527               alert(deletePictureText);
528             } else {
529               alert(failedDeletePictureText);
530             }
531           });
532         }
533       },
534       close: true,
535     });
536
537     toast.showToast();
538   }
539 }
540
541 export function setupTribute() {
542   return new Tribute({
543     noMatchTemplate: function () {
544       return "";
545     },
546     collection: [
547       // Emojis
548       {
549         trigger: ":",
550         menuItemTemplate: (item: any) => {
551           const shortName = `:${item.original.key}:`;
552           return `${item.original.val} ${shortName}`;
553         },
554         selectTemplate: (item: any) => {
555           const customEmoji = customEmojisLookup.get(
556             item.original.key
557           )?.custom_emoji;
558           if (customEmoji == undefined) return `${item.original.val}`;
559           else
560             return `![${customEmoji.alt_text}](${customEmoji.image_url} "${customEmoji.shortcode}")`;
561         },
562         values: Object.entries(emojiShortName)
563           .map(e => {
564             return { key: e[1], val: e[0] };
565           })
566           .concat(
567             Array.from(customEmojisLookup.entries()).map(k => ({
568               key: k[0],
569               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}" />`,
570             }))
571           ),
572         allowSpaces: false,
573         autocompleteMode: true,
574         // TODO
575         // menuItemLimit: mentionDropdownFetchLimit,
576         menuShowMinLength: 2,
577       },
578       // Persons
579       {
580         trigger: "@",
581         selectTemplate: (item: any) => {
582           const it: PersonTribute = item.original;
583           return `[${it.key}](${it.view.person.actor_id})`;
584         },
585         values: debounce(async (text: string, cb: any) => {
586           cb(await personSearch(text));
587         }),
588         allowSpaces: false,
589         autocompleteMode: true,
590         // TODO
591         // menuItemLimit: mentionDropdownFetchLimit,
592         menuShowMinLength: 2,
593       },
594
595       // Communities
596       {
597         trigger: "!",
598         selectTemplate: (item: any) => {
599           const it: CommunityTribute = item.original;
600           return `[${it.key}](${it.view.community.actor_id})`;
601         },
602         values: debounce(async (text: string, cb: any) => {
603           cb(await communitySearch(text));
604         }),
605         allowSpaces: false,
606         autocompleteMode: true,
607         // TODO
608         // menuItemLimit: mentionDropdownFetchLimit,
609         menuShowMinLength: 2,
610       },
611     ],
612   });
613 }
614
615 function setupEmojiDataModel(custom_emoji_views: CustomEmojiView[]) {
616   const groupedEmojis = groupBy(
617     custom_emoji_views,
618     x => x.custom_emoji.category
619   );
620   for (const [category, emojis] of Object.entries(groupedEmojis)) {
621     customEmojis.push({
622       id: category,
623       name: category,
624       emojis: emojis.map(emoji => ({
625         id: emoji.custom_emoji.shortcode,
626         name: emoji.custom_emoji.shortcode,
627         keywords: emoji.keywords.map(x => x.keyword),
628         skins: [{ src: emoji.custom_emoji.image_url }],
629       })),
630     });
631   }
632   customEmojisLookup = new Map(
633     custom_emoji_views.map(view => [view.custom_emoji.shortcode, view])
634   );
635 }
636
637 export function updateEmojiDataModel(custom_emoji_view: CustomEmojiView) {
638   const emoji: EmojiMartCustomEmoji = {
639     id: custom_emoji_view.custom_emoji.shortcode,
640     name: custom_emoji_view.custom_emoji.shortcode,
641     keywords: custom_emoji_view.keywords.map(x => x.keyword),
642     skins: [{ src: custom_emoji_view.custom_emoji.image_url }],
643   };
644   const categoryIndex = customEmojis.findIndex(
645     x => x.id == custom_emoji_view.custom_emoji.category
646   );
647   if (categoryIndex == -1) {
648     customEmojis.push({
649       id: custom_emoji_view.custom_emoji.category,
650       name: custom_emoji_view.custom_emoji.category,
651       emojis: [emoji],
652     });
653   } else {
654     const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
655       x => x.id == custom_emoji_view.custom_emoji.shortcode
656     );
657     if (emojiIndex == -1) {
658       customEmojis[categoryIndex].emojis.push(emoji);
659     } else {
660       customEmojis[categoryIndex].emojis[emojiIndex] = emoji;
661     }
662   }
663   customEmojisLookup.set(
664     custom_emoji_view.custom_emoji.shortcode,
665     custom_emoji_view
666   );
667 }
668
669 export function removeFromEmojiDataModel(id: number) {
670   let view: CustomEmojiView | undefined;
671   for (const item of customEmojisLookup.values()) {
672     if (item.custom_emoji.id === id) {
673       view = item;
674       break;
675     }
676   }
677   if (!view) return;
678   const categoryIndex = customEmojis.findIndex(
679     x => x.id == view?.custom_emoji.category
680   );
681   const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
682     x => x.id == view?.custom_emoji.shortcode
683   );
684   customEmojis[categoryIndex].emojis = customEmojis[
685     categoryIndex
686   ].emojis.splice(emojiIndex, 1);
687
688   customEmojisLookup.delete(view?.custom_emoji.shortcode);
689 }
690
691 function setupMarkdown() {
692   const markdownItConfig: MarkdownIt.Options = {
693     html: false,
694     linkify: true,
695     typographer: true,
696   };
697
698   const emojiDefs = Array.from(customEmojisLookup.entries()).reduce(
699     (main, [key, value]) => ({ ...main, [key]: value }),
700     {}
701   );
702   md = new MarkdownIt(markdownItConfig)
703     .use(markdown_it_sub)
704     .use(markdown_it_sup)
705     .use(markdown_it_footnote)
706     .use(markdown_it_html5_embed, html5EmbedConfig)
707     .use(markdown_it_container, "spoiler", spoilerConfig)
708     .use(markdown_it_emoji, {
709       defs: emojiDefs,
710     });
711
712   mdNoImages = new MarkdownIt(markdownItConfig)
713     .use(markdown_it_sub)
714     .use(markdown_it_sup)
715     .use(markdown_it_footnote)
716     .use(markdown_it_html5_embed, html5EmbedConfig)
717     .use(markdown_it_container, "spoiler", spoilerConfig)
718     .use(markdown_it_emoji, {
719       defs: emojiDefs,
720     })
721     .disable("image");
722   const defaultRenderer = md.renderer.rules.image;
723   md.renderer.rules.image = function (
724     tokens: Token[],
725     idx: number,
726     options: MarkdownIt.Options,
727     env: any,
728     self: Renderer
729   ) {
730     //Provide custom renderer for our emojis to allow us to add a css class and force size dimensions on them.
731     const item = tokens[idx] as any;
732     const title = item.attrs.length >= 3 ? item.attrs[2][1] : "";
733     const src: string = item.attrs[0][1];
734     const isCustomEmoji = customEmojisLookup.get(title) != undefined;
735     if (!isCustomEmoji) {
736       return defaultRenderer?.(tokens, idx, options, env, self) ?? "";
737     }
738     const alt_text = item.content;
739     return `<img class="icon icon-emoji" src="${src}" title="${title}" alt="${alt_text}"/>`;
740   };
741   md.renderer.rules.table_open = function () {
742     return '<table class="table">';
743   };
744 }
745
746 export function getEmojiMart(
747   onEmojiSelect: (e: any) => void,
748   customPickerOptions: any = {}
749 ) {
750   const pickerOptions = {
751     ...customPickerOptions,
752     onEmojiSelect: onEmojiSelect,
753     custom: customEmojis,
754   };
755   return new Picker(pickerOptions);
756 }
757
758 var tippyInstance: any;
759 if (isBrowser()) {
760   tippyInstance = tippy("[data-tippy-content]");
761 }
762
763 export function setupTippy() {
764   if (isBrowser()) {
765     tippyInstance.forEach((e: any) => e.destroy());
766     tippyInstance = tippy("[data-tippy-content]", {
767       delay: [500, 0],
768       // Display on "long press"
769       touch: ["hold", 500],
770     });
771   }
772 }
773
774 interface PersonTribute {
775   key: string;
776   view: PersonView;
777 }
778
779 async function personSearch(text: string): Promise<PersonTribute[]> {
780   const usersResponse = await fetchUsers(text);
781
782   return usersResponse.map(pv => ({
783     key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
784     view: pv,
785   }));
786 }
787
788 interface CommunityTribute {
789   key: string;
790   view: CommunityView;
791 }
792
793 async function communitySearch(text: string): Promise<CommunityTribute[]> {
794   const communitiesResponse = await fetchCommunities(text);
795
796   return communitiesResponse.map(cv => ({
797     key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
798     view: cv,
799   }));
800 }
801
802 export function getRecipientIdFromProps(props: any): number {
803   return props.match.params.recipient_id
804     ? Number(props.match.params.recipient_id)
805     : 1;
806 }
807
808 export function getIdFromProps(props: any): number | undefined {
809   const id = props.match.params.post_id;
810   return id ? Number(id) : undefined;
811 }
812
813 export function getCommentIdFromProps(props: any): number | undefined {
814   const id = props.match.params.comment_id;
815   return id ? Number(id) : undefined;
816 }
817
818 type ImmutableListKey =
819   | "comment"
820   | "comment_reply"
821   | "person_mention"
822   | "community"
823   | "private_message"
824   | "post"
825   | "post_report"
826   | "comment_report"
827   | "private_message_report"
828   | "registration_application";
829
830 function editListImmutable<
831   T extends { [key in F]: { id: number } },
832   F extends ImmutableListKey
833 >(fieldName: F, data: T, list: T[]): T[] {
834   return [
835     ...list.map(c => (c[fieldName].id === data[fieldName].id ? data : c)),
836   ];
837 }
838
839 export function editComment(
840   data: CommentView,
841   comments: CommentView[]
842 ): CommentView[] {
843   return editListImmutable("comment", data, comments);
844 }
845
846 export function editCommentReply(
847   data: CommentReplyView,
848   replies: CommentReplyView[]
849 ): CommentReplyView[] {
850   return editListImmutable("comment_reply", data, replies);
851 }
852
853 interface WithComment {
854   comment: CommentI;
855   counts: CommentAggregates;
856   my_vote?: number;
857   saved: boolean;
858 }
859
860 export function editMention(
861   data: PersonMentionView,
862   comments: PersonMentionView[]
863 ): PersonMentionView[] {
864   return editListImmutable("person_mention", data, comments);
865 }
866
867 export function editCommunity(
868   data: CommunityView,
869   communities: CommunityView[]
870 ): CommunityView[] {
871   return editListImmutable("community", data, communities);
872 }
873
874 export function editPrivateMessage(
875   data: PrivateMessageView,
876   messages: PrivateMessageView[]
877 ): PrivateMessageView[] {
878   return editListImmutable("private_message", data, messages);
879 }
880
881 export function editPost(data: PostView, posts: PostView[]): PostView[] {
882   return editListImmutable("post", data, posts);
883 }
884
885 export function editPostReport(
886   data: PostReportView,
887   reports: PostReportView[]
888 ) {
889   return editListImmutable("post_report", data, reports);
890 }
891
892 export function editCommentReport(
893   data: CommentReportView,
894   reports: CommentReportView[]
895 ): CommentReportView[] {
896   return editListImmutable("comment_report", data, reports);
897 }
898
899 export function editPrivateMessageReport(
900   data: PrivateMessageReportView,
901   reports: PrivateMessageReportView[]
902 ): PrivateMessageReportView[] {
903   return editListImmutable("private_message_report", data, reports);
904 }
905
906 export function editRegistrationApplication(
907   data: RegistrationApplicationView,
908   apps: RegistrationApplicationView[]
909 ): RegistrationApplicationView[] {
910   return editListImmutable("registration_application", data, apps);
911 }
912
913 export function editWith<D extends WithComment, L extends WithComment>(
914   { comment, counts, saved, my_vote }: D,
915   list: L[]
916 ) {
917   return [
918     ...list.map(c =>
919       c.comment.id === comment.id
920         ? { ...c, comment, counts, saved, my_vote }
921         : c
922     ),
923   ];
924 }
925
926 export function updatePersonBlock(
927   data: BlockPersonResponse,
928   myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
929 ) {
930   if (myUserInfo) {
931     if (data.blocked) {
932       myUserInfo.person_blocks.push({
933         person: myUserInfo.local_user_view.person,
934         target: data.person_view.person,
935       });
936       toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
937     } else {
938       myUserInfo.person_blocks = myUserInfo.person_blocks.filter(
939         i => i.target.id !== data.person_view.person.id
940       );
941       toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
942     }
943   }
944 }
945
946 export function updateCommunityBlock(
947   data: BlockCommunityResponse,
948   myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
949 ) {
950   if (myUserInfo) {
951     if (data.blocked) {
952       myUserInfo.community_blocks.push({
953         person: myUserInfo.local_user_view.person,
954         community: data.community_view.community,
955       });
956       toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
957     } else {
958       myUserInfo.community_blocks = myUserInfo.community_blocks.filter(
959         i => i.community.id !== data.community_view.community.id
960       );
961       toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
962     }
963   }
964 }
965
966 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
967   const nodes: CommentNodeI[] = [];
968   for (const comment of comments) {
969     nodes.push({ comment_view: comment, children: [], depth: 0 });
970   }
971   return nodes;
972 }
973
974 export function convertCommentSortType(sort: SortType): CommentSortType {
975   if (
976     sort == "TopAll" ||
977     sort == "TopDay" ||
978     sort == "TopWeek" ||
979     sort == "TopMonth" ||
980     sort == "TopYear"
981   ) {
982     return "Top";
983   } else if (sort == "New") {
984     return "New";
985   } else if (sort == "Hot" || sort == "Active") {
986     return "Hot";
987   } else {
988     return "Hot";
989   }
990 }
991
992 export function buildCommentsTree(
993   comments: CommentView[],
994   parentComment: boolean
995 ): CommentNodeI[] {
996   const map = new Map<number, CommentNodeI>();
997   const depthOffset = !parentComment
998     ? 0
999     : getDepthFromComment(comments[0].comment) ?? 0;
1000
1001   for (const comment_view of comments) {
1002     const depthI = getDepthFromComment(comment_view.comment) ?? 0;
1003     const depth = depthI ? depthI - depthOffset : 0;
1004     const node: CommentNodeI = {
1005       comment_view,
1006       children: [],
1007       depth,
1008     };
1009     map.set(comment_view.comment.id, { ...node });
1010   }
1011
1012   const tree: CommentNodeI[] = [];
1013
1014   // if its a parent comment fetch, then push the first comment to the top node.
1015   if (parentComment) {
1016     const cNode = map.get(comments[0].comment.id);
1017     if (cNode) {
1018       tree.push(cNode);
1019     }
1020   }
1021
1022   for (const comment_view of comments) {
1023     const child = map.get(comment_view.comment.id);
1024     if (child) {
1025       const parent_id = getCommentParentId(comment_view.comment);
1026       if (parent_id) {
1027         const parent = map.get(parent_id);
1028         // Necessary because blocked comment might not exist
1029         if (parent) {
1030           parent.children.push(child);
1031         }
1032       } else {
1033         if (!parentComment) {
1034           tree.push(child);
1035         }
1036       }
1037     }
1038   }
1039
1040   return tree;
1041 }
1042
1043 export function getCommentParentId(comment?: CommentI): number | undefined {
1044   const split = comment?.path.split(".");
1045   // remove the 0
1046   split?.shift();
1047
1048   return split && split.length > 1
1049     ? Number(split.at(split.length - 2))
1050     : undefined;
1051 }
1052
1053 export function getDepthFromComment(comment?: CommentI): number | undefined {
1054   const len = comment?.path.split(".").length;
1055   return len ? len - 2 : undefined;
1056 }
1057
1058 // TODO make immutable
1059 export function insertCommentIntoTree(
1060   tree: CommentNodeI[],
1061   cv: CommentView,
1062   parentComment: boolean
1063 ) {
1064   // Building a fake node to be used for later
1065   const node: CommentNodeI = {
1066     comment_view: cv,
1067     children: [],
1068     depth: 0,
1069   };
1070
1071   const parentId = getCommentParentId(cv.comment);
1072   if (parentId) {
1073     const parent_comment = searchCommentTree(tree, parentId);
1074     if (parent_comment) {
1075       node.depth = parent_comment.depth + 1;
1076       parent_comment.children.unshift(node);
1077     }
1078   } else if (!parentComment) {
1079     tree.unshift(node);
1080   }
1081 }
1082
1083 export function searchCommentTree(
1084   tree: CommentNodeI[],
1085   id: number
1086 ): CommentNodeI | undefined {
1087   for (const node of tree) {
1088     if (node.comment_view.comment.id === id) {
1089       return node;
1090     }
1091
1092     for (const child of node.children) {
1093       const res = searchCommentTree([child], id);
1094
1095       if (res) {
1096         return res;
1097       }
1098     }
1099   }
1100   return undefined;
1101 }
1102
1103 export const colorList: string[] = [
1104   hsl(0),
1105   hsl(50),
1106   hsl(100),
1107   hsl(150),
1108   hsl(200),
1109   hsl(250),
1110   hsl(300),
1111 ];
1112
1113 function hsl(num: number) {
1114   return `hsla(${num}, 35%, 50%, 0.5)`;
1115 }
1116
1117 export function hostname(url: string): string {
1118   const cUrl = new URL(url);
1119   return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1120 }
1121
1122 export function validTitle(title?: string): boolean {
1123   // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1124   if (!title || title.length < 3) return true;
1125
1126   const regex = new RegExp(/.*\S.*/, "g");
1127
1128   return regex.test(title);
1129 }
1130
1131 export function siteBannerCss(banner: string): string {
1132   return ` \
1133     background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1134     background-attachment: fixed; \
1135     background-position: top; \
1136     background-repeat: no-repeat; \
1137     background-size: 100% cover; \
1138
1139     width: 100%; \
1140     max-height: 100vh; \
1141     `;
1142 }
1143
1144 export function isBrowser() {
1145   return typeof window !== "undefined";
1146 }
1147
1148 export function setIsoData(context: any): IsoData {
1149   // If its the browser, you need to deserialize the data from the window
1150   if (isBrowser()) {
1151     return window.isoData;
1152   } else return context.router.staticContext;
1153 }
1154
1155 moment.updateLocale("en", {
1156   relativeTime: {
1157     future: "in %s",
1158     past: "%s ago",
1159     s: "<1m",
1160     ss: "%ds",
1161     m: "1m",
1162     mm: "%dm",
1163     h: "1h",
1164     hh: "%dh",
1165     d: "1d",
1166     dd: "%dd",
1167     w: "1w",
1168     ww: "%dw",
1169     M: "1M",
1170     MM: "%dM",
1171     y: "1Y",
1172     yy: "%dY",
1173   },
1174 });
1175
1176 export function saveScrollPosition(context: any) {
1177   const path: string = context.router.route.location.pathname;
1178   const y = window.scrollY;
1179   sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1180 }
1181
1182 export function restoreScrollPosition(context: any) {
1183   const path: string = context.router.route.location.pathname;
1184   const y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1185   window.scrollTo(0, y);
1186 }
1187
1188 export function showLocal(isoData: IsoData): boolean {
1189   return isoData.site_res.site_view.local_site.federation_enabled;
1190 }
1191
1192 export interface Choice {
1193   value: string;
1194   label: string;
1195   disabled?: boolean;
1196 }
1197
1198 export function getUpdatedSearchId(id?: number | null, urlId?: number | null) {
1199   return id === null
1200     ? undefined
1201     : ((id ?? urlId) === 0 ? undefined : id ?? urlId)?.toString();
1202 }
1203
1204 export function communityToChoice(cv: CommunityView): Choice {
1205   return {
1206     value: cv.community.id.toString(),
1207     label: communitySelectName(cv),
1208   };
1209 }
1210
1211 export function personToChoice(pvs: PersonView): Choice {
1212   return {
1213     value: pvs.person.id.toString(),
1214     label: personSelectName(pvs),
1215   };
1216 }
1217
1218 function fetchSearchResults(q: string, type_: SearchType) {
1219   const form: Search = {
1220     q,
1221     type_,
1222     sort: "TopAll",
1223     listing_type: "All",
1224     page: 1,
1225     limit: fetchLimit,
1226     auth: myAuth(),
1227   };
1228
1229   return HttpService.client.search(form);
1230 }
1231
1232 export async function fetchCommunities(q: string) {
1233   const res = await fetchSearchResults(q, "Communities");
1234
1235   return res.state === "success" ? res.data.communities : [];
1236 }
1237
1238 export async function fetchUsers(q: string) {
1239   const res = await fetchSearchResults(q, "Users");
1240
1241   return res.state === "success" ? res.data.users : [];
1242 }
1243
1244 export function communitySelectName(cv: CommunityView): string {
1245   return cv.community.local
1246     ? cv.community.title
1247     : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1248 }
1249
1250 export function personSelectName({
1251   person: { display_name, name, local, actor_id },
1252 }: PersonView): string {
1253   const pName = display_name ?? name;
1254   return local ? pName : `${hostname(actor_id)}/${pName}`;
1255 }
1256
1257 export function initializeSite(site?: GetSiteResponse) {
1258   UserService.Instance.myUserInfo = site?.my_user;
1259   i18n.changeLanguage();
1260   if (site) {
1261     setupEmojiDataModel(site.custom_emojis ?? []);
1262   }
1263   setupMarkdown();
1264 }
1265
1266 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1267   maximumSignificantDigits: 3,
1268   //@ts-ignore
1269   notation: "compact",
1270   compactDisplay: "short",
1271 });
1272
1273 export function numToSI(value: number): string {
1274   return SHORTNUM_SI_FORMAT.format(value);
1275 }
1276
1277 export function isBanned(ps: Person): boolean {
1278   const expires = ps.ban_expires;
1279   // Add Z to convert from UTC date
1280   // TODO this check probably isn't necessary anymore
1281   if (expires) {
1282     if (ps.banned && new Date(expires + "Z") > new Date()) {
1283       return true;
1284     } else {
1285       return false;
1286     }
1287   } else {
1288     return ps.banned;
1289   }
1290 }
1291
1292 export function myAuth(): string | undefined {
1293   return UserService.Instance.auth();
1294 }
1295
1296 export function myAuthRequired(): string {
1297   return UserService.Instance.auth(true) ?? "";
1298 }
1299
1300 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1301   return siteRes.site_view.local_site.enable_downvotes;
1302 }
1303
1304 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1305   return siteRes.site_view.local_site.enable_nsfw;
1306 }
1307
1308 export function postToCommentSortType(sort: SortType): CommentSortType {
1309   switch (sort) {
1310     case "Active":
1311     case "Hot":
1312       return "Hot";
1313     case "New":
1314     case "NewComments":
1315       return "New";
1316     case "Old":
1317       return "Old";
1318     default:
1319       return "Top";
1320   }
1321 }
1322
1323 export function canCreateCommunity(
1324   siteRes: GetSiteResponse,
1325   myUserInfo = UserService.Instance.myUserInfo
1326 ): boolean {
1327   const adminOnly = siteRes.site_view.local_site.community_creation_admin_only;
1328   // TODO: Make this check if user is logged on as well
1329   return !adminOnly || amAdmin(myUserInfo);
1330 }
1331
1332 export function isPostBlocked(
1333   pv: PostView,
1334   myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
1335 ): boolean {
1336   return (
1337     (myUserInfo?.community_blocks
1338       .map(c => c.community.id)
1339       .includes(pv.community.id) ||
1340       myUserInfo?.person_blocks
1341         .map(p => p.target.id)
1342         .includes(pv.creator.id)) ??
1343     false
1344   );
1345 }
1346
1347 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1348 export function nsfwCheck(
1349   pv: PostView,
1350   myUserInfo = UserService.Instance.myUserInfo
1351 ): boolean {
1352   const nsfw = pv.post.nsfw || pv.community.nsfw;
1353   const myShowNsfw = myUserInfo?.local_user_view.local_user.show_nsfw ?? false;
1354   return !nsfw || (nsfw && myShowNsfw);
1355 }
1356
1357 export function getRandomFromList<T>(list: T[]): T | undefined {
1358   return list.length == 0
1359     ? undefined
1360     : list.at(Math.floor(Math.random() * list.length));
1361 }
1362
1363 /**
1364  * This shows what language you can select
1365  *
1366  * Use showAll for the site form
1367  * Use showSite for the profile and community forms
1368  * Use false for both those to filter on your profile and site ones
1369  */
1370 export function selectableLanguages(
1371   allLanguages: Language[],
1372   siteLanguages: number[],
1373   showAll?: boolean,
1374   showSite?: boolean,
1375   myUserInfo = UserService.Instance.myUserInfo
1376 ): Language[] {
1377   const allLangIds = allLanguages.map(l => l.id);
1378   let myLangs = myUserInfo?.discussion_languages ?? allLangIds;
1379   myLangs = myLangs.length == 0 ? allLangIds : myLangs;
1380   const siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages;
1381
1382   if (showAll) {
1383     return allLanguages;
1384   } else {
1385     if (showSite) {
1386       return allLanguages.filter(x => siteLangs.includes(x.id));
1387     } else {
1388       return allLanguages
1389         .filter(x => siteLangs.includes(x.id))
1390         .filter(x => myLangs.includes(x.id));
1391     }
1392   }
1393 }
1394
1395 interface EmojiMartCategory {
1396   id: string;
1397   name: string;
1398   emojis: EmojiMartCustomEmoji[];
1399 }
1400
1401 interface EmojiMartCustomEmoji {
1402   id: string;
1403   name: string;
1404   keywords: string[];
1405   skins: EmojiMartSkin[];
1406 }
1407
1408 interface EmojiMartSkin {
1409   src: string;
1410 }
1411
1412 const groupBy = <T>(
1413   array: T[],
1414   predicate: (value: T, index: number, array: T[]) => string
1415 ) =>
1416   array.reduce((acc, value, index, array) => {
1417     (acc[predicate(value, index, array)] ||= []).push(value);
1418     return acc;
1419   }, {} as { [key: string]: T[] });
1420
1421 export type QueryParams<T extends Record<string, any>> = {
1422   [key in keyof T]?: string;
1423 };
1424
1425 export function getQueryParams<T extends Record<string, any>>(processors: {
1426   [K in keyof T]: (param: string) => T[K];
1427 }): T {
1428   if (isBrowser()) {
1429     const searchParams = new URLSearchParams(window.location.search);
1430
1431     return Array.from(Object.entries(processors)).reduce(
1432       (acc, [key, process]) => ({
1433         ...acc,
1434         [key]: process(searchParams.get(key)),
1435       }),
1436       {} as T
1437     );
1438   }
1439
1440   return {} as T;
1441 }
1442
1443 export function getQueryString<T extends Record<string, string | undefined>>(
1444   obj: T
1445 ) {
1446   return Object.entries(obj)
1447     .filter(([, val]) => val !== undefined && val !== null)
1448     .reduce(
1449       (acc, [key, val], index) => `${acc}${index > 0 ? "&" : ""}${key}=${val}`,
1450       "?"
1451     );
1452 }
1453
1454 export function isAuthPath(pathname: string) {
1455   return /create_.*|inbox|settings|admin|reports|registration_applications/g.test(
1456     pathname
1457   );
1458 }
1459
1460 export function canShare() {
1461   return isBrowser() && !!navigator.canShare;
1462 }
1463
1464 export function share(shareData: ShareData) {
1465   if (isBrowser()) {
1466     navigator.share(shareData);
1467   }
1468 }
1469
1470 export function newVote(voteType: VoteType, myVote?: number): number {
1471   if (voteType == VoteType.Upvote) {
1472     return myVote == 1 ? 0 : 1;
1473   } else {
1474     return myVote == -1 ? 0 : -1;
1475   }
1476 }
1477
1478 function sleep(millis: number): Promise<void> {
1479   return new Promise(resolve => setTimeout(resolve, millis));
1480 }
1481
1482 /**
1483  * Polls / repeatedly runs a promise, every X milliseconds
1484  */
1485 export async function poll(promiseFn: any, millis: number) {
1486   if (window.document.visibilityState !== "hidden") {
1487     await promiseFn();
1488   }
1489   await sleep(millis);
1490   return poll(promiseFn, millis);
1491 }