]> Untitled Git - lemmy-ui.git/blob - src/shared/utils.ts
Fix language bug on mobile browsers
[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 // TODO might need to add a user setting for this too
858 export function getDataTypeFromProps(props: any): DataType {
859   return props.match.params.data_type
860     ? routeDataTypeToEnum(props.match.params.data_type)
861     : DataType.Post;
862 }
863
864 export function getSortTypeFromProps(props: any): SortType {
865   return props.match.params.sort
866     ? routeSortTypeToEnum(props.match.params.sort)
867     : UserService.Instance.localUserView
868     ? Object.values(SortType)[
869         UserService.Instance.localUserView.local_user.default_sort_type
870       ]
871     : SortType.Active;
872 }
873
874 export function getPageFromProps(props: any): number {
875   return props.match.params.page ? Number(props.match.params.page) : 1;
876 }
877
878 export function getRecipientIdFromProps(props: any): number {
879   return props.match.params.recipient_id
880     ? Number(props.match.params.recipient_id)
881     : 1;
882 }
883
884 export function getIdFromProps(props: any): number {
885   return Number(props.match.params.id);
886 }
887
888 export function getCommentIdFromProps(props: any): number {
889   return Number(props.match.params.comment_id);
890 }
891
892 export function getUsernameFromProps(props: any): string {
893   return props.match.params.username;
894 }
895
896 export function editCommentRes(data: CommentView, comments: CommentView[]) {
897   let found = comments.find(c => c.comment.id == data.comment.id);
898   if (found) {
899     found.comment.content = data.comment.content;
900     found.comment.updated = data.comment.updated;
901     found.comment.removed = data.comment.removed;
902     found.comment.deleted = data.comment.deleted;
903     found.counts.upvotes = data.counts.upvotes;
904     found.counts.downvotes = data.counts.downvotes;
905     found.counts.score = data.counts.score;
906   }
907 }
908
909 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
910   let found = comments.find(c => c.comment.id == data.comment.id);
911   if (found) {
912     found.saved = data.saved;
913   }
914 }
915
916 export function createCommentLikeRes(
917   data: CommentView,
918   comments: CommentView[]
919 ) {
920   let found = comments.find(c => c.comment.id === data.comment.id);
921   if (found) {
922     found.counts.score = data.counts.score;
923     found.counts.upvotes = data.counts.upvotes;
924     found.counts.downvotes = data.counts.downvotes;
925     if (data.my_vote !== null) {
926       found.my_vote = data.my_vote;
927     }
928   }
929 }
930
931 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
932   let found = posts.find(p => p.post.id == data.post.id);
933   if (found) {
934     createPostLikeRes(data, found);
935   }
936 }
937
938 export function createPostLikeRes(data: PostView, post_view: PostView) {
939   if (post_view) {
940     post_view.counts.score = data.counts.score;
941     post_view.counts.upvotes = data.counts.upvotes;
942     post_view.counts.downvotes = data.counts.downvotes;
943     if (data.my_vote !== null) {
944       post_view.my_vote = data.my_vote;
945     }
946   }
947 }
948
949 export function editPostFindRes(data: PostView, posts: PostView[]) {
950   let found = posts.find(p => p.post.id == data.post.id);
951   if (found) {
952     editPostRes(data, found);
953   }
954 }
955
956 export function editPostRes(data: PostView, post: PostView) {
957   if (post) {
958     post.post.url = data.post.url;
959     post.post.name = data.post.name;
960     post.post.nsfw = data.post.nsfw;
961     post.post.deleted = data.post.deleted;
962     post.post.removed = data.post.removed;
963     post.post.stickied = data.post.stickied;
964     post.post.body = data.post.body;
965     post.post.locked = data.post.locked;
966     post.saved = data.saved;
967   }
968 }
969
970 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
971   let nodes: CommentNodeI[] = [];
972   for (let comment of comments) {
973     nodes.push({ comment_view: comment });
974   }
975   return nodes;
976 }
977
978 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
979   // First, put removed and deleted comments at the bottom, then do your other sorts
980   if (sort == CommentSortType.Top) {
981     tree.sort(
982       (a, b) =>
983         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
984         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
985         b.comment_view.counts.score - a.comment_view.counts.score
986     );
987   } else if (sort == CommentSortType.New) {
988     tree.sort(
989       (a, b) =>
990         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
991         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
992         b.comment_view.comment.published.localeCompare(
993           a.comment_view.comment.published
994         )
995     );
996   } else if (sort == CommentSortType.Old) {
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         a.comment_view.comment.published.localeCompare(
1002           b.comment_view.comment.published
1003         )
1004     );
1005   } else if (sort == CommentSortType.Hot) {
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         hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
1011     );
1012   }
1013
1014   // Go through the children recursively
1015   for (let node of tree) {
1016     if (node.children) {
1017       commentSort(node.children, sort);
1018     }
1019   }
1020 }
1021
1022 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
1023   commentSort(tree, convertCommentSortType(sort));
1024 }
1025
1026 function convertCommentSortType(sort: SortType): CommentSortType {
1027   if (
1028     sort == SortType.TopAll ||
1029     sort == SortType.TopDay ||
1030     sort == SortType.TopWeek ||
1031     sort == SortType.TopMonth ||
1032     sort == SortType.TopYear
1033   ) {
1034     return CommentSortType.Top;
1035   } else if (sort == SortType.New) {
1036     return CommentSortType.New;
1037   } else if (sort == SortType.Hot || sort == SortType.Active) {
1038     return CommentSortType.Hot;
1039   } else {
1040     return CommentSortType.Hot;
1041   }
1042 }
1043
1044 export function buildCommentsTree(
1045   comments: CommentView[],
1046   commentSortType: CommentSortType
1047 ): CommentNodeI[] {
1048   let map = new Map<number, CommentNodeI>();
1049   for (let comment_view of comments) {
1050     let node: CommentNodeI = {
1051       comment_view: comment_view,
1052       children: [],
1053     };
1054     map.set(comment_view.comment.id, { ...node });
1055   }
1056   let tree: CommentNodeI[] = [];
1057   for (let comment_view of comments) {
1058     let child = map.get(comment_view.comment.id);
1059     if (comment_view.comment.parent_id) {
1060       let parent_ = map.get(comment_view.comment.parent_id);
1061       parent_.children.push(child);
1062     } else {
1063       tree.push(child);
1064     }
1065
1066     setDepth(child);
1067   }
1068
1069   commentSort(tree, commentSortType);
1070
1071   return tree;
1072 }
1073
1074 function setDepth(node: CommentNodeI, i = 0) {
1075   for (let child of node.children) {
1076     child.depth = i;
1077     setDepth(child, i + 1);
1078   }
1079 }
1080
1081 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1082   // Building a fake node to be used for later
1083   let node: CommentNodeI = {
1084     comment_view: cv,
1085     children: [],
1086     depth: 0,
1087   };
1088
1089   if (cv.comment.parent_id) {
1090     let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1091     if (parentComment) {
1092       node.depth = parentComment.depth + 1;
1093       parentComment.children.unshift(node);
1094     }
1095   } else {
1096     tree.unshift(node);
1097   }
1098 }
1099
1100 export function searchCommentTree(
1101   tree: CommentNodeI[],
1102   id: number
1103 ): CommentNodeI {
1104   for (let node of tree) {
1105     if (node.comment_view.comment.id === id) {
1106       return node;
1107     }
1108
1109     for (const child of node.children) {
1110       const res = searchCommentTree([child], id);
1111
1112       if (res) {
1113         return res;
1114       }
1115     }
1116   }
1117   return null;
1118 }
1119
1120 export const colorList: string[] = [
1121   hsl(0),
1122   hsl(100),
1123   hsl(150),
1124   hsl(200),
1125   hsl(250),
1126   hsl(300),
1127 ];
1128
1129 function hsl(num: number) {
1130   return `hsla(${num}, 35%, 50%, 1)`;
1131 }
1132
1133 export function previewLines(
1134   text: string,
1135   maxChars = 300,
1136   maxLines = 1
1137 ): string {
1138   return (
1139     text
1140       .slice(0, maxChars)
1141       .split("\n")
1142       // Use lines * 2 because markdown requires 2 lines
1143       .slice(0, maxLines * 2)
1144       .join("\n") + "..."
1145   );
1146 }
1147
1148 export function hostname(url: string): string {
1149   let cUrl = new URL(url);
1150   return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1151 }
1152
1153 export function validTitle(title?: string): boolean {
1154   // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1155   if (title === null || title.length < 3) return true;
1156
1157   const regex = new RegExp(/.*\S.*/, "g");
1158
1159   return regex.test(title);
1160 }
1161
1162 export function siteBannerCss(banner: string): string {
1163   return ` \
1164     background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1165     background-attachment: fixed; \
1166     background-position: top; \
1167     background-repeat: no-repeat; \
1168     background-size: 100% cover; \
1169
1170     width: 100%; \
1171     max-height: 100vh; \
1172     `;
1173 }
1174
1175 export function isBrowser() {
1176   return typeof window !== "undefined";
1177 }
1178
1179 export function setIsoData(context: any): IsoData {
1180   let isoData: IsoData = isBrowser()
1181     ? window.isoData
1182     : context.router.staticContext;
1183   return isoData;
1184 }
1185
1186 export function wsSubscribe(parseMessage: any): Subscription {
1187   if (isBrowser()) {
1188     return WebSocketService.Instance.subject
1189       .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1190       .subscribe(
1191         msg => parseMessage(msg),
1192         err => console.error(err),
1193         () => console.log("complete")
1194       );
1195   } else {
1196     return null;
1197   }
1198 }
1199
1200 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1201   if (auth) {
1202     obj.auth = auth;
1203   }
1204 }
1205
1206 export function authField(
1207   throwErr = true,
1208   auth = UserService.Instance.auth
1209 ): string {
1210   if (auth == null && throwErr) {
1211     toast(i18n.t("not_logged_in"), "danger");
1212     throw "Not logged in";
1213   } else {
1214     return auth;
1215   }
1216 }
1217
1218 moment.updateLocale("en", {
1219   relativeTime: {
1220     future: "in %s",
1221     past: "%s ago",
1222     s: "<1m",
1223     ss: "%ds",
1224     m: "1m",
1225     mm: "%dm",
1226     h: "1h",
1227     hh: "%dh",
1228     d: "1d",
1229     dd: "%dd",
1230     w: "1w",
1231     ww: "%dw",
1232     M: "1M",
1233     MM: "%dM",
1234     y: "1Y",
1235     yy: "%dY",
1236   },
1237 });
1238
1239 export function saveScrollPosition(context: any) {
1240   let path: string = context.router.route.location.pathname;
1241   let y = window.scrollY;
1242   sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1243 }
1244
1245 export function restoreScrollPosition(context: any) {
1246   let path: string = context.router.route.location.pathname;
1247   let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1248   window.scrollTo(0, y);
1249 }
1250
1251 export function showLocal(isoData: IsoData): boolean {
1252   return isoData.site_res.federated_instances?.linked.length > 0;
1253 }
1254
1255 interface ChoicesValue {
1256   value: string;
1257   label: string;
1258 }
1259
1260 export function communityToChoice(cv: CommunityView): ChoicesValue {
1261   let choice: ChoicesValue = {
1262     value: cv.community.id.toString(),
1263     label: communitySelectName(cv),
1264   };
1265   return choice;
1266 }
1267
1268 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1269   let choice: ChoicesValue = {
1270     value: pvs.person.id.toString(),
1271     label: personSelectName(pvs),
1272   };
1273   return choice;
1274 }
1275
1276 export async function fetchCommunities(q: string) {
1277   let form: Search = {
1278     q,
1279     type_: SearchType.Communities,
1280     sort: SortType.TopAll,
1281     listing_type: ListingType.All,
1282     page: 1,
1283     limit: fetchLimit,
1284     auth: authField(false),
1285   };
1286   let client = new LemmyHttp(httpBase);
1287   return client.search(form);
1288 }
1289
1290 export async function fetchUsers(q: string) {
1291   let form: Search = {
1292     q,
1293     type_: SearchType.Users,
1294     sort: SortType.TopAll,
1295     listing_type: ListingType.All,
1296     page: 1,
1297     limit: fetchLimit,
1298     auth: authField(false),
1299   };
1300   let client = new LemmyHttp(httpBase);
1301   return client.search(form);
1302 }
1303
1304 export const choicesConfig = {
1305   shouldSort: false,
1306   searchResultLimit: fetchLimit,
1307   classNames: {
1308     containerOuter: "choices",
1309     containerInner: "choices__inner bg-light border-0",
1310     input: "form-control",
1311     inputCloned: "choices__input--cloned",
1312     list: "choices__list",
1313     listItems: "choices__list--multiple",
1314     listSingle: "choices__list--single",
1315     listDropdown: "choices__list--dropdown",
1316     item: "choices__item bg-light",
1317     itemSelectable: "choices__item--selectable",
1318     itemDisabled: "choices__item--disabled",
1319     itemChoice: "choices__item--choice",
1320     placeholder: "choices__placeholder",
1321     group: "choices__group",
1322     groupHeading: "choices__heading",
1323     button: "choices__button",
1324     activeState: "is-active",
1325     focusState: "is-focused",
1326     openState: "is-open",
1327     disabledState: "is-disabled",
1328     highlightedState: "text-info",
1329     selectedState: "text-info",
1330     flippedState: "is-flipped",
1331     loadingState: "is-loading",
1332     noResults: "has-no-results",
1333     noChoices: "has-no-choices",
1334   },
1335 };
1336
1337 export function communitySelectName(cv: CommunityView): string {
1338   return cv.community.local
1339     ? cv.community.name
1340     : `${hostname(cv.community.actor_id)}/${cv.community.name}`;
1341 }
1342
1343 export function personSelectName(pvs: PersonViewSafe): string {
1344   return pvs.person.local
1345     ? pvs.person.name
1346     : `${hostname(pvs.person.actor_id)}/${pvs.person.name}`;
1347 }
1348
1349 export function initializeSite(site: GetSiteResponse) {
1350   UserService.Instance.localUserView = site.my_user;
1351   i18n.changeLanguage(getLanguage());
1352 }