]> Untitled Git - lemmy-ui.git/blob - src/shared/utils.ts
and of course, yarn.lock
[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   const 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   md.renderer.rules.table_open = function () {
612     return '<table class="table">';
613   };
614 }
615
616 export function getEmojiMart(
617   onEmojiSelect: (e: any) => void,
618   customPickerOptions: any = {}
619 ) {
620   const pickerOptions = {
621     ...customPickerOptions,
622     onEmojiSelect: onEmojiSelect,
623     custom: customEmojis,
624   };
625   return new Picker(pickerOptions);
626 }
627
628 var tippyInstance: any;
629 if (isBrowser()) {
630   tippyInstance = tippy("[data-tippy-content]");
631 }
632
633 export function setupTippy() {
634   if (isBrowser()) {
635     tippyInstance.forEach((e: any) => e.destroy());
636     tippyInstance = tippy("[data-tippy-content]", {
637       delay: [500, 0],
638       // Display on "long press"
639       touch: ["hold", 500],
640     });
641   }
642 }
643
644 interface PersonTribute {
645   key: string;
646   view: PersonView;
647 }
648
649 async function personSearch(text: string): Promise<PersonTribute[]> {
650   const usersResponse = await fetchUsers(text);
651
652   return usersResponse.map(pv => ({
653     key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
654     view: pv,
655   }));
656 }
657
658 interface CommunityTribute {
659   key: string;
660   view: CommunityView;
661 }
662
663 async function communitySearch(text: string): Promise<CommunityTribute[]> {
664   const communitiesResponse = await fetchCommunities(text);
665
666   return communitiesResponse.map(cv => ({
667     key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
668     view: cv,
669   }));
670 }
671
672 export function getRecipientIdFromProps(props: any): number {
673   return props.match.params.recipient_id
674     ? Number(props.match.params.recipient_id)
675     : 1;
676 }
677
678 export function getIdFromProps(props: any): number | undefined {
679   const id = props.match.params.post_id;
680   return id ? Number(id) : undefined;
681 }
682
683 export function getCommentIdFromProps(props: any): number | undefined {
684   const id = props.match.params.comment_id;
685   return id ? Number(id) : undefined;
686 }
687
688 type ImmutableListKey =
689   | "comment"
690   | "comment_reply"
691   | "person_mention"
692   | "community"
693   | "private_message"
694   | "post"
695   | "post_report"
696   | "comment_report"
697   | "private_message_report"
698   | "registration_application";
699
700 function editListImmutable<
701   T extends { [key in F]: { id: number } },
702   F extends ImmutableListKey
703 >(fieldName: F, data: T, list: T[]): T[] {
704   return [
705     ...list.map(c => (c[fieldName].id === data[fieldName].id ? data : c)),
706   ];
707 }
708
709 export function editComment(
710   data: CommentView,
711   comments: CommentView[]
712 ): CommentView[] {
713   return editListImmutable("comment", data, comments);
714 }
715
716 export function editCommentReply(
717   data: CommentReplyView,
718   replies: CommentReplyView[]
719 ): CommentReplyView[] {
720   return editListImmutable("comment_reply", data, replies);
721 }
722
723 interface WithComment {
724   comment: CommentI;
725   counts: CommentAggregates;
726   my_vote?: number;
727   saved: boolean;
728 }
729
730 export function editMention(
731   data: PersonMentionView,
732   comments: PersonMentionView[]
733 ): PersonMentionView[] {
734   return editListImmutable("person_mention", data, comments);
735 }
736
737 export function editCommunity(
738   data: CommunityView,
739   communities: CommunityView[]
740 ): CommunityView[] {
741   return editListImmutable("community", data, communities);
742 }
743
744 export function editPrivateMessage(
745   data: PrivateMessageView,
746   messages: PrivateMessageView[]
747 ): PrivateMessageView[] {
748   return editListImmutable("private_message", data, messages);
749 }
750
751 export function editPost(data: PostView, posts: PostView[]): PostView[] {
752   return editListImmutable("post", data, posts);
753 }
754
755 export function editPostReport(
756   data: PostReportView,
757   reports: PostReportView[]
758 ) {
759   return editListImmutable("post_report", data, reports);
760 }
761
762 export function editCommentReport(
763   data: CommentReportView,
764   reports: CommentReportView[]
765 ): CommentReportView[] {
766   return editListImmutable("comment_report", data, reports);
767 }
768
769 export function editPrivateMessageReport(
770   data: PrivateMessageReportView,
771   reports: PrivateMessageReportView[]
772 ): PrivateMessageReportView[] {
773   return editListImmutable("private_message_report", data, reports);
774 }
775
776 export function editRegistrationApplication(
777   data: RegistrationApplicationView,
778   apps: RegistrationApplicationView[]
779 ): RegistrationApplicationView[] {
780   return editListImmutable("registration_application", data, apps);
781 }
782
783 export function editWith<D extends WithComment, L extends WithComment>(
784   { comment, counts, saved, my_vote }: D,
785   list: L[]
786 ) {
787   return [
788     ...list.map(c =>
789       c.comment.id === comment.id
790         ? { ...c, comment, counts, saved, my_vote }
791         : c
792     ),
793   ];
794 }
795
796 export function updatePersonBlock(
797   data: BlockPersonResponse,
798   myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
799 ) {
800   if (myUserInfo) {
801     if (data.blocked) {
802       myUserInfo.person_blocks.push({
803         person: myUserInfo.local_user_view.person,
804         target: data.person_view.person,
805       });
806       toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
807     } else {
808       myUserInfo.person_blocks = myUserInfo.person_blocks.filter(
809         i => i.target.id !== data.person_view.person.id
810       );
811       toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
812     }
813   }
814 }
815
816 export function updateCommunityBlock(
817   data: BlockCommunityResponse,
818   myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
819 ) {
820   if (myUserInfo) {
821     if (data.blocked) {
822       myUserInfo.community_blocks.push({
823         person: myUserInfo.local_user_view.person,
824         community: data.community_view.community,
825       });
826       toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
827     } else {
828       myUserInfo.community_blocks = myUserInfo.community_blocks.filter(
829         i => i.community.id !== data.community_view.community.id
830       );
831       toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
832     }
833   }
834 }
835
836 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
837   const nodes: CommentNodeI[] = [];
838   for (const comment of comments) {
839     nodes.push({ comment_view: comment, children: [], depth: 0 });
840   }
841   return nodes;
842 }
843
844 export function convertCommentSortType(sort: SortType): CommentSortType {
845   if (
846     sort == "TopAll" ||
847     sort == "TopDay" ||
848     sort == "TopWeek" ||
849     sort == "TopMonth" ||
850     sort == "TopYear"
851   ) {
852     return "Top";
853   } else if (sort == "New") {
854     return "New";
855   } else if (sort == "Hot" || sort == "Active") {
856     return "Hot";
857   } else {
858     return "Hot";
859   }
860 }
861
862 export function buildCommentsTree(
863   comments: CommentView[],
864   parentComment: boolean
865 ): CommentNodeI[] {
866   const map = new Map<number, CommentNodeI>();
867   const depthOffset = !parentComment
868     ? 0
869     : getDepthFromComment(comments[0].comment) ?? 0;
870
871   for (const comment_view of comments) {
872     const depthI = getDepthFromComment(comment_view.comment) ?? 0;
873     const depth = depthI ? depthI - depthOffset : 0;
874     const node: CommentNodeI = {
875       comment_view,
876       children: [],
877       depth,
878     };
879     map.set(comment_view.comment.id, { ...node });
880   }
881
882   const tree: CommentNodeI[] = [];
883
884   // if its a parent comment fetch, then push the first comment to the top node.
885   if (parentComment) {
886     const cNode = map.get(comments[0].comment.id);
887     if (cNode) {
888       tree.push(cNode);
889     }
890   }
891
892   for (const comment_view of comments) {
893     const child = map.get(comment_view.comment.id);
894     if (child) {
895       const parent_id = getCommentParentId(comment_view.comment);
896       if (parent_id) {
897         const parent = map.get(parent_id);
898         // Necessary because blocked comment might not exist
899         if (parent) {
900           parent.children.push(child);
901         }
902       } else {
903         if (!parentComment) {
904           tree.push(child);
905         }
906       }
907     }
908   }
909
910   return tree;
911 }
912
913 export function getCommentParentId(comment?: CommentI): number | undefined {
914   const split = comment?.path.split(".");
915   // remove the 0
916   split?.shift();
917
918   return split && split.length > 1
919     ? Number(split.at(split.length - 2))
920     : undefined;
921 }
922
923 export function getDepthFromComment(comment?: CommentI): number | undefined {
924   const len = comment?.path.split(".").length;
925   return len ? len - 2 : undefined;
926 }
927
928 // TODO make immutable
929 export function insertCommentIntoTree(
930   tree: CommentNodeI[],
931   cv: CommentView,
932   parentComment: boolean
933 ) {
934   // Building a fake node to be used for later
935   const node: CommentNodeI = {
936     comment_view: cv,
937     children: [],
938     depth: 0,
939   };
940
941   const parentId = getCommentParentId(cv.comment);
942   if (parentId) {
943     const parent_comment = searchCommentTree(tree, parentId);
944     if (parent_comment) {
945       node.depth = parent_comment.depth + 1;
946       parent_comment.children.unshift(node);
947     }
948   } else if (!parentComment) {
949     tree.unshift(node);
950   }
951 }
952
953 export function searchCommentTree(
954   tree: CommentNodeI[],
955   id: number
956 ): CommentNodeI | undefined {
957   for (const node of tree) {
958     if (node.comment_view.comment.id === id) {
959       return node;
960     }
961
962     for (const child of node.children) {
963       const res = searchCommentTree([child], id);
964
965       if (res) {
966         return res;
967       }
968     }
969   }
970   return undefined;
971 }
972
973 export const colorList: string[] = [
974   hsl(0),
975   hsl(50),
976   hsl(100),
977   hsl(150),
978   hsl(200),
979   hsl(250),
980   hsl(300),
981 ];
982
983 function hsl(num: number) {
984   return `hsla(${num}, 35%, 50%, 0.5)`;
985 }
986
987 export function hostname(url: string): string {
988   const cUrl = new URL(url);
989   return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
990 }
991
992 export function validTitle(title?: string): boolean {
993   // Initial title is null, minimum length is taken care of by textarea's minLength={3}
994   if (!title || title.length < 3) return true;
995
996   const regex = new RegExp(/.*\S.*/, "g");
997
998   return regex.test(title);
999 }
1000
1001 export function siteBannerCss(banner: string): string {
1002   return ` \
1003     background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1004     background-attachment: fixed; \
1005     background-position: top; \
1006     background-repeat: no-repeat; \
1007     background-size: 100% cover; \
1008
1009     width: 100%; \
1010     max-height: 100vh; \
1011     `;
1012 }
1013
1014 export function setIsoData(context: any): IsoData {
1015   // If its the browser, you need to deserialize the data from the window
1016   if (isBrowser()) {
1017     return window.isoData;
1018   } else return context.router.staticContext;
1019 }
1020
1021 moment.updateLocale("en", {
1022   relativeTime: {
1023     future: "in %s",
1024     past: "%s ago",
1025     s: "<1m",
1026     ss: "%ds",
1027     m: "1m",
1028     mm: "%dm",
1029     h: "1h",
1030     hh: "%dh",
1031     d: "1d",
1032     dd: "%dd",
1033     w: "1w",
1034     ww: "%dw",
1035     M: "1M",
1036     MM: "%dM",
1037     y: "1Y",
1038     yy: "%dY",
1039   },
1040 });
1041
1042 export function saveScrollPosition(context: any) {
1043   const path: string = context.router.route.location.pathname;
1044   const y = window.scrollY;
1045   sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1046 }
1047
1048 export function restoreScrollPosition(context: any) {
1049   const path: string = context.router.route.location.pathname;
1050   const y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1051   window.scrollTo(0, y);
1052 }
1053
1054 export function showLocal(isoData: IsoData): boolean {
1055   return isoData.site_res.site_view.local_site.federation_enabled;
1056 }
1057
1058 export interface Choice {
1059   value: string;
1060   label: string;
1061   disabled?: boolean;
1062 }
1063
1064 export function getUpdatedSearchId(id?: number | null, urlId?: number | null) {
1065   return id === null
1066     ? undefined
1067     : ((id ?? urlId) === 0 ? undefined : id ?? urlId)?.toString();
1068 }
1069
1070 export function communityToChoice(cv: CommunityView): Choice {
1071   return {
1072     value: cv.community.id.toString(),
1073     label: communitySelectName(cv),
1074   };
1075 }
1076
1077 export function personToChoice(pvs: PersonView): Choice {
1078   return {
1079     value: pvs.person.id.toString(),
1080     label: personSelectName(pvs),
1081   };
1082 }
1083
1084 function fetchSearchResults(q: string, type_: SearchType) {
1085   const form: Search = {
1086     q,
1087     type_,
1088     sort: "TopAll",
1089     listing_type: "All",
1090     page: 1,
1091     limit: fetchLimit,
1092     auth: myAuth(),
1093   };
1094
1095   return HttpService.client.search(form);
1096 }
1097
1098 export async function fetchCommunities(q: string) {
1099   const res = await fetchSearchResults(q, "Communities");
1100
1101   return res.state === "success" ? res.data.communities : [];
1102 }
1103
1104 export async function fetchUsers(q: string) {
1105   const res = await fetchSearchResults(q, "Users");
1106
1107   return res.state === "success" ? res.data.users : [];
1108 }
1109
1110 export function communitySelectName(cv: CommunityView): string {
1111   return cv.community.local
1112     ? cv.community.title
1113     : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1114 }
1115
1116 export function personSelectName({
1117   person: { display_name, name, local, actor_id },
1118 }: PersonView): string {
1119   const pName = display_name ?? name;
1120   return local ? pName : `${hostname(actor_id)}/${pName}`;
1121 }
1122
1123 export function initializeSite(site?: GetSiteResponse) {
1124   UserService.Instance.myUserInfo = site?.my_user;
1125   i18n.changeLanguage();
1126   if (site) {
1127     setupEmojiDataModel(site.custom_emojis ?? []);
1128   }
1129   setupMarkdown();
1130 }
1131
1132 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1133   maximumSignificantDigits: 3,
1134   //@ts-ignore
1135   notation: "compact",
1136   compactDisplay: "short",
1137 });
1138
1139 export function numToSI(value: number): string {
1140   return SHORTNUM_SI_FORMAT.format(value);
1141 }
1142
1143 export function myAuth(): string | undefined {
1144   return UserService.Instance.auth();
1145 }
1146
1147 export function myAuthRequired(): string {
1148   return UserService.Instance.auth(true) ?? "";
1149 }
1150
1151 export function enableDownvotes(siteRes: GetSiteResponse): boolean {
1152   return siteRes.site_view.local_site.enable_downvotes;
1153 }
1154
1155 export function enableNsfw(siteRes: GetSiteResponse): boolean {
1156   return siteRes.site_view.local_site.enable_nsfw;
1157 }
1158
1159 export function postToCommentSortType(sort: SortType): CommentSortType {
1160   switch (sort) {
1161     case "Active":
1162     case "Hot":
1163       return "Hot";
1164     case "New":
1165     case "NewComments":
1166       return "New";
1167     case "Old":
1168       return "Old";
1169     default:
1170       return "Top";
1171   }
1172 }
1173
1174 export function isPostBlocked(
1175   pv: PostView,
1176   myUserInfo: MyUserInfo | undefined = UserService.Instance.myUserInfo
1177 ): boolean {
1178   return (
1179     (myUserInfo?.community_blocks
1180       .map(c => c.community.id)
1181       .includes(pv.community.id) ||
1182       myUserInfo?.person_blocks
1183         .map(p => p.target.id)
1184         .includes(pv.creator.id)) ??
1185     false
1186   );
1187 }
1188
1189 /// Checks to make sure you can view NSFW posts. Returns true if you can.
1190 export function nsfwCheck(
1191   pv: PostView,
1192   myUserInfo = UserService.Instance.myUserInfo
1193 ): boolean {
1194   const nsfw = pv.post.nsfw || pv.community.nsfw;
1195   const myShowNsfw = myUserInfo?.local_user_view.local_user.show_nsfw ?? false;
1196   return !nsfw || (nsfw && myShowNsfw);
1197 }
1198
1199 export function getRandomFromList<T>(list: T[]): T | undefined {
1200   return list.length == 0
1201     ? undefined
1202     : list.at(Math.floor(Math.random() * list.length));
1203 }
1204
1205 /**
1206  * This shows what language you can select
1207  *
1208  * Use showAll for the site form
1209  * Use showSite for the profile and community forms
1210  * Use false for both those to filter on your profile and site ones
1211  */
1212 export function selectableLanguages(
1213   allLanguages: Language[],
1214   siteLanguages: number[],
1215   showAll?: boolean,
1216   showSite?: boolean,
1217   myUserInfo = UserService.Instance.myUserInfo
1218 ): Language[] {
1219   const allLangIds = allLanguages.map(l => l.id);
1220   let myLangs = myUserInfo?.discussion_languages ?? allLangIds;
1221   myLangs = myLangs.length == 0 ? allLangIds : myLangs;
1222   const siteLangs = siteLanguages.length == 0 ? allLangIds : siteLanguages;
1223
1224   if (showAll) {
1225     return allLanguages;
1226   } else {
1227     if (showSite) {
1228       return allLanguages.filter(x => siteLangs.includes(x.id));
1229     } else {
1230       return allLanguages
1231         .filter(x => siteLangs.includes(x.id))
1232         .filter(x => myLangs.includes(x.id));
1233     }
1234   }
1235 }
1236
1237 interface EmojiMartCategory {
1238   id: string;
1239   name: string;
1240   emojis: EmojiMartCustomEmoji[];
1241 }
1242
1243 interface EmojiMartCustomEmoji {
1244   id: string;
1245   name: string;
1246   keywords: string[];
1247   skins: EmojiMartSkin[];
1248 }
1249
1250 interface EmojiMartSkin {
1251   src: string;
1252 }
1253
1254 export function isAuthPath(pathname: string) {
1255   return /create_.*|inbox|settings|admin|reports|registration_applications/g.test(
1256     pathname
1257   );
1258 }
1259
1260 export function newVote(voteType: VoteType, myVote?: number): number {
1261   if (voteType == VoteType.Upvote) {
1262     return myVote == 1 ? 0 : 1;
1263   } else {
1264     return myVote == -1 ? 0 : -1;
1265   }
1266 }