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