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