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