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