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