]> Untitled Git - lemmy-ui.git/blob - src/shared/utils.ts
Merge pull request #322 from LemmyNet/fix/comment_collapse
[lemmy-ui.git] / src / shared / utils.ts
1 import "moment/locale/es";
2 import "moment/locale/el";
3 import "moment/locale/eu";
4 import "moment/locale/eo";
5 import "moment/locale/de";
6 import "moment/locale/zh-cn";
7 import "moment/locale/fr";
8 import "moment/locale/sv";
9 import "moment/locale/ru";
10 import "moment/locale/nl";
11 import "moment/locale/it";
12 import "moment/locale/fi";
13 import "moment/locale/ca";
14 import "moment/locale/fa";
15 import "moment/locale/pl";
16 import "moment/locale/pt-br";
17 import "moment/locale/ja";
18 import "moment/locale/ka";
19 import "moment/locale/hi";
20 import "moment/locale/gl";
21 import "moment/locale/tr";
22 import "moment/locale/hu";
23 import "moment/locale/uk";
24 import "moment/locale/sq";
25 import "moment/locale/km";
26 import "moment/locale/ga";
27 import "moment/locale/sr";
28 import "moment/locale/ko";
29 import "moment/locale/da";
30 import "moment/locale/hr";
31 import "moment/locale/bg";
32 import "moment/locale/id";
33 import "moment/locale/nb";
34
35 import {
36   UserOperation,
37   CommentView,
38   LocalUserSettingsView,
39   SortType,
40   ListingType,
41   SearchType,
42   WebSocketResponse,
43   WebSocketJsonResponse,
44   Search,
45   SearchResponse,
46   PostView,
47   PrivateMessageView,
48   LemmyWebsocket,
49   PersonViewSafe,
50   CommunityView,
51   LemmyHttp,
52 } from "lemmy-js-client";
53
54 import {
55   CommentSortType,
56   DataType,
57   IsoData,
58   CommentNode as CommentNodeI,
59 } from "./interfaces";
60 import { UserService, WebSocketService } from "./services";
61 var Tribute: any;
62 if (isBrowser()) {
63   Tribute = require("tributejs");
64 }
65 import markdown_it from "markdown-it";
66 import markdown_it_sub from "markdown-it-sub";
67 import markdown_it_sup from "markdown-it-sup";
68 import markdown_it_container from "markdown-it-container";
69 import emojiShortName from "emoji-short-name";
70 import Toastify from "toastify-js";
71 import tippy from "tippy.js";
72 import moment from "moment";
73 import { Subscription } from "rxjs";
74 import { retryWhen, delay, take } from "rxjs/operators";
75 import { i18n } from "./i18next";
76 import { httpBase } from "./env";
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   let allowedLangs = navigator.languages.filter(v => langs.includes(v)) || [
398     "en",
399   ];
400   return allowedLangs[0];
401 }
402
403 export function getMomentLanguage(): string {
404   let lang = getLanguage();
405   if (lang.startsWith("zh")) {
406     lang = "zh-cn";
407   } else if (lang.startsWith("sv")) {
408     lang = "sv";
409   } else if (lang.startsWith("fr")) {
410     lang = "fr";
411   } else if (lang.startsWith("de")) {
412     lang = "de";
413   } else if (lang.startsWith("ru")) {
414     lang = "ru";
415   } else if (lang.startsWith("es")) {
416     lang = "es";
417   } else if (lang.startsWith("eo")) {
418     lang = "eo";
419   } else if (lang.startsWith("nl")) {
420     lang = "nl";
421   } else if (lang.startsWith("it")) {
422     lang = "it";
423   } else if (lang.startsWith("fi")) {
424     lang = "fi";
425   } else if (lang.startsWith("ca")) {
426     lang = "ca";
427   } else if (lang.startsWith("fa")) {
428     lang = "fa";
429   } else if (lang.startsWith("pl")) {
430     lang = "pl";
431   } else if (lang.startsWith("pt")) {
432     lang = "pt-br";
433   } else if (lang.startsWith("ja")) {
434     lang = "ja";
435   } else if (lang.startsWith("ka")) {
436     lang = "ka";
437   } else if (lang.startsWith("hi")) {
438     lang = "hi";
439   } else if (lang.startsWith("el")) {
440     lang = "el";
441   } else if (lang.startsWith("eu")) {
442     lang = "eu";
443   } else if (lang.startsWith("gl")) {
444     lang = "gl";
445   } else if (lang.startsWith("tr")) {
446     lang = "tr";
447   } else if (lang.startsWith("hu")) {
448     lang = "hu";
449   } else if (lang.startsWith("uk")) {
450     lang = "uk";
451   } else if (lang.startsWith("sq")) {
452     lang = "sq";
453   } else if (lang.startsWith("km")) {
454     lang = "km";
455   } else if (lang.startsWith("ga")) {
456     lang = "ga";
457   } else if (lang.startsWith("sr")) {
458     lang = "sr";
459   } else if (lang.startsWith("ko")) {
460     lang = "ko";
461   } else if (lang.startsWith("da")) {
462     lang = "da";
463   } else if (lang.startsWith("oc")) {
464     lang = "oc";
465   } else if (lang.startsWith("hr")) {
466     lang = "hr";
467   } else if (lang.startsWith("th")) {
468     lang = "th";
469   } else if (lang.startsWith("bg")) {
470     lang = "bg";
471   } else if (lang.startsWith("id")) {
472     lang = "id";
473   } else if (lang.startsWith("nb")) {
474     lang = "nb";
475   } else {
476     lang = "en";
477   }
478   return lang;
479 }
480
481 export function setTheme(theme: string, forceReload = false) {
482   if (!isBrowser()) {
483     return;
484   }
485   if (theme === "browser" && !forceReload) {
486     return;
487   }
488   // This is only run on a force reload
489   if (theme == "browser") {
490     theme = "darkly";
491   }
492
493   // Unload all the other themes
494   for (var i = 0; i < themes.length; i++) {
495     let styleSheet = document.getElementById(themes[i]);
496     if (styleSheet) {
497       styleSheet.setAttribute("disabled", "disabled");
498     }
499   }
500
501   document
502     .getElementById("default-light")
503     ?.setAttribute("disabled", "disabled");
504   document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
505
506   // Load the theme dynamically
507   let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
508   loadCss(theme, cssLoc);
509   document.getElementById(theme).removeAttribute("disabled");
510 }
511
512 export function loadCss(id: string, loc: string) {
513   if (!document.getElementById(id)) {
514     var head = document.getElementsByTagName("head")[0];
515     var link = document.createElement("link");
516     link.id = id;
517     link.rel = "stylesheet";
518     link.type = "text/css";
519     link.href = loc;
520     link.media = "all";
521     head.appendChild(link);
522   }
523 }
524
525 export function objectFlip(obj: any) {
526   const ret = {};
527   Object.keys(obj).forEach(key => {
528     ret[obj[key]] = key;
529   });
530   return ret;
531 }
532
533 export function showAvatars(): boolean {
534   return (
535     UserService.Instance.localUserView?.local_user.show_avatars ||
536     !UserService.Instance.localUserView
537   );
538 }
539
540 export function showScores(): boolean {
541   return (
542     UserService.Instance.localUserView?.local_user.show_scores ||
543     !UserService.Instance.localUserView
544   );
545 }
546
547 export function isCakeDay(published: string): boolean {
548   // moment(undefined) or moment.utc(undefined) returns the current date/time
549   // moment(null) or moment.utc(null) returns null
550   const createDate = moment.utc(published || null).local();
551   const currentDate = moment(new Date());
552
553   return (
554     createDate.date() === currentDate.date() &&
555     createDate.month() === currentDate.month() &&
556     createDate.year() !== currentDate.year()
557   );
558 }
559
560 export function toast(text: string, background = "success") {
561   if (isBrowser()) {
562     let backgroundColor = `var(--${background})`;
563     Toastify({
564       text: text,
565       backgroundColor: backgroundColor,
566       gravity: "bottom",
567       position: "left",
568     }).showToast();
569   }
570 }
571
572 export function pictrsDeleteToast(
573   clickToDeleteText: string,
574   deletePictureText: string,
575   deleteUrl: string
576 ) {
577   if (isBrowser()) {
578     let backgroundColor = `var(--light)`;
579     let toast = Toastify({
580       text: clickToDeleteText,
581       backgroundColor: backgroundColor,
582       gravity: "top",
583       position: "right",
584       duration: 10000,
585       onClick: () => {
586         if (toast) {
587           window.location.replace(deleteUrl);
588           alert(deletePictureText);
589           toast.hideToast();
590         }
591       },
592       close: true,
593     }).showToast();
594   }
595 }
596
597 interface NotifyInfo {
598   name: string;
599   icon?: string;
600   link: string;
601   body: string;
602 }
603
604 export function messageToastify(info: NotifyInfo, router: any) {
605   if (isBrowser()) {
606     let htmlBody = info.body ? md.render(info.body) : "";
607     let backgroundColor = `var(--light)`;
608
609     let toast = Toastify({
610       text: `${htmlBody}<br />${info.name}`,
611       avatar: info.icon ? info.icon : null,
612       backgroundColor: backgroundColor,
613       className: "text-dark",
614       close: true,
615       gravity: "top",
616       position: "right",
617       duration: 5000,
618       escapeMarkup: false,
619       onClick: () => {
620         if (toast) {
621           toast.hideToast();
622           router.history.push(info.link);
623         }
624       },
625     }).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: `/post/${comment_view.post.id}/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       icon: info.icon,
666       body: info.body,
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: (text: string, cb: (persons: PersonTribute[]) => any) => {
709           personSearch(text, (persons: PersonTribute[]) => cb(persons));
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: (text: string, cb: any) => {
726           communitySearch(text, (communities: CommunityTribute[]) =>
727             cb(communities)
728           );
729         },
730         allowSpaces: false,
731         autocompleteMode: true,
732         // TODO
733         // menuItemLimit: mentionDropdownFetchLimit,
734         menuShowMinLength: 2,
735       },
736     ],
737   });
738 }
739
740 var tippyInstance: any;
741 if (isBrowser()) {
742   tippyInstance = tippy("[data-tippy-content]");
743 }
744
745 export function setupTippy() {
746   if (isBrowser()) {
747     tippyInstance.forEach((e: any) => e.destroy());
748     tippyInstance = tippy("[data-tippy-content]", {
749       delay: [500, 0],
750       // Display on "long press"
751       touch: ["hold", 500],
752     });
753   }
754 }
755
756 interface PersonTribute {
757   key: string;
758   view: PersonViewSafe;
759 }
760
761 function personSearch(text: string, cb: (persons: PersonTribute[]) => any) {
762   if (text) {
763     let form: Search = {
764       q: text,
765       type_: SearchType.Users,
766       sort: SortType.TopAll,
767       listing_type: ListingType.All,
768       page: 1,
769       limit: mentionDropdownFetchLimit,
770       auth: authField(false),
771     };
772
773     WebSocketService.Instance.send(wsClient.search(form));
774
775     let personSub = WebSocketService.Instance.subject.subscribe(
776       msg => {
777         let res = wsJsonToRes(msg);
778         if (res.op == UserOperation.Search) {
779           let data = res.data as SearchResponse;
780           let persons: PersonTribute[] = data.users.map(pv => {
781             let tribute: PersonTribute = {
782               key: `@${pv.person.name}@${hostname(pv.person.actor_id)}`,
783               view: pv,
784             };
785             return tribute;
786           });
787           cb(persons);
788           personSub.unsubscribe();
789         }
790       },
791       err => console.error(err),
792       () => console.log("complete")
793     );
794   } else {
795     cb([]);
796   }
797 }
798
799 interface CommunityTribute {
800   key: string;
801   view: CommunityView;
802 }
803
804 function communitySearch(
805   text: string,
806   cb: (communities: CommunityTribute[]) => any
807 ) {
808   if (text) {
809     let form: Search = {
810       q: text,
811       type_: SearchType.Communities,
812       sort: SortType.TopAll,
813       listing_type: ListingType.All,
814       page: 1,
815       limit: mentionDropdownFetchLimit,
816       auth: authField(false),
817     };
818
819     WebSocketService.Instance.send(wsClient.search(form));
820
821     let communitySub = WebSocketService.Instance.subject.subscribe(
822       msg => {
823         let res = wsJsonToRes(msg);
824         if (res.op == UserOperation.Search) {
825           let data = res.data as SearchResponse;
826           let communities: CommunityTribute[] = data.communities.map(cv => {
827             let tribute: CommunityTribute = {
828               key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
829               view: cv,
830             };
831             return tribute;
832           });
833           cb(communities);
834           communitySub.unsubscribe();
835         }
836       },
837       err => console.error(err),
838       () => console.log("complete")
839     );
840   } else {
841     cb([]);
842   }
843 }
844
845 export function getListingTypeFromProps(props: any): ListingType {
846   return props.match.params.listing_type
847     ? routeListingTypeToEnum(props.match.params.listing_type)
848     : UserService.Instance.localUserView
849     ? Object.values(ListingType)[
850         UserService.Instance.localUserView.local_user.default_listing_type
851       ]
852     : ListingType.Local;
853 }
854
855 // TODO might need to add a user setting for this too
856 export function getDataTypeFromProps(props: any): DataType {
857   return props.match.params.data_type
858     ? routeDataTypeToEnum(props.match.params.data_type)
859     : DataType.Post;
860 }
861
862 export function getSortTypeFromProps(props: any): SortType {
863   return props.match.params.sort
864     ? routeSortTypeToEnum(props.match.params.sort)
865     : UserService.Instance.localUserView
866     ? Object.values(SortType)[
867         UserService.Instance.localUserView.local_user.default_sort_type
868       ]
869     : SortType.Active;
870 }
871
872 export function getPageFromProps(props: any): number {
873   return props.match.params.page ? Number(props.match.params.page) : 1;
874 }
875
876 export function getRecipientIdFromProps(props: any): number {
877   return props.match.params.recipient_id
878     ? Number(props.match.params.recipient_id)
879     : 1;
880 }
881
882 export function getIdFromProps(props: any): number {
883   return Number(props.match.params.id);
884 }
885
886 export function getCommentIdFromProps(props: any): number {
887   return Number(props.match.params.comment_id);
888 }
889
890 export function getUsernameFromProps(props: any): string {
891   return props.match.params.username;
892 }
893
894 export function editCommentRes(data: CommentView, comments: CommentView[]) {
895   let found = comments.find(c => c.comment.id == data.comment.id);
896   if (found) {
897     found.comment.content = data.comment.content;
898     found.comment.updated = data.comment.updated;
899     found.comment.removed = data.comment.removed;
900     found.comment.deleted = data.comment.deleted;
901     found.counts.upvotes = data.counts.upvotes;
902     found.counts.downvotes = data.counts.downvotes;
903     found.counts.score = data.counts.score;
904   }
905 }
906
907 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
908   let found = comments.find(c => c.comment.id == data.comment.id);
909   if (found) {
910     found.saved = data.saved;
911   }
912 }
913
914 export function createCommentLikeRes(
915   data: CommentView,
916   comments: CommentView[]
917 ) {
918   let found = comments.find(c => c.comment.id === data.comment.id);
919   if (found) {
920     found.counts.score = data.counts.score;
921     found.counts.upvotes = data.counts.upvotes;
922     found.counts.downvotes = data.counts.downvotes;
923     if (data.my_vote !== null) {
924       found.my_vote = data.my_vote;
925     }
926   }
927 }
928
929 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
930   let found = posts.find(p => p.post.id == data.post.id);
931   if (found) {
932     createPostLikeRes(data, found);
933   }
934 }
935
936 export function createPostLikeRes(data: PostView, post_view: PostView) {
937   if (post_view) {
938     post_view.counts.score = data.counts.score;
939     post_view.counts.upvotes = data.counts.upvotes;
940     post_view.counts.downvotes = data.counts.downvotes;
941     if (data.my_vote !== null) {
942       post_view.my_vote = data.my_vote;
943     }
944   }
945 }
946
947 export function editPostFindRes(data: PostView, posts: PostView[]) {
948   let found = posts.find(p => p.post.id == data.post.id);
949   if (found) {
950     editPostRes(data, found);
951   }
952 }
953
954 export function editPostRes(data: PostView, post: PostView) {
955   if (post) {
956     post.post.url = data.post.url;
957     post.post.name = data.post.name;
958     post.post.nsfw = data.post.nsfw;
959     post.post.deleted = data.post.deleted;
960     post.post.removed = data.post.removed;
961     post.post.stickied = data.post.stickied;
962     post.post.body = data.post.body;
963     post.post.locked = data.post.locked;
964     post.saved = data.saved;
965   }
966 }
967
968 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
969   let nodes: CommentNodeI[] = [];
970   for (let comment of comments) {
971     nodes.push({ comment_view: comment });
972   }
973   return nodes;
974 }
975
976 function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
977   // First, put removed and deleted comments at the bottom, then do your other sorts
978   if (sort == CommentSortType.Top) {
979     tree.sort(
980       (a, b) =>
981         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
982         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
983         b.comment_view.counts.score - a.comment_view.counts.score
984     );
985   } else if (sort == CommentSortType.New) {
986     tree.sort(
987       (a, b) =>
988         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
989         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
990         b.comment_view.comment.published.localeCompare(
991           a.comment_view.comment.published
992         )
993     );
994   } else if (sort == CommentSortType.Old) {
995     tree.sort(
996       (a, b) =>
997         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
998         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
999         a.comment_view.comment.published.localeCompare(
1000           b.comment_view.comment.published
1001         )
1002     );
1003   } else if (sort == CommentSortType.Hot) {
1004     tree.sort(
1005       (a, b) =>
1006         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
1007         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
1008         hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
1009     );
1010   }
1011
1012   // Go through the children recursively
1013   for (let node of tree) {
1014     if (node.children) {
1015       commentSort(node.children, sort);
1016     }
1017   }
1018 }
1019
1020 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
1021   commentSort(tree, convertCommentSortType(sort));
1022 }
1023
1024 function convertCommentSortType(sort: SortType): CommentSortType {
1025   if (
1026     sort == SortType.TopAll ||
1027     sort == SortType.TopDay ||
1028     sort == SortType.TopWeek ||
1029     sort == SortType.TopMonth ||
1030     sort == SortType.TopYear
1031   ) {
1032     return CommentSortType.Top;
1033   } else if (sort == SortType.New) {
1034     return CommentSortType.New;
1035   } else if (sort == SortType.Hot || sort == SortType.Active) {
1036     return CommentSortType.Hot;
1037   } else {
1038     return CommentSortType.Hot;
1039   }
1040 }
1041
1042 export function buildCommentsTree(
1043   comments: CommentView[],
1044   commentSortType: CommentSortType
1045 ): CommentNodeI[] {
1046   let map = new Map<number, CommentNodeI>();
1047   for (let comment_view of comments) {
1048     let node: CommentNodeI = {
1049       comment_view: comment_view,
1050       children: [],
1051     };
1052     map.set(comment_view.comment.id, { ...node });
1053   }
1054   let tree: CommentNodeI[] = [];
1055   for (let comment_view of comments) {
1056     let child = map.get(comment_view.comment.id);
1057     if (comment_view.comment.parent_id) {
1058       let parent_ = map.get(comment_view.comment.parent_id);
1059       parent_.children.push(child);
1060     } else {
1061       tree.push(child);
1062     }
1063
1064     setDepth(child);
1065   }
1066
1067   commentSort(tree, commentSortType);
1068
1069   return tree;
1070 }
1071
1072 function setDepth(node: CommentNodeI, i = 0) {
1073   for (let child of node.children) {
1074     child.depth = i;
1075     setDepth(child, i + 1);
1076   }
1077 }
1078
1079 export function insertCommentIntoTree(tree: CommentNodeI[], cv: CommentView) {
1080   // Building a fake node to be used for later
1081   let node: CommentNodeI = {
1082     comment_view: cv,
1083     children: [],
1084     depth: 0,
1085   };
1086
1087   if (cv.comment.parent_id) {
1088     let parentComment = searchCommentTree(tree, cv.comment.parent_id);
1089     if (parentComment) {
1090       node.depth = parentComment.depth + 1;
1091       parentComment.children.unshift(node);
1092     }
1093   } else {
1094     tree.unshift(node);
1095   }
1096 }
1097
1098 export function searchCommentTree(
1099   tree: CommentNodeI[],
1100   id: number
1101 ): CommentNodeI {
1102   for (let node of tree) {
1103     if (node.comment_view.comment.id === id) {
1104       return node;
1105     }
1106
1107     for (const child of node.children) {
1108       const res = searchCommentTree([child], id);
1109
1110       if (res) {
1111         return res;
1112       }
1113     }
1114   }
1115   return null;
1116 }
1117
1118 export const colorList: string[] = [
1119   hsl(0),
1120   hsl(100),
1121   hsl(150),
1122   hsl(200),
1123   hsl(250),
1124   hsl(300),
1125 ];
1126
1127 function hsl(num: number) {
1128   return `hsla(${num}, 35%, 50%, 1)`;
1129 }
1130
1131 export function previewLines(
1132   text: string,
1133   maxChars = 300,
1134   maxLines = 1
1135 ): string {
1136   return (
1137     text
1138       .slice(0, maxChars)
1139       .split("\n")
1140       // Use lines * 2 because markdown requires 2 lines
1141       .slice(0, maxLines * 2)
1142       .join("\n") + "..."
1143   );
1144 }
1145
1146 export function hostname(url: string): string {
1147   let cUrl = new URL(url);
1148   return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1149 }
1150
1151 export function validTitle(title?: string): boolean {
1152   // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1153   if (title === null || title.length < 3) return true;
1154
1155   const regex = new RegExp(/.*\S.*/, "g");
1156
1157   return regex.test(title);
1158 }
1159
1160 export function siteBannerCss(banner: string): string {
1161   return ` \
1162     background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1163     background-attachment: fixed; \
1164     background-position: top; \
1165     background-repeat: no-repeat; \
1166     background-size: 100% cover; \
1167
1168     width: 100%; \
1169     max-height: 100vh; \
1170     `;
1171 }
1172
1173 export function isBrowser() {
1174   return typeof window !== "undefined";
1175 }
1176
1177 export function setIsoData(context: any): IsoData {
1178   let isoData: IsoData = isBrowser()
1179     ? window.isoData
1180     : context.router.staticContext;
1181   return isoData;
1182 }
1183
1184 export function wsSubscribe(parseMessage: any): Subscription {
1185   if (isBrowser()) {
1186     return WebSocketService.Instance.subject
1187       .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1188       .subscribe(
1189         msg => parseMessage(msg),
1190         err => console.error(err),
1191         () => console.log("complete")
1192       );
1193   } else {
1194     return null;
1195   }
1196 }
1197
1198 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1199   if (auth) {
1200     obj.auth = auth;
1201   }
1202 }
1203
1204 export function authField(
1205   throwErr = true,
1206   auth = UserService.Instance.auth
1207 ): string {
1208   if (auth == null && throwErr) {
1209     toast(i18n.t("not_logged_in"), "danger");
1210     throw "Not logged in";
1211   } else {
1212     return auth;
1213   }
1214 }
1215
1216 moment.updateLocale("en", {
1217   relativeTime: {
1218     future: "in %s",
1219     past: "%s ago",
1220     s: "<1m",
1221     ss: "%ds",
1222     m: "1m",
1223     mm: "%dm",
1224     h: "1h",
1225     hh: "%dh",
1226     d: "1d",
1227     dd: "%dd",
1228     w: "1w",
1229     ww: "%dw",
1230     M: "1M",
1231     MM: "%dM",
1232     y: "1Y",
1233     yy: "%dY",
1234   },
1235 });
1236
1237 export function saveScrollPosition(context: any) {
1238   let path: string = context.router.route.location.pathname;
1239   let y = window.scrollY;
1240   sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1241 }
1242
1243 export function restoreScrollPosition(context: any) {
1244   let path: string = context.router.route.location.pathname;
1245   let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1246   window.scrollTo(0, y);
1247 }
1248
1249 export function showLocal(isoData: IsoData): boolean {
1250   return isoData.site_res.federated_instances?.linked.length > 0;
1251 }
1252
1253 interface ChoicesValue {
1254   value: string;
1255   label: string;
1256 }
1257
1258 export function communityToChoice(cv: CommunityView): ChoicesValue {
1259   let choice: ChoicesValue = {
1260     value: cv.community.id.toString(),
1261     label: communitySelectName(cv),
1262   };
1263   return choice;
1264 }
1265
1266 export function personToChoice(pvs: PersonViewSafe): ChoicesValue {
1267   let choice: ChoicesValue = {
1268     value: pvs.person.id.toString(),
1269     label: personSelectName(pvs),
1270   };
1271   return choice;
1272 }
1273
1274 export async function fetchCommunities(q: string) {
1275   let form: Search = {
1276     q,
1277     type_: SearchType.Communities,
1278     sort: SortType.TopAll,
1279     listing_type: ListingType.All,
1280     page: 1,
1281     limit: fetchLimit,
1282     auth: authField(false),
1283   };
1284   let client = new LemmyHttp(httpBase);
1285   return client.search(form);
1286 }
1287
1288 export async function fetchUsers(q: string) {
1289   let form: Search = {
1290     q,
1291     type_: SearchType.Users,
1292     sort: SortType.TopAll,
1293     listing_type: ListingType.All,
1294     page: 1,
1295     limit: fetchLimit,
1296     auth: authField(false),
1297   };
1298   let client = new LemmyHttp(httpBase);
1299   return client.search(form);
1300 }
1301
1302 export const choicesConfig = {
1303   shouldSort: false,
1304   searchResultLimit: fetchLimit,
1305   classNames: {
1306     containerOuter: "choices",
1307     containerInner: "choices__inner bg-light border-0",
1308     input: "form-control",
1309     inputCloned: "choices__input--cloned",
1310     list: "choices__list",
1311     listItems: "choices__list--multiple",
1312     listSingle: "choices__list--single",
1313     listDropdown: "choices__list--dropdown",
1314     item: "choices__item bg-light",
1315     itemSelectable: "choices__item--selectable",
1316     itemDisabled: "choices__item--disabled",
1317     itemChoice: "choices__item--choice",
1318     placeholder: "choices__placeholder",
1319     group: "choices__group",
1320     groupHeading: "choices__heading",
1321     button: "choices__button",
1322     activeState: "is-active",
1323     focusState: "is-focused",
1324     openState: "is-open",
1325     disabledState: "is-disabled",
1326     highlightedState: "text-info",
1327     selectedState: "text-info",
1328     flippedState: "is-flipped",
1329     loadingState: "is-loading",
1330     noResults: "has-no-results",
1331     noChoices: "has-no-choices",
1332   },
1333 };
1334
1335 export function communitySelectName(cv: CommunityView): string {
1336   return cv.community.local
1337     ? cv.community.name
1338     : `${hostname(cv.community.actor_id)}/${cv.community.name}`;
1339 }
1340
1341 export function personSelectName(pvs: PersonViewSafe): string {
1342   return pvs.person.local
1343     ? pvs.person.name
1344     : `${hostname(pvs.person.actor_id)}/${pvs.person.name}`;
1345 }