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