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