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