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