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