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