]> Untitled Git - lemmy-ui.git/blob - src/shared/utils.ts
Adding nofollow to links. Fixes #542 (#543)
[lemmy-ui.git] / src / shared / utils.ts
1 import emojiShortName from "emoji-short-name";
2 import {
3   BlockCommunityResponse,
4   BlockPersonResponse,
5   CommentReportView,
6   CommentView,
7   CommunityBlockView,
8   CommunityView,
9   GetSiteMetadata,
10   GetSiteResponse,
11   LemmyHttp,
12   LemmyWebsocket,
13   ListingType,
14   MyUserInfo,
15   PersonBlockView,
16   PersonSafe,
17   PersonViewSafe,
18   PostReportView,
19   PostView,
20   PrivateMessageView,
21   RegistrationApplicationView,
22   Search,
23   SearchResponse,
24   SearchType,
25   SortType,
26   UserOperation,
27   WebSocketJsonResponse,
28   WebSocketResponse,
29 } from "lemmy-js-client";
30 import markdown_it from "markdown-it";
31 import markdown_it_container from "markdown-it-container";
32 import markdown_it_footnote from "markdown-it-footnote";
33 import markdown_it_html5_embed from "markdown-it-html5-embed";
34 import markdown_it_sub from "markdown-it-sub";
35 import markdown_it_sup from "markdown-it-sup";
36 import moment from "moment";
37 import { Subscription } from "rxjs";
38 import { delay, retryWhen, take } from "rxjs/operators";
39 import tippy from "tippy.js";
40 import Toastify from "toastify-js";
41 import { httpBase } from "./env";
42 import { i18n, languages } from "./i18next";
43 import {
44   CommentNode as CommentNodeI,
45   CommentSortType,
46   DataType,
47   IsoData,
48 } from "./interfaces";
49 import { UserService, WebSocketService } from "./services";
50
51 var Tribute: any;
52 if (isBrowser()) {
53   Tribute = require("tributejs");
54 }
55
56 export const wsClient = new LemmyWebsocket();
57
58 export const favIconUrl = "/static/assets/icons/favicon.svg";
59 export const favIconPngUrl = "/static/assets/icons/apple-touch-icon.png";
60 // TODO
61 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
62 export const repoUrl = "https://github.com/LemmyNet";
63 export const joinLemmyUrl = "https://join-lemmy.org";
64 export const donateLemmyUrl = `${joinLemmyUrl}/donate`;
65 export const docsUrl = `${joinLemmyUrl}/docs/en/index.html`;
66 export const helpGuideUrl = `${joinLemmyUrl}/docs/en/about/guide.html`; // TODO find a way to redirect to the non-en folder
67 export const markdownHelpUrl = `${helpGuideUrl}#using-markdown`;
68 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
69 export const archiveTodayUrl = "https://archive.today";
70 export const ghostArchiveUrl = "https://ghostarchive.org";
71 export const webArchiveUrl = "https://web.archive.org";
72 export const elementUrl = "https://element.io";
73
74 export const postRefetchSeconds: number = 60 * 1000;
75 export const fetchLimit = 20;
76 export const mentionDropdownFetchLimit = 10;
77
78 export const relTags = "noopener nofollow";
79
80 export const themes = [
81   "litera",
82   "materia",
83   "minty",
84   "solar",
85   "united",
86   "cyborg",
87   "darkly",
88   "journal",
89   "sketchy",
90   "vaporwave",
91   "vaporwave-dark",
92   "i386",
93   "litely",
94   "nord",
95 ];
96
97 const DEFAULT_ALPHABET =
98   "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
99
100 function getRandomCharFromAlphabet(alphabet: string): string {
101   return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
102 }
103
104 export function randomStr(
105   idDesiredLength = 20,
106   alphabet = DEFAULT_ALPHABET
107 ): string {
108   /**
109    * Create n-long array and map it to random chars from given alphabet.
110    * Then join individual chars as string
111    */
112   return Array.from({ length: idDesiredLength })
113     .map(() => {
114       return getRandomCharFromAlphabet(alphabet);
115     })
116     .join("");
117 }
118
119 export function wsJsonToRes<ResponseType>(
120   msg: WebSocketJsonResponse<ResponseType>
121 ): WebSocketResponse<ResponseType> {
122   return {
123     op: wsUserOp(msg),
124     data: msg.data,
125   };
126 }
127
128 export function wsUserOp(msg: any): UserOperation {
129   let opStr: string = msg.op;
130   return UserOperation[opStr];
131 }
132
133 export const md = new markdown_it({
134   html: true,
135   linkify: true,
136   typographer: true,
137 })
138   .use(markdown_it_sub)
139   .use(markdown_it_sup)
140   .use(markdown_it_footnote)
141   .use(markdown_it_html5_embed, {
142     html5embed: {
143       useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
144       attributes: {
145         audio: 'controls preload="metadata"',
146         video:
147           'width="100%" max-height="100%" controls loop preload="metadata"',
148       },
149     },
150   })
151   .use(markdown_it_container, "spoiler", {
152     validate: function (params: any) {
153       return params.trim().match(/^spoiler\s+(.*)$/);
154     },
155
156     render: function (tokens: any, idx: any) {
157       var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
158
159       if (tokens[idx].nesting === 1) {
160         // opening tag
161         return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
162       } else {
163         // closing tag
164         return "</details>\n";
165       }
166     },
167   });
168
169 export function hotRankComment(comment_view: CommentView): number {
170   return hotRank(comment_view.counts.score, comment_view.comment.published);
171 }
172
173 export function hotRankActivePost(post_view: PostView): number {
174   return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
175 }
176
177 export function hotRankPost(post_view: PostView): number {
178   return hotRank(post_view.counts.score, post_view.post.published);
179 }
180
181 export function hotRank(score: number, timeStr: string): number {
182   // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
183   let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
184   let now: Date = new Date();
185   let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
186
187   let rank =
188     (10000 * Math.log10(Math.max(1, 3 + score))) /
189     Math.pow(hoursElapsed + 2, 1.8);
190
191   // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
192
193   return rank;
194 }
195
196 export function mdToHtml(text: string) {
197   return { __html: md.render(text) };
198 }
199
200 export function getUnixTime(text: string): number {
201   return text ? new Date(text).getTime() / 1000 : undefined;
202 }
203
204 export function futureDaysToUnixTime(days: number): number {
205   return days
206     ? Math.trunc(
207         new Date(Date.now() + 1000 * 60 * 60 * 24 * days).getTime() / 1000
208       )
209     : undefined;
210 }
211
212 export function canMod(
213   myUserInfo: MyUserInfo,
214   modIds: number[],
215   creator_id: number,
216   onSelf = false
217 ): boolean {
218   // You can do moderator actions only on the mods added after you.
219   if (myUserInfo) {
220     let yourIndex = modIds.findIndex(
221       id => id == myUserInfo.local_user_view.person.id
222     );
223     if (yourIndex == -1) {
224       return false;
225     } else {
226       // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
227       modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
228       return !modIds.includes(creator_id);
229     }
230   } else {
231     return false;
232   }
233 }
234
235 export function isMod(modIds: number[], creator_id: number): boolean {
236   return modIds.includes(creator_id);
237 }
238
239 const imageRegex = /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/;
240 const videoRegex = /(http)?s?:?(\/\/[^"']*\.(?:mp4|webm))/;
241
242 export function isImage(url: string) {
243   return imageRegex.test(url);
244 }
245
246 export function isVideo(url: string) {
247   return videoRegex.test(url);
248 }
249
250 export function validURL(str: string) {
251   return !!new URL(str);
252 }
253
254 export function communityRSSUrl(actorId: string, sort: string): string {
255   let url = new URL(actorId);
256   return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
257 }
258
259 export function validEmail(email: string) {
260   let re =
261     /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
262   return re.test(String(email).toLowerCase());
263 }
264
265 export function capitalizeFirstLetter(str: string): string {
266   return str.charAt(0).toUpperCase() + str.slice(1);
267 }
268
269 export function routeSortTypeToEnum(sort: string): SortType {
270   return SortType[sort];
271 }
272
273 export function listingTypeFromNum(type_: number): ListingType {
274   return Object.values(ListingType)[type_];
275 }
276
277 export function sortTypeFromNum(type_: number): SortType {
278   return Object.values(SortType)[type_];
279 }
280
281 export function routeListingTypeToEnum(type: string): ListingType {
282   return ListingType[type];
283 }
284
285 export function routeDataTypeToEnum(type: string): DataType {
286   return DataType[capitalizeFirstLetter(type)];
287 }
288
289 export function routeSearchTypeToEnum(type: string): SearchType {
290   return SearchType[type];
291 }
292
293 export async function getSiteMetadata(url: string) {
294   let form: GetSiteMetadata = {
295     url,
296   };
297   let client = new LemmyHttp(httpBase);
298   return client.getSiteMetadata(form);
299 }
300
301 export function debounce(func: any, wait = 1000, immediate = false) {
302   // 'private' variable for instance
303   // The returned function will be able to reference this due to closure.
304   // Each call to the returned function will share this common timer.
305   let timeout: any;
306
307   // Calling debounce returns a new anonymous function
308   return function () {
309     // reference the context and args for the setTimeout function
310     var args = arguments;
311
312     // Should the function be called now? If immediate is true
313     //   and not already in a timeout then the answer is: Yes
314     var callNow = immediate && !timeout;
315
316     // This is the basic debounce behaviour where you can call this
317     //   function several times, but it will only execute once
318     //   [before or after imposing a delay].
319     //   Each time the returned function is called, the timer starts over.
320     clearTimeout(timeout);
321
322     // Set the new timeout
323     timeout = setTimeout(function () {
324       // Inside the timeout function, clear the timeout variable
325       // which will let the next execution run when in 'immediate' mode
326       timeout = null;
327
328       // Check if the function already ran with the immediate flag
329       if (!immediate) {
330         // Call the original function with apply
331         // apply lets you define the 'this' object as well as the arguments
332         //    (both captured before setTimeout)
333         func.apply(this, args);
334       }
335     }, wait);
336
337     // Immediate mode and no wait timer? Execute the function..
338     if (callNow) func.apply(this, args);
339   };
340 }
341
342 export function getLanguages(override?: string): string[] {
343   let myUserInfo = UserService.Instance.myUserInfo;
344   let lang =
345     override ||
346     (myUserInfo?.local_user_view.local_user.lang
347       ? myUserInfo.local_user_view.local_user.lang
348       : "browser");
349
350   if (lang == "browser" && isBrowser()) {
351     return getBrowserLanguages();
352   } else {
353     return [lang];
354   }
355 }
356
357 function getBrowserLanguages(): string[] {
358   // Intersect lemmy's langs, with the browser langs
359   let langs = languages ? languages.map(l => l.code) : ["en"];
360
361   // NOTE, mobile browsers seem to be missing this list, so append en
362   let allowedLangs = navigator.languages
363     .concat("en")
364     .filter(v => langs.includes(v));
365   return allowedLangs;
366 }
367
368 export function setTheme(theme: string, forceReload = false) {
369   if (!isBrowser()) {
370     return;
371   }
372   if (theme === "browser" && !forceReload) {
373     return;
374   }
375   // This is only run on a force reload
376   if (theme == "browser") {
377     theme = "darkly";
378   }
379
380   // Unload all the other themes
381   for (var i = 0; i < themes.length; i++) {
382     let styleSheet = document.getElementById(themes[i]);
383     if (styleSheet) {
384       styleSheet.setAttribute("disabled", "disabled");
385     }
386   }
387
388   document
389     .getElementById("default-light")
390     ?.setAttribute("disabled", "disabled");
391   document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
392
393   // Load the theme dynamically
394   let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
395   loadCss(theme, cssLoc);
396   document.getElementById(theme).removeAttribute("disabled");
397 }
398
399 export function loadCss(id: string, loc: string) {
400   if (!document.getElementById(id)) {
401     var head = document.getElementsByTagName("head")[0];
402     var link = document.createElement("link");
403     link.id = id;
404     link.rel = "stylesheet";
405     link.type = "text/css";
406     link.href = loc;
407     link.media = "all";
408     head.appendChild(link);
409   }
410 }
411
412 export function objectFlip(obj: any) {
413   const ret = {};
414   Object.keys(obj).forEach(key => {
415     ret[obj[key]] = key;
416   });
417   return ret;
418 }
419
420 export function showAvatars(): boolean {
421   return (
422     UserService.Instance.myUserInfo?.local_user_view.local_user.show_avatars ||
423     !UserService.Instance.myUserInfo
424   );
425 }
426
427 export function showScores(): boolean {
428   return (
429     UserService.Instance.myUserInfo?.local_user_view.local_user.show_scores ||
430     !UserService.Instance.myUserInfo
431   );
432 }
433
434 export function isCakeDay(published: string): boolean {
435   // moment(undefined) or moment.utc(undefined) returns the current date/time
436   // moment(null) or moment.utc(null) returns null
437   const createDate = moment.utc(published || null).local();
438   const currentDate = moment(new Date());
439
440   return (
441     createDate.date() === currentDate.date() &&
442     createDate.month() === currentDate.month() &&
443     createDate.year() !== currentDate.year()
444   );
445 }
446
447 export function toast(text: string, background = "success") {
448   if (isBrowser()) {
449     let backgroundColor = `var(--${background})`;
450     Toastify({
451       text: text,
452       backgroundColor: backgroundColor,
453       gravity: "bottom",
454       position: "left",
455     }).showToast();
456   }
457 }
458
459 export function pictrsDeleteToast(
460   clickToDeleteText: string,
461   deletePictureText: string,
462   deleteUrl: string
463 ) {
464   if (isBrowser()) {
465     let backgroundColor = `var(--light)`;
466     let toast = Toastify({
467       text: clickToDeleteText,
468       backgroundColor: backgroundColor,
469       gravity: "top",
470       position: "right",
471       duration: 10000,
472       onClick: () => {
473         if (toast) {
474           window.location.replace(deleteUrl);
475           alert(deletePictureText);
476           toast.hideToast();
477         }
478       },
479       close: true,
480     }).showToast();
481   }
482 }
483
484 interface NotifyInfo {
485   name: string;
486   icon?: string;
487   link: string;
488   body: string;
489 }
490
491 export function messageToastify(info: NotifyInfo, router: any) {
492   if (isBrowser()) {
493     let htmlBody = info.body ? md.render(info.body) : "";
494     let backgroundColor = `var(--light)`;
495
496     let toast = Toastify({
497       text: `${htmlBody}<br />${info.name}`,
498       avatar: info.icon ? info.icon : null,
499       backgroundColor: backgroundColor,
500       className: "text-dark",
501       close: true,
502       gravity: "top",
503       position: "right",
504       duration: 5000,
505       escapeMarkup: false,
506       onClick: () => {
507         if (toast) {
508           toast.hideToast();
509           router.history.push(info.link);
510         }
511       },
512     }).showToast();
513   }
514 }
515
516 export function notifyPost(post_view: PostView, router: any) {
517   let info: NotifyInfo = {
518     name: post_view.community.name,
519     icon: post_view.community.icon,
520     link: `/post/${post_view.post.id}`,
521     body: post_view.post.name,
522   };
523   notify(info, router);
524 }
525
526 export function notifyComment(comment_view: CommentView, router: any) {
527   let info: NotifyInfo = {
528     name: comment_view.creator.name,
529     icon: comment_view.creator.avatar,
530     link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
531     body: comment_view.comment.content,
532   };
533   notify(info, router);
534 }
535
536 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
537   let info: NotifyInfo = {
538     name: pmv.creator.name,
539     icon: pmv.creator.avatar,
540     link: `/inbox`,
541     body: pmv.private_message.content,
542   };
543   notify(info, router);
544 }
545
546 function notify(info: NotifyInfo, router: any) {
547   messageToastify(info, router);
548
549   // TODO absolute nightmare bug, but notifs are currently broken.
550   // Notification.new will try to do a browser fetch ???
551
552   // if (Notification.permission !== "granted") Notification.requestPermission();
553   // else {
554   //   var notification = new Notification(info.name, {
555   //     icon: info.icon,
556   //     body: info.body,
557   //   });
558
559   //   notification.onclick = (ev: Event): any => {
560   //     ev.preventDefault();
561   //     router.history.push(info.link);
562   //   };
563   // }
564 }
565
566 export function setupTribute() {
567   return new Tribute({
568     noMatchTemplate: function () {
569       return "";
570     },
571     collection: [
572       // Emojis
573       {
574         trigger: ":",
575         menuItemTemplate: (item: any) => {
576           let shortName = `:${item.original.key}:`;
577           return `${item.original.val} ${shortName}`;
578         },
579         selectTemplate: (item: any) => {
580           return `${item.original.val}`;
581         },
582         values: Object.entries(emojiShortName).map(e => {
583           return { key: e[1], val: e[0] };
584         }),
585         allowSpaces: false,
586         autocompleteMode: true,
587         // TODO
588         // menuItemLimit: mentionDropdownFetchLimit,
589         menuShowMinLength: 2,
590       },
591       // Persons
592       {
593         trigger: "@",
594         selectTemplate: (item: any) => {
595           let it: PersonTribute = item.original;
596           return `[${it.key}](${it.view.person.actor_id})`;
597         },
598         values: (text: string, cb: (persons: PersonTribute[]) => any) => {
599           personSearch(text, (persons: PersonTribute[]) => cb(persons));
600         },
601         allowSpaces: false,
602         autocompleteMode: true,
603         // TODO
604         // menuItemLimit: mentionDropdownFetchLimit,
605         menuShowMinLength: 2,
606       },
607
608       // Communities
609       {
610         trigger: "!",
611         selectTemplate: (item: any) => {
612           let it: CommunityTribute = item.original;
613           return `[${it.key}](${it.view.community.actor_id})`;
614         },
615         values: (text: string, cb: any) => {
616           communitySearch(text, (communities: CommunityTribute[]) =>
617             cb(communities)
618           );
619         },
620         allowSpaces: false,
621         autocompleteMode: true,
622         // TODO
623         // menuItemLimit: mentionDropdownFetchLimit,
624         menuShowMinLength: 2,
625       },
626     ],
627   });
628 }
629
630 var tippyInstance: any;
631 if (isBrowser()) {
632   tippyInstance = tippy("[data-tippy-content]");
633 }
634
635 export function setupTippy() {
636   if (isBrowser()) {
637     tippyInstance.forEach((e: any) => e.destroy());
638     tippyInstance = tippy("[data-tippy-content]", {
639       delay: [500, 0],
640       // Display on "long press"
641       touch: ["hold", 500],
642     });
643   }
644 }
645
646 interface PersonTribute {
647   key: string;
648   view: PersonViewSafe;
649 }
650
651 function personSearch(text: string, cb: (persons: PersonTribute[]) => any) {
652   if (text) {
653     let form: Search = {
654       q: text,
655       type_: SearchType.Users,
656       sort: SortType.TopAll,
657       listing_type: ListingType.All,
658       page: 1,
659       limit: mentionDropdownFetchLimit,
660       auth: authField(false),
661     };
662
663     WebSocketService.Instance.send(wsClient.search(form));
664
665     let personSub = WebSocketService.Instance.subject.subscribe(
666       msg => {
667         let res = wsJsonToRes(msg);
668         if (res.op == UserOperation.Search) {
669           let data = res.data as SearchResponse;
670           let persons: PersonTribute[] = data.users.map(pv => {
671             let tribute: PersonTribute = {
672               key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
673               view: pv,
674             };
675             return tribute;
676           });
677           cb(persons);
678           personSub.unsubscribe();
679         }
680       },
681       err => console.error(err),
682       () => console.log("complete")
683     );
684   } else {
685     cb([]);
686   }
687 }
688
689 interface CommunityTribute {
690   key: string;
691   view: CommunityView;
692 }
693
694 function communitySearch(
695   text: string,
696   cb: (communities: CommunityTribute[]) => any
697 ) {
698   if (text) {
699     let form: Search = {
700       q: text,
701       type_: SearchType.Communities,
702       sort: SortType.TopAll,
703       listing_type: ListingType.All,
704       page: 1,
705       limit: mentionDropdownFetchLimit,
706       auth: authField(false),
707     };
708
709     WebSocketService.Instance.send(wsClient.search(form));
710
711     let communitySub = WebSocketService.Instance.subject.subscribe(
712       msg => {
713         let res = wsJsonToRes(msg);
714         if (res.op == UserOperation.Search) {
715           let data = res.data as SearchResponse;
716           let communities: CommunityTribute[] = data.communities.map(cv => {
717             let tribute: CommunityTribute = {
718               key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
719               view: cv,
720             };
721             return tribute;
722           });
723           cb(communities);
724           communitySub.unsubscribe();
725         }
726       },
727       err => console.error(err),
728       () => console.log("complete")
729     );
730   } else {
731     cb([]);
732   }
733 }
734
735 export function getListingTypeFromProps(props: any): ListingType {
736   return props.match.params.listing_type
737     ? routeListingTypeToEnum(props.match.params.listing_type)
738     : UserService.Instance.myUserInfo
739     ? Object.values(ListingType)[
740         UserService.Instance.myUserInfo.local_user_view.local_user
741           .default_listing_type
742       ]
743     : ListingType.Local;
744 }
745
746 export function getListingTypeFromPropsNoDefault(props: any): ListingType {
747   return props.match.params.listing_type
748     ? routeListingTypeToEnum(props.match.params.listing_type)
749     : ListingType.Local;
750 }
751
752 // TODO might need to add a user setting for this too
753 export function getDataTypeFromProps(props: any): DataType {
754   return props.match.params.data_type
755     ? routeDataTypeToEnum(props.match.params.data_type)
756     : DataType.Post;
757 }
758
759 export function getSortTypeFromProps(props: any): SortType {
760   return props.match.params.sort
761     ? routeSortTypeToEnum(props.match.params.sort)
762     : UserService.Instance.myUserInfo
763     ? Object.values(SortType)[
764         UserService.Instance.myUserInfo.local_user_view.local_user
765           .default_sort_type
766       ]
767     : SortType.Active;
768 }
769
770 export function getPageFromProps(props: any): number {
771   return props.match.params.page ? Number(props.match.params.page) : 1;
772 }
773
774 export function getRecipientIdFromProps(props: any): number {
775   return props.match.params.recipient_id
776     ? Number(props.match.params.recipient_id)
777     : 1;
778 }
779
780 export function getIdFromProps(props: any): number {
781   return Number(props.match.params.id);
782 }
783
784 export function getCommentIdFromProps(props: any): number {
785   return Number(props.match.params.comment_id);
786 }
787
788 export function getUsernameFromProps(props: any): string {
789   return props.match.params.username;
790 }
791
792 export function editCommentRes(data: CommentView, comments: CommentView[]) {
793   let found = comments.find(c => c.comment.id == data.comment.id);
794   if (found) {
795     found.comment.content = data.comment.content;
796     found.comment.updated = data.comment.updated;
797     found.comment.removed = data.comment.removed;
798     found.comment.deleted = data.comment.deleted;
799     found.counts.upvotes = data.counts.upvotes;
800     found.counts.downvotes = data.counts.downvotes;
801     found.counts.score = data.counts.score;
802   }
803 }
804
805 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
806   let found = comments.find(c => c.comment.id == data.comment.id);
807   if (found) {
808     found.saved = data.saved;
809   }
810 }
811
812 export function updatePersonBlock(
813   data: BlockPersonResponse
814 ): PersonBlockView[] {
815   if (data.blocked) {
816     UserService.Instance.myUserInfo.person_blocks.push({
817       person: UserService.Instance.myUserInfo.local_user_view.person,
818       target: data.person_view.person,
819     });
820     toast(`${i18n.t("blocked")} ${data.person_view.person.name}`);
821   } else {
822     UserService.Instance.myUserInfo.person_blocks =
823       UserService.Instance.myUserInfo.person_blocks.filter(
824         i => i.target.id != data.person_view.person.id
825       );
826     toast(`${i18n.t("unblocked")} ${data.person_view.person.name}`);
827   }
828   return UserService.Instance.myUserInfo.person_blocks;
829 }
830
831 export function updateCommunityBlock(
832   data: BlockCommunityResponse
833 ): CommunityBlockView[] {
834   if (data.blocked) {
835     UserService.Instance.myUserInfo.community_blocks.push({
836       person: UserService.Instance.myUserInfo.local_user_view.person,
837       community: data.community_view.community,
838     });
839     toast(`${i18n.t("blocked")} ${data.community_view.community.name}`);
840   } else {
841     UserService.Instance.myUserInfo.community_blocks =
842       UserService.Instance.myUserInfo.community_blocks.filter(
843         i => i.community.id != data.community_view.community.id
844       );
845     toast(`${i18n.t("unblocked")} ${data.community_view.community.name}`);
846   }
847   return UserService.Instance.myUserInfo.community_blocks;
848 }
849
850 export function createCommentLikeRes(
851   data: CommentView,
852   comments: CommentView[]
853 ) {
854   let found = comments.find(c => c.comment.id === data.comment.id);
855   if (found) {
856     found.counts.score = data.counts.score;
857     found.counts.upvotes = data.counts.upvotes;
858     found.counts.downvotes = data.counts.downvotes;
859     if (data.my_vote !== null) {
860       found.my_vote = data.my_vote;
861     }
862   }
863 }
864
865 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
866   let found = posts.find(p => p.post.id == data.post.id);
867   if (found) {
868     createPostLikeRes(data, found);
869   }
870 }
871
872 export function createPostLikeRes(data: PostView, post_view: PostView) {
873   if (post_view) {
874     post_view.counts.score = data.counts.score;
875     post_view.counts.upvotes = data.counts.upvotes;
876     post_view.counts.downvotes = data.counts.downvotes;
877     if (data.my_vote !== null) {
878       post_view.my_vote = data.my_vote;
879     }
880   }
881 }
882
883 export function editPostFindRes(data: PostView, posts: PostView[]) {
884   let found = posts.find(p => p.post.id == data.post.id);
885   if (found) {
886     editPostRes(data, found);
887   }
888 }
889
890 export function editPostRes(data: PostView, post: PostView) {
891   if (post) {
892     post.post.url = data.post.url;
893     post.post.name = data.post.name;
894     post.post.nsfw = data.post.nsfw;
895     post.post.deleted = data.post.deleted;
896     post.post.removed = data.post.removed;
897     post.post.stickied = data.post.stickied;
898     post.post.body = data.post.body;
899     post.post.locked = data.post.locked;
900     post.saved = data.saved;
901   }
902 }
903
904 export function updatePostReportRes(
905   data: PostReportView,
906   reports: PostReportView[]
907 ) {
908   let found = reports.find(p => p.post_report.id == data.post_report.id);
909   if (found) {
910     found.post_report = data.post_report;
911   }
912 }
913
914 export function updateCommentReportRes(
915   data: CommentReportView,
916   reports: CommentReportView[]
917 ) {
918   let found = reports.find(c => c.comment_report.id == data.comment_report.id);
919   if (found) {
920     found.comment_report = data.comment_report;
921   }
922 }
923
924 export function updateRegistrationApplicationRes(
925   data: RegistrationApplicationView,
926   applications: RegistrationApplicationView[]
927 ) {
928   let found = applications.find(
929     ra => ra.registration_application.id == data.registration_application.id
930   );
931   if (found) {
932     found.registration_application = data.registration_application;
933     found.admin = data.admin;
934     found.creator_local_user = data.creator_local_user;
935   }
936 }
937
938 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
939   let nodes: CommentNodeI[] = [];
940   for (let comment of comments) {
941     nodes.push({ comment_view: comment });
942   }
943   return nodes;
944 }
945
946 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
947   // First, put removed and deleted comments at the bottom, then do your other sorts
948   if (sort == CommentSortType.Top) {
949     tree.sort(
950       (a, b) =>
951         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
952         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
953         b.comment_view.counts.score - a.comment_view.counts.score
954     );
955   } else if (sort == CommentSortType.New) {
956     tree.sort(
957       (a, b) =>
958         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
959         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
960         b.comment_view.comment.published.localeCompare(
961           a.comment_view.comment.published
962         )
963     );
964   } else if (sort == CommentSortType.Old) {
965     tree.sort(
966       (a, b) =>
967         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
968         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
969         a.comment_view.comment.published.localeCompare(
970           b.comment_view.comment.published
971         )
972     );
973   } else if (sort == CommentSortType.Hot) {
974     tree.sort(
975       (a, b) =>
976         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
977         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
978         hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
979     );
980   }
981
982   // Go through the children recursively
983   for (let node of tree) {
984     if (node.children) {
985       commentSort(node.children, sort);
986     }
987   }
988 }
989
990 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
991   commentSort(tree, convertCommentSortType(sort));
992 }
993
994 function convertCommentSortType(sort: SortType): CommentSortType {
995   if (
996     sort == SortType.TopAll ||
997     sort == SortType.TopDay ||
998     sort == SortType.TopWeek ||
999     sort == SortType.TopMonth ||
1000     sort == SortType.TopYear
1001   ) {
1002     return CommentSortType.Top;
1003   } else if (sort == SortType.New) {
1004     return CommentSortType.New;
1005   } else if (sort == SortType.Hot || sort == SortType.Active) {
1006     return CommentSortType.Hot;
1007   } else {
1008     return CommentSortType.Hot;
1009   }
1010 }
1011
1012 export function buildCommentsTree(
1013   comments: CommentView[],
1014   commentSortType: CommentSortType
1015 ): CommentNodeI[] {
1016   let map = new Map<number, CommentNodeI>();
1017   for (let comment_view of comments) {
1018     let node: CommentNodeI = {
1019       comment_view: comment_view,
1020       children: [],
1021     };
1022     map.set(comment_view.comment.id, { ...node });
1023   }
1024   let tree: CommentNodeI[] = [];
1025   for (let comment_view of comments) {
1026     let child = map.get(comment_view.comment.id);
1027     let parent_id = comment_view.comment.parent_id;
1028     if (parent_id) {
1029       let parent = map.get(parent_id);
1030       // Necessary because blocked comment might not exist
1031       if (parent) {
1032         parent.children.push(child);
1033       }
1034     } else {
1035       tree.push(child);
1036     }
1037
1038     setDepth(child);
1039   }
1040
1041   commentSort(tree, commentSortType);
1042
1043   return tree;
1044 }
1045
1046 function setDepth(node: CommentNodeI, i = 0) {
1047   for (let child of node.children) {
1048     child.depth = i;
1049     setDepth(child, i + 1);
1050   }
1051 }
1052
1053 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1054   // Building a fake node to be used for later
1055   let node: CommentNodeI = {
1056     comment_view: cv,
1057     children: [],
1058     depth: 0,
1059   };
1060
1061   if (cv.comment.parent_id) {
1062     let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1063     if (parentComment) {
1064       node.depth = parentComment.depth + 1;
1065       parentComment.children.unshift(node);
1066     }
1067   } else {
1068     tree.unshift(node);
1069   }
1070 }
1071
1072 export function searchCommentTree(
1073   tree: CommentNodeI[],
1074   id: number
1075 ): CommentNodeI {
1076   for (let node of tree) {
1077     if (node.comment_view.comment.id === id) {
1078       return node;
1079     }
1080
1081     for (const child of node.children) {
1082       const res = searchCommentTree([child], id);
1083
1084       if (res) {
1085         return res;
1086       }
1087     }
1088   }
1089   return null;
1090 }
1091
1092 export const colorList: string[] = [
1093   hsl(0),
1094   hsl(100),
1095   hsl(150),
1096   hsl(200),
1097   hsl(250),
1098   hsl(300),
1099 ];
1100
1101 function hsl(num: number) {
1102   return `hsla(${num}, 35%, 50%, 1)`;
1103 }
1104
1105 export function previewLines(
1106   text: string,
1107   maxChars = 300,
1108   maxLines = 1
1109 ): string {
1110   return (
1111     text
1112       .slice(0, maxChars)
1113       .split("\n")
1114       // Use lines * 2 because markdown requires 2 lines
1115       .slice(0, maxLines * 2)
1116       .join("\n") + "..."
1117   );
1118 }
1119
1120 export function hostname(url: string): string {
1121   let cUrl = new URL(url);
1122   return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1123 }
1124
1125 export function validTitle(title?: string): boolean {
1126   // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1127   if (title === null || title.length < 3) return true;
1128
1129   const regex = new RegExp(/.*\S.*/, "g");
1130
1131   return regex.test(title);
1132 }
1133
1134 export function siteBannerCss(banner: string): string {
1135   return ` \
1136     background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1137     background-attachment: fixed; \
1138     background-position: top; \
1139     background-repeat: no-repeat; \
1140     background-size: 100% cover; \
1141
1142     width: 100%; \
1143     max-height: 100vh; \
1144     `;
1145 }
1146
1147 export function isBrowser() {
1148   return typeof window !== "undefined";
1149 }
1150
1151 export function setIsoData(context: any): IsoData {
1152   let isoData: IsoData = isBrowser()
1153     ? window.isoData
1154     : context.router.staticContext;
1155   return isoData;
1156 }
1157
1158 export function wsSubscribe(parseMessage: any): Subscription {
1159   if (isBrowser()) {
1160     return WebSocketService.Instance.subject
1161       .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1162       .subscribe(
1163         msg => parseMessage(msg),
1164         err => console.error(err),
1165         () => console.log("complete")
1166       );
1167   } else {
1168     return null;
1169   }
1170 }
1171
1172 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1173   if (auth) {
1174     obj.auth = auth;
1175   }
1176 }
1177
1178 export function authField(
1179   throwErr = true,
1180   auth = UserService.Instance.auth
1181 ): string {
1182   if (auth == null && throwErr) {
1183     toast(i18n.t("not_logged_in"), "danger");
1184     throw "Not logged in";
1185   } else {
1186     return auth;
1187   }
1188 }
1189
1190 moment.updateLocale("en", {
1191   relativeTime: {
1192     future: "in %s",
1193     past: "%s ago",
1194     s: "<1m",
1195     ss: "%ds",
1196     m: "1m",
1197     mm: "%dm",
1198     h: "1h",
1199     hh: "%dh",
1200     d: "1d",
1201     dd: "%dd",
1202     w: "1w",
1203     ww: "%dw",
1204     M: "1M",
1205     MM: "%dM",
1206     y: "1Y",
1207     yy: "%dY",
1208   },
1209 });
1210
1211 export function saveScrollPosition(context: any) {
1212   let path: string = context.router.route.location.pathname;
1213   let y = window.scrollY;
1214   sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1215 }
1216
1217 export function restoreScrollPosition(context: any) {
1218   let path: string = context.router.route.location.pathname;
1219   let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1220   window.scrollTo(0, y);
1221 }
1222
1223 export function showLocal(isoData: IsoData): boolean {
1224   return isoData.site_res.federated_instances?.linked.length > 0;
1225 }
1226
1227 interface ChoicesValue {
1228   value: string;
1229   label: string;
1230 }
1231
1232 export function communityToChoice(cv: CommunityView): ChoicesValue {
1233   let choice: ChoicesValue = {
1234     value: cv.community.id.toString(),
1235     label: communitySelectName(cv),
1236   };
1237   return choice;
1238 }
1239
1240 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1241   let choice: ChoicesValue = {
1242     value: pvs.person.id.toString(),
1243     label: personSelectName(pvs),
1244   };
1245   return choice;
1246 }
1247
1248 export async function fetchCommunities(q: string) {
1249   let form: Search = {
1250     q,
1251     type_: SearchType.Communities,
1252     sort: SortType.TopAll,
1253     listing_type: ListingType.All,
1254     page: 1,
1255     limit: fetchLimit,
1256     auth: authField(false),
1257   };
1258   let client = new LemmyHttp(httpBase);
1259   return client.search(form);
1260 }
1261
1262 export async function fetchUsers(q: string) {
1263   let form: Search = {
1264     q,
1265     type_: SearchType.Users,
1266     sort: SortType.TopAll,
1267     listing_type: ListingType.All,
1268     page: 1,
1269     limit: fetchLimit,
1270     auth: authField(false),
1271   };
1272   let client = new LemmyHttp(httpBase);
1273   return client.search(form);
1274 }
1275
1276 export const choicesConfig = {
1277   shouldSort: false,
1278   searchResultLimit: fetchLimit,
1279   classNames: {
1280     containerOuter: "choices",
1281     containerInner: "choices__inner bg-secondary border-0",
1282     input: "form-control",
1283     inputCloned: "choices__input--cloned",
1284     list: "choices__list",
1285     listItems: "choices__list--multiple",
1286     listSingle: "choices__list--single",
1287     listDropdown: "choices__list--dropdown",
1288     item: "choices__item bg-secondary",
1289     itemSelectable: "choices__item--selectable",
1290     itemDisabled: "choices__item--disabled",
1291     itemChoice: "choices__item--choice",
1292     placeholder: "choices__placeholder",
1293     group: "choices__group",
1294     groupHeading: "choices__heading",
1295     button: "choices__button",
1296     activeState: "is-active",
1297     focusState: "is-focused",
1298     openState: "is-open",
1299     disabledState: "is-disabled",
1300     highlightedState: "text-info",
1301     selectedState: "text-info",
1302     flippedState: "is-flipped",
1303     loadingState: "is-loading",
1304     noResults: "has-no-results",
1305     noChoices: "has-no-choices",
1306   },
1307 };
1308
1309 export function communitySelectName(cv: CommunityView): string {
1310   return cv.community.local
1311     ? cv.community.title
1312     : `${hostname(cv.community.actor_id)}/${cv.community.title}`;
1313 }
1314
1315 export function personSelectName(pvs: PersonViewSafe): string {
1316   let pName = pvs.person.display_name || pvs.person.name;
1317   return pvs.person.local ? pName : `${hostname(pvs.person.actor_id)}/${pName}`;
1318 }
1319
1320 export function initializeSite(site: GetSiteResponse) {
1321   UserService.Instance.myUserInfo = site.my_user;
1322   i18n.changeLanguage(getLanguages()[0]);
1323 }
1324
1325 const SHORTNUM_SI_FORMAT = new Intl.NumberFormat("en-US", {
1326   maximumSignificantDigits: 3,
1327   //@ts-ignore
1328   notation: "compact",
1329   compactDisplay: "short",
1330 });
1331
1332 export function numToSI(value: number): string {
1333   return SHORTNUM_SI_FORMAT.format(value);
1334 }
1335
1336 export function isBanned(ps: PersonSafe): boolean {
1337   // Add Z to convert from UTC date
1338   if (ps.ban_expires) {
1339     if (ps.banned && new Date(ps.ban_expires + "Z") > new Date()) {
1340       return true;
1341     } else {
1342       return false;
1343     }
1344   } else {
1345     return ps.banned;
1346   }
1347 }