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