]> Untitled Git - lemmy-ui.git/blob - src/shared/utils.ts
c0caad88a385d10e3996b9248888d6efa19430dd
[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   CommunityView,
13   CustomEmojiView,
14   GetSiteMetadata,
15   GetSiteResponse,
16   Language,
17   LemmyHttp,
18   MyUserInfo,
19   PersonMentionView,
20   PersonView,
21   PostReportView,
22   PostView,
23   PrivateMessageReportView,
24   PrivateMessageView,
25   RegistrationApplicationView,
26   Search,
27   SearchType,
28   SortType,
29 } from "lemmy-js-client";
30 import { default as MarkdownIt } from "markdown-it";
31 import markdown_it_container from "markdown-it-container";
32 import markdown_it_emoji from "markdown-it-emoji/bare";
33 import markdown_it_footnote from "markdown-it-footnote";
34 import markdown_it_html5_embed from "markdown-it-html5-embed";
35 import markdown_it_sub from "markdown-it-sub";
36 import markdown_it_sup from "markdown-it-sup";
37 import Renderer from "markdown-it/lib/renderer";
38 import Token from "markdown-it/lib/token";
39 import moment from "moment";
40 import tippy from "tippy.js";
41 import Toastify from "toastify-js";
42 import { getHttpBase } from "./env";
43 import { i18n, languages } from "./i18next";
44 import { CommentNodeI, DataType, IsoData, VoteType } from "./interfaces";
45 import { HttpService, UserService } from "./services";
46 import { isBrowser } from "./utils/browser/is-browser";
47 import { debounce } from "./utils/helpers/debounce";
48 import { groupBy } from "./utils/helpers/group-by";
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 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
233 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
234
235 export function isImage(url: string) {
236   return imageRegex.test(url);
237 }
238
239 export function isVideo(url: string) {
240   return videoRegex.test(url);
241 }
242
243 export function validURL(str: string) {
244   return !!new URL(str);
245 }
246
247 export function communityRSSUrl(actorId: string, sort: string): string {
248   const url = new URL(actorId);
249   return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
250 }
251
252 export function validEmail(email: string) {
253   const re =
254     /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
255   return re.test(String(email).toLowerCase());
256 }
257
258 export function capitalizeFirstLetter(str: string): string {
259   return str.charAt(0).toUpperCase() + str.slice(1);
260 }
261
262 export async function getSiteMetadata(url: string) {
263   const form: GetSiteMetadata = { url };
264   const client = new LemmyHttp(getHttpBase());
265   return client.getSiteMetadata(form);
266 }
267
268 export function getDataTypeString(dt: DataType) {
269   return dt === DataType.Post ? "Post" : "Comment";
270 }
271
272 export function getLanguages(
273   override?: string,
274   myUserInfo = UserService.Instance.myUserInfo
275 ): string[] {
276   const myLang = myUserInfo?.local_user_view.local_user.interface_language;
277   const lang = override || myLang || "browser";
278
279   if (lang == "browser" && isBrowser()) {
280     return getBrowserLanguages();
281   } else {
282     return [lang];
283   }
284 }
285
286 function getBrowserLanguages(): string[] {
287   // Intersect lemmy's langs, with the browser langs
288   const langs = languages ? languages.map(l => l.code) : ["en"];
289
290   // NOTE, mobile browsers seem to be missing this list, so append en
291   const allowedLangs = navigator.languages
292     .concat("en")
293     .filter(v => langs.includes(v));
294   return allowedLangs;
295 }
296
297 export async function fetchThemeList(): Promise<string[]> {
298   return fetch("/css/themelist").then(res => res.json());
299 }
300
301 export async function setTheme(theme: string, forceReload = false) {
302   if (!isBrowser()) {
303     return;
304   }
305   if (theme === "browser" && !forceReload) {
306     return;
307   }
308   // This is only run on a force reload
309   if (theme == "browser") {
310     theme = "darkly";
311   }
312
313   const themeList = await fetchThemeList();
314
315   // Unload all the other themes
316   for (var i = 0; i < themeList.length; i++) {
317     const styleSheet = document.getElementById(themeList[i]);
318     if (styleSheet) {
319       styleSheet.setAttribute("disabled", "disabled");
320     }
321   }
322
323   document
324     .getElementById("default-light")
325     ?.setAttribute("disabled", "disabled");
326   document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
327
328   // Load the theme dynamically
329   const cssLoc = `/css/themes/${theme}.css`;
330
331   loadCss(theme, cssLoc);
332   document.getElementById(theme)?.removeAttribute("disabled");
333 }
334
335 export function loadCss(id: string, loc: string) {
336   if (!document.getElementById(id)) {
337     var head = document.getElementsByTagName("head")[0];
338     var link = document.createElement("link");
339     link.id = id;
340     link.rel = "stylesheet";
341     link.type = "text/css";
342     link.href = loc;
343     link.media = "all";
344     head.appendChild(link);
345   }
346 }
347
348 export function objectFlip(obj: any) {
349   const ret = {};
350   Object.keys(obj).forEach(key => {
351     ret[obj[key]] = key;
352   });
353   return ret;
354 }
355
356 export function showAvatars(
357   myUserInfo = UserService.Instance.myUserInfo
358 ): boolean {
359   return myUserInfo?.local_user_view.local_user.show_avatars ?? true;
360 }
361
362 export function showScores(
363   myUserInfo = UserService.Instance.myUserInfo
364 ): boolean {
365   return myUserInfo?.local_user_view.local_user.show_scores ?? true;
366 }
367
368 export function isCakeDay(published: string): boolean {
369   // moment(undefined) or moment.utc(undefined) returns the current date/time
370   // moment(null) or moment.utc(null) returns null
371   const createDate = moment.utc(published).local();
372   const currentDate = moment(new Date());
373
374   return (
375     createDate.date() === currentDate.date() &&
376     createDate.month() === currentDate.month() &&
377     createDate.year() !== currentDate.year()
378   );
379 }
380
381 export function toast(text: string, background: ThemeColor = "success") {
382   if (isBrowser()) {
383     const backgroundColor = `var(--${background})`;
384     Toastify({
385       text: text,
386       backgroundColor: backgroundColor,
387       gravity: "bottom",
388       position: "left",
389       duration: 5000,
390     }).showToast();
391   }
392 }
393
394 export function pictrsDeleteToast(filename: string, deleteUrl: string) {
395   if (isBrowser()) {
396     const clickToDeleteText = i18n.t("click_to_delete_picture", { filename });
397     const deletePictureText = i18n.t("picture_deleted", {
398       filename,
399     });
400     const failedDeletePictureText = i18n.t("failed_to_delete_picture", {
401       filename,
402     });
403
404     const backgroundColor = `var(--light)`;
405
406     const toast = Toastify({
407       text: clickToDeleteText,
408       backgroundColor: backgroundColor,
409       gravity: "top",
410       position: "right",
411       duration: 10000,
412       onClick: () => {
413         if (toast) {
414           fetch(deleteUrl).then(res => {
415             toast.hideToast();
416             if (res.ok === true) {
417               alert(deletePictureText);
418             } else {
419               alert(failedDeletePictureText);
420             }
421           });
422         }
423       },
424       close: true,
425     });
426
427     toast.showToast();
428   }
429 }
430
431 export function setupTribute() {
432   return new Tribute({
433     noMatchTemplate: function () {
434       return "";
435     },
436     collection: [
437       // Emojis
438       {
439         trigger: ":",
440         menuItemTemplate: (item: any) => {
441           const shortName = `:${item.original.key}:`;
442           return `${item.original.val} ${shortName}`;
443         },
444         selectTemplate: (item: any) => {
445           const customEmoji = customEmojisLookup.get(
446             item.original.key
447           )?.custom_emoji;
448           if (customEmoji == undefined) return `${item.original.val}`;
449           else
450             return `![${customEmoji.alt_text}](${customEmoji.image_url} "${customEmoji.shortcode}")`;
451         },
452         values: Object.entries(emojiShortName)
453           .map(e => {
454             return { key: e[1], val: e[0] };
455           })
456           .concat(
457             Array.from(customEmojisLookup.entries()).map(k => ({
458               key: k[0],
459               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}" />`,
460             }))
461           ),
462         allowSpaces: false,
463         autocompleteMode: true,
464         // TODO
465         // menuItemLimit: mentionDropdownFetchLimit,
466         menuShowMinLength: 2,
467       },
468       // Persons
469       {
470         trigger: "@",
471         selectTemplate: (item: any) => {
472           const it: PersonTribute = item.original;
473           return `[${it.key}](${it.view.person.actor_id})`;
474         },
475         values: debounce(async (text: string, cb: any) => {
476           cb(await personSearch(text));
477         }),
478         allowSpaces: false,
479         autocompleteMode: true,
480         // TODO
481         // menuItemLimit: mentionDropdownFetchLimit,
482         menuShowMinLength: 2,
483       },
484
485       // Communities
486       {
487         trigger: "!",
488         selectTemplate: (item: any) => {
489           const it: CommunityTribute = item.original;
490           return `[${it.key}](${it.view.community.actor_id})`;
491         },
492         values: debounce(async (text: string, cb: any) => {
493           cb(await communitySearch(text));
494         }),
495         allowSpaces: false,
496         autocompleteMode: true,
497         // TODO
498         // menuItemLimit: mentionDropdownFetchLimit,
499         menuShowMinLength: 2,
500       },
501     ],
502   });
503 }
504
505 function setupEmojiDataModel(custom_emoji_views: CustomEmojiView[]) {
506   const groupedEmojis = groupBy(
507     custom_emoji_views,
508     x => x.custom_emoji.category
509   );
510   for (const [category, emojis] of Object.entries(groupedEmojis)) {
511     customEmojis.push({
512       id: category,
513       name: category,
514       emojis: emojis.map(emoji => ({
515         id: emoji.custom_emoji.shortcode,
516         name: emoji.custom_emoji.shortcode,
517         keywords: emoji.keywords.map(x => x.keyword),
518         skins: [{ src: emoji.custom_emoji.image_url }],
519       })),
520     });
521   }
522   customEmojisLookup = new Map(
523     custom_emoji_views.map(view => [view.custom_emoji.shortcode, view])
524   );
525 }
526
527 export function updateEmojiDataModel(custom_emoji_view: CustomEmojiView) {
528   const emoji: EmojiMartCustomEmoji = {
529     id: custom_emoji_view.custom_emoji.shortcode,
530     name: custom_emoji_view.custom_emoji.shortcode,
531     keywords: custom_emoji_view.keywords.map(x => x.keyword),
532     skins: [{ src: custom_emoji_view.custom_emoji.image_url }],
533   };
534   const categoryIndex = customEmojis.findIndex(
535     x => x.id == custom_emoji_view.custom_emoji.category
536   );
537   if (categoryIndex == -1) {
538     customEmojis.push({
539       id: custom_emoji_view.custom_emoji.category,
540       name: custom_emoji_view.custom_emoji.category,
541       emojis: [emoji],
542     });
543   } else {
544     const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
545       x => x.id == custom_emoji_view.custom_emoji.shortcode
546     );
547     if (emojiIndex == -1) {
548       customEmojis[categoryIndex].emojis.push(emoji);
549     } else {
550       customEmojis[categoryIndex].emojis[emojiIndex] = emoji;
551     }
552   }
553   customEmojisLookup.set(
554     custom_emoji_view.custom_emoji.shortcode,
555     custom_emoji_view
556   );
557 }
558
559 export function removeFromEmojiDataModel(id: number) {
560   let view: CustomEmojiView | undefined;
561   for (const item of customEmojisLookup.values()) {
562     if (item.custom_emoji.id === id) {
563       view = item;
564       break;
565     }
566   }
567   if (!view) return;
568   const categoryIndex = customEmojis.findIndex(
569     x => x.id == view?.custom_emoji.category
570   );
571   const emojiIndex = customEmojis[categoryIndex].emojis.findIndex(
572     x => x.id == view?.custom_emoji.shortcode
573   );
574   customEmojis[categoryIndex].emojis = customEmojis[
575     categoryIndex
576   ].emojis.splice(emojiIndex, 1);
577
578   customEmojisLookup.delete(view?.custom_emoji.shortcode);
579 }
580
581 function setupMarkdown() {
582   const markdownItConfig: MarkdownIt.Options = {
583     html: false,
584     linkify: true,
585     typographer: true,
586   };
587
588   const emojiDefs = Array.from(customEmojisLookup.entries()).reduce(
589     (main, [key, value]) => ({ ...main, [key]: value }),
590     {}
591   );
592   md = new MarkdownIt(markdownItConfig)
593     .use(markdown_it_sub)
594     .use(markdown_it_sup)
595     .use(markdown_it_footnote)
596     .use(markdown_it_html5_embed, html5EmbedConfig)
597     .use(markdown_it_container, "spoiler", spoilerConfig)
598     .use(markdown_it_emoji, {
599       defs: emojiDefs,
600     });
601
602   mdNoImages = new MarkdownIt(markdownItConfig)
603     .use(markdown_it_sub)
604     .use(markdown_it_sup)
605     .use(markdown_it_footnote)
606     .use(markdown_it_html5_embed, html5EmbedConfig)
607     .use(markdown_it_container, "spoiler", spoilerConfig)
608     .use(markdown_it_emoji, {
609       defs: emojiDefs,
610     })
611     .disable("image");
612   var defaultRenderer = md.renderer.rules.image;
613   md.renderer.rules.image = function (
614     tokens: Token[],
615     idx: number,
616     options: MarkdownIt.Options,
617     env: any,
618     self: Renderer
619   ) {
620     //Provide custom renderer for our emojis to allow us to add a css class and force size dimensions on them.
621     const item = tokens[idx] as any;
622     const title = item.attrs.length >= 3 ? item.attrs[2][1] : "";
623     const src: string = item.attrs[0][1];
624     const isCustomEmoji = customEmojisLookup.get(title) != undefined;
625     if (!isCustomEmoji) {
626       return defaultRenderer?.(tokens, idx, options, env, self) ?? "";
627     }
628     const alt_text = item.content;
629     return `<img class="icon icon-emoji" src="${src}" title="${title}" alt="${alt_text}"/>`;
630   };
631 }
632
633 export function getEmojiMart(
634   onEmojiSelect: (e: any) => void,
635   customPickerOptions: any = {}
636 ) {
637   const pickerOptions = {
638     ...customPickerOptions,
639     onEmojiSelect: onEmojiSelect,
640     custom: customEmojis,
641   };
642   return new Picker(pickerOptions);
643 }
644
645 var tippyInstance: any;
646 if (isBrowser()) {
647   tippyInstance = tippy("[data-tippy-content]");
648 }
649
650 export function setupTippy() {
651   if (isBrowser()) {
652     tippyInstance.forEach((e: any) => e.destroy());
653     tippyInstance = tippy("[data-tippy-content]", {
654       delay: [500, 0],
655       // Display on "long press"
656       touch: ["hold", 500],
657     });
658   }
659 }
660
661 interface PersonTribute {
662   key: string;
663   view: PersonView;
664 }
665
666 async function personSearch(text: string): Promise<PersonTribute[]> {
667   const usersResponse = await fetchUsers(text);
668
669   return usersResponse.map(pv => ({
670     key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
671     view: pv,
672   }));
673 }
674
675 interface CommunityTribute {
676   key: string;
677   view: CommunityView;
678 }
679
680 async function communitySearch(text: string): Promise<CommunityTribute[]> {
681   const communitiesResponse = await fetchCommunities(text);
682
683   return communitiesResponse.map(cv => ({
684     key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
685     view: cv,
686   }));
687 }
688
689 export function getRecipientIdFromProps(props: any): number {
690   return props.match.params.recipient_id
691     ? Number(props.match.params.recipient_id)
692     : 1;
693 }
694
695 export function getIdFromProps(props: any): number | undefined {
696   const id = props.match.params.post_id;
697   return id ? Number(id) : undefined;
698 }
699
700 export function getCommentIdFromProps(props: any): number | undefined {
701   const id = props.match.params.comment_id;
702   return id ? Number(id) : undefined;
703 }
704
705 type ImmutableListKey =
706   | "comment"
707   | "comment_reply"
708   | "person_mention"
709   | "community"
710   | "private_message"
711   | "post"
712   | "post_report"
713   | "comment_report"
714   | "private_message_report"
715   | "registration_application";
716
717 function editListImmutable<
718   T extends { [key in F]: { id: number } },
719   F extends ImmutableListKey
720 >(fieldName: F, data: T, list: T[]): T[] {
721   return [
722     ...list.map(c => (c[fieldName].id === data[fieldName].id ? data : c)),
723   ];
724 }
725
726 export function editComment(
727   data: CommentView,
728   comments: CommentView[]
729 ): CommentView[] {
730   return editListImmutable("comment", data, comments);
731 }
732
733 export function editCommentReply(
734   data: CommentReplyView,
735   replies: CommentReplyView[]
736 ): CommentReplyView[] {
737   return editListImmutable("comment_reply", data, replies);
738 }
739
740 interface WithComment {
741   comment: CommentI;
742   counts: CommentAggregates;
743   my_vote?: number;
744   saved: boolean;
745 }
746
747 export function editMention(
748   data: PersonMentionView,
749   comments: PersonMentionView[]
750 ): PersonMentionView[] {
751   return editListImmutable("person_mention", data, comments);
752 }
753
754 export function editCommunity(
755   data: CommunityView,
756   communities: CommunityView[]
757 ): CommunityView[] {
758   return editListImmutable("community", data, communities);
759 }
760
761 export function editPrivateMessage(
762   data: PrivateMessageView,
763   messages: PrivateMessageView[]
764 ): PrivateMessageView[] {
765   return editListImmutable("private_message", data, messages);
766 }
767
768 export function editPost(data: PostView, posts: PostView[]): PostView[] {
769   return editListImmutable("post", data, posts);
770 }
771
772 export function editPostReport(
773   data: PostReportView,
774   reports: PostReportView[]
775 ) {
776   return editListImmutable("post_report", data, reports);
777 }
778
779 export function editCommentReport(
780   data: CommentReportView,
781   reports: CommentReportView[]
782 ): CommentReportView[] {
783   return editListImmutable("comment_report", data, reports);
784 }
785
786 export function editPrivateMessageReport(
787   data: PrivateMessageReportView,
788   reports: PrivateMessageReportView[]
789 ): PrivateMessageReportView[] {
790   return editListImmutable("private_message_report", data, reports);
791 }
792
793 export function editRegistrationApplication(
794   data: RegistrationApplicationView,
795   apps: RegistrationApplicationView[]
796 ): RegistrationApplicationView[] {
797   return editListImmutable("registration_application", data, apps);
798 }
799
800 export function editWith<D extends WithComment, L extends WithComment>(
801   { comment, counts, saved, my_vote }: D,
802   list: L[]
803 ) {
804   return [
805     ...list.map(c =>
806       c.comment.id === comment.id
807         ? { ...c, comment, counts, saved, my_vote }
808         : c
809     ),
810   ];
811 }
812
813 export function updatePersonBlock(
814   data: BlockPersonResponse,
815   myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
816 ) {
817   if (myUserInfo) {
818     if (data.blocked) {
819       myUserInfo.person_blocks.push({
820         person: myUserInfo.local_user_view.person,
821         target: data.person_view.person,
822       });
823       toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
824     } else {
825       myUserInfo.person_blocks = myUserInfo.person_blocks.filter(
826         i => i.target.id !== data.person_view.person.id
827       );
828       toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
829     }
830   }
831 }
832
833 export function updateCommunityBlock(
834   data: BlockCommunityResponse,
835   myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
836 ) {
837   if (myUserInfo) {
838     if (data.blocked) {
839       myUserInfo.community_blocks.push({
840         person: myUserInfo.local_user_view.person,
841         community: data.community_view.community,
842       });
843       toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
844     } else {
845       myUserInfo.community_blocks = myUserInfo.community_blocks.filter(
846         i => i.community.id !== data.community_view.community.id
847       );
848       toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
849     }
850   }
851 }
852
853 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
854   const nodes: CommentNodeI[] = [];
855   for (const comment of comments) {
856     nodes.push({ comment_view: comment, children: [], depth: 0 });
857   }
858   return nodes;
859 }
860
861 export function convertCommentSortType(sort: SortType): CommentSortType {
862   if (
863     sort == "TopAll" ||
864     sort == "TopDay" ||
865     sort == "TopWeek" ||
866     sort == "TopMonth" ||
867     sort == "TopYear"
868   ) {
869     return "Top";
870   } else if (sort == "New") {
871     return "New";
872   } else if (sort == "Hot" || sort == "Active") {
873     return "Hot";
874   } else {
875     return "Hot";
876   }
877 }
878
879 export function buildCommentsTree(
880   comments: CommentView[],
881   parentComment: boolean
882 ): CommentNodeI[] {
883   const map = new Map<number, CommentNodeI>();
884   const depthOffset = !parentComment
885     ? 0
886     : getDepthFromComment(comments[0].comment) ?? 0;
887
888   for (const comment_view of comments) {
889     const depthI = getDepthFromComment(comment_view.comment) ?? 0;
890     const depth = depthI ? depthI - depthOffset : 0;
891     const node: CommentNodeI = {
892       comment_view,
893       children: [],
894       depth,
895     };
896     map.set(comment_view.comment.id, { ...node });
897   }
898
899   const tree: CommentNodeI[] = [];
900
901   // if its a parent comment fetch, then push the first comment to the top node.
902   if (parentComment) {
903     const cNode = map.get(comments[0].comment.id);
904     if (cNode) {
905       tree.push(cNode);
906     }
907   }
908
909   for (const comment_view of comments) {
910     const child = map.get(comment_view.comment.id);
911     if (child) {
912       const parent_id = getCommentParentId(comment_view.comment);
913       if (parent_id) {
914         const parent = map.get(parent_id);
915         // Necessary because blocked comment might not exist
916         if (parent) {
917           parent.children.push(child);
918         }
919       } else {
920         if (!parentComment) {
921           tree.push(child);
922         }
923       }
924     }
925   }
926
927   return tree;
928 }
929
930 export function getCommentParentId(comment?: CommentI): number | undefined {
931   const split = comment?.path.split(".");
932   // remove the 0
933   split?.shift();
934
935   return split && split.length > 1
936     ? Number(split.at(split.length - 2))
937     : undefined;
938 }
939
940 export function getDepthFromComment(comment?: CommentI): number | undefined {
941   const len = comment?.path.split(".").length;
942   return len ? len - 2 : undefined;
943 }
944
945 // TODO make immutable
946 export function insertCommentIntoTree(
947   tree: CommentNodeI[],
948   cv: CommentView,
949   parentComment: boolean
950 ) {
951   // Building a fake node to be used for later
952   const node: CommentNodeI = {
953     comment_view: cv,
954     children: [],
955     depth: 0,
956   };
957
958   const parentId = getCommentParentId(cv.comment);
959   if (parentId) {
960     const parent_comment = searchCommentTree(tree, parentId);
961     if (parent_comment) {
962       node.depth = parent_comment.depth + 1;
963       parent_comment.children.unshift(node);
964     }
965   } else if (!parentComment) {
966     tree.unshift(node);
967   }
968 }
969
970 export function searchCommentTree(
971   tree: CommentNodeI[],
972   id: number
973 ): CommentNodeI | undefined {
974   for (const node of tree) {
975     if (node.comment_view.comment.id === id) {
976       return node;
977     }
978
979     for (const child of node.children) {
980       const res = searchCommentTree([child], id);
981
982       if (res) {
983         return res;
984       }
985     }
986   }
987   return undefined;
988 }
989
990 export const colorList: string[] = [
991   hsl(0),
992   hsl(50),
993   hsl(100),
994   hsl(150),
995   hsl(200),
996   hsl(250),
997   hsl(300),
998 ];
999
1000 function hsl(num: number) {
1001   return `hsla(${num}, 35%, 50%, 0.5)`;
1002 }
1003
1004 export function hostname(url: string): string {
1005   const cUrl = new URL(url);
1006   return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1007 }
1008
1009 export function validTitle(title?: string): boolean {
1010   // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1011   if (!title || title.length < 3) return true;
1012
1013   const regex = new RegExp(/.*\S.*/, "g");
1014
1015   return regex.test(title);
1016 }
1017
1018 export function siteBannerCss(banner: string): string {
1019   return ` \
1020     background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1021     background-attachment: fixed; \
1022     background-position: top; \
1023     background-repeat: no-repeat; \
1024     background-size: 100% cover; \
1025
1026     width: 100%; \
1027     max-height: 100vh; \
1028     `;
1029 }
1030
1031 export function setIsoData(context: any): IsoData {
1032   // If its the browser, you need to deserialize the data from the window
1033   if (isBrowser()) {
1034     return window.isoData;
1035   } else return context.router.staticContext;
1036 }
1037
1038 moment.updateLocale("en", {
1039   relativeTime: {
1040     future: "in %s",
1041     past: "%s ago",
1042     s: "<1m",
1043     ss: "%ds",
1044     m: "1m",
1045     mm: "%dm",
1046     h: "1h",
1047     hh: "%dh",
1048     d: "1d",
1049     dd: "%dd",
1050     w: "1w",
1051     ww: "%dw",
1052     M: "1M",
1053     MM: "%dM",
1054     y: "1Y",
1055     yy: "%dY",
1056   },
1057 });
1058
1059 export function saveScrollPosition(context: any) {
1060   const path: string = context.router.route.location.pathname;
1061   const y = window.scrollY;
1062   sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1063 }
1064
1065 export function restoreScrollPosition(context: any) {
1066   const path: string = context.router.route.location.pathname;
1067   const y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1068   window.scrollTo(0, y);
1069 }
1070
1071 export function showLocal(isoData: IsoData): boolean {
1072   return isoData.site_res.site_view.local_site.federation_enabled;
1073 }
1074
1075 export interface Choice {
1076   value: string;
1077   label: string;
1078   disabled?: boolean;
1079 }
1080
1081 export function getUpdatedSearchId(id?: number | null, urlId?: number | null) {
1082   return id === null
1083     ? undefined
1084     : ((id ?? urlId) === 0 ? undefined : id ?? urlId)?.toString();
1085 }
1086
1087 export function communityToChoice(cv: CommunityView): Choice {
1088   return {
1089     value: cv.community.id.toString(),
1090     label: communitySelectName(cv),
1091   };
1092 }
1093
1094 export function personToChoice(pvs: PersonView): Choice {
1095   return {
1096     value: pvs.person.id.toString(),
1097     label: personSelectName(pvs),
1098   };
1099 }
1100
1101 function fetchSearchResults(q: string, type_: SearchType) {
1102   const form: Search = {
1103     q,
1104     type_,
1105     sort: "TopAll",
1106     listing_type: "All",
1107     page: 1,
1108     limit: fetchLimit,
1109     auth: myAuth(),
1110   };
1111
1112   return HttpService.client.search(form);
1113 }
1114
1115 export async function fetchCommunities(q: string) {
1116   const res = await fetchSearchResults(q, "Communities");
1117
1118   return res.state === "success" ? res.data.communities : [];
1119 }
1120
1121 export async function fetchUsers(q: string) {
1122   const res = await fetchSearchResults(q, "Users");
1123
1124   return res.state === "success" ? res.data.users : [];
1125 }
1126
1127 export function communitySelectName(cv: CommunityView): string {
1128   return cv.community.local
1129     ? cv.community.title
1130     : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1131 }
1132
1133 export function personSelectName({
1134   person: { display_name, name, local, actor_id },
1135 }: PersonView): string {
1136   const pName = display_name ?? name;
1137   return local ? pName : `${hostname(actor_id)}/${pName}`;
1138 }
1139
1140 export function initializeSite(site?: GetSiteResponse) {
1141   UserService.Instance.myUserInfo = site?.my_user;
1142   i18n.changeLanguage(getLanguages()[0]);
1143   if (site) {
1144     setupEmojiDataModel(site.custom_emojis ?? []);
1145   }
1146   setupMarkdown();
1147 }
1148
1149 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1150   maximumSignificantDigits: 3,
1151   //@ts-ignore
1152   notation: "compact",
1153   compactDisplay: "short",
1154 });
1155
1156 export function numToSI(value: number): string {
1157   return SHORTNUM_SI_FORMAT.format(value);
1158 }
1159
1160 export function myAuth(): string | undefined {
1161   return UserService.Instance.auth();
1162 }
1163
1164 export function myAuthRequired(): string {
1165   return UserService.Instance.auth(true) ?? "";
1166 }
1167
1168 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1169   return siteRes.site_view.local_site.enable_downvotes;
1170 }
1171
1172 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1173   return siteRes.site_view.local_site.enable_nsfw;
1174 }
1175
1176 export function postToCommentSortType(sort: SortType): CommentSortType {
1177   switch (sort) {
1178     case "Active":
1179     case "Hot":
1180       return "Hot";
1181     case "New":
1182     case "NewComments":
1183       return "New";
1184     case "Old":
1185       return "Old";
1186     default:
1187       return "Top";
1188   }
1189 }
1190
1191 export function isPostBlocked(
1192   pv: PostView,
1193   myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
1194 ): boolean {
1195   return (
1196     (myUserInfo?.community_blocks
1197       .map(c => c.community.id)
1198       .includes(pv.community.id) ||
1199       myUserInfo?.person_blocks
1200         .map(p => p.target.id)
1201         .includes(pv.creator.id)) ??
1202     false
1203   );
1204 }
1205
1206 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1207 export function nsfwCheck(
1208   pv: PostView,
1209   myUserInfo = UserService.Instance.myUserInfo
1210 ): boolean {
1211   const nsfw = pv.post.nsfw || pv.community.nsfw;
1212   const myShowNsfw = myUserInfo?.local_user_view.local_user.show_nsfw ?? false;
1213   return !nsfw || (nsfw && myShowNsfw);
1214 }
1215
1216 export function getRandomFromList<T>(list: T[]): T | undefined {
1217   return list.length == 0
1218     ? undefined
1219     : list.at(Math.floor(Math.random() * list.length));
1220 }
1221
1222 /**
1223  * This shows what language you can select
1224  *
1225  * Use showAll for the site form
1226  * Use showSite for the profile and community forms
1227  * Use false for both those to filter on your profile and site ones
1228  */
1229 export function selectableLanguages(
1230   allLanguages: Language[],
1231   siteLanguages: number[],
1232   showAll?: boolean,
1233   showSite?: boolean,
1234   myUserInfo = UserService.Instance.myUserInfo
1235 ): Language[] {
1236   const allLangIds = allLanguages.map(l => l.id);
1237   let myLangs = myUserInfo?.discussion_languages ?? allLangIds;
1238   myLangs = myLangs.length == 0 ? allLangIds : myLangs;
1239   const siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages;
1240
1241   if (showAll) {
1242     return allLanguages;
1243   } else {
1244     if (showSite) {
1245       return allLanguages.filter(x => siteLangs.includes(x.id));
1246     } else {
1247       return allLanguages
1248         .filter(x => siteLangs.includes(x.id))
1249         .filter(x => myLangs.includes(x.id));
1250     }
1251   }
1252 }
1253
1254 interface EmojiMartCategory {
1255   id: string;
1256   name: string;
1257   emojis: EmojiMartCustomEmoji[];
1258 }
1259
1260 interface EmojiMartCustomEmoji {
1261   id: string;
1262   name: string;
1263   keywords: string[];
1264   skins: EmojiMartSkin[];
1265 }
1266
1267 interface EmojiMartSkin {
1268   src: string;
1269 }
1270
1271 export function isAuthPath(pathname: string) {
1272   return /create_.*|inbox|settings|admin|reports|registration_applications/g.test(
1273     pathname
1274   );
1275 }
1276
1277 export function newVote(voteType: VoteType, myVote?: number): number {
1278   if (voteType == VoteType.Upvote) {
1279     return myVote == 1 ? 0 : 1;
1280   } else {
1281     return myVote == -1 ? 0 : -1;
1282   }
1283 }