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