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