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