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