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