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