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