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