]> Untitled Git - lemmy-ui.git/blob - src/shared/utils.ts
Actually sending ws requests, some other fixes.
[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
31 import {
32   UserOperation,
33   CommentView,
34   User_,
35   SortType,
36   ListingType,
37   SearchType,
38   WebSocketResponse,
39   WebSocketJsonResponse,
40   Search,
41   SearchResponse,
42   PostView,
43   PrivateMessageView,
44   LemmyWebsocket,
45 } from 'lemmy-js-client';
46
47 import {
48   CommentSortType,
49   DataType,
50   IsoData,
51   CommentNode as CommentNodeI,
52 } from './interfaces';
53 import { UserService, WebSocketService } from './services';
54
55 var Tribute;
56 if (isBrowser()) {
57   Tribute = require('tributejs');
58 }
59 import markdown_it from 'markdown-it';
60 import markdown_it_sub from 'markdown-it-sub';
61 import markdown_it_sup from 'markdown-it-sup';
62 import markdownitEmoji from 'markdown-it-emoji/light';
63 import markdown_it_container from 'markdown-it-container';
64 import emojiShortName from 'emoji-short-name';
65 import Toastify from 'toastify-js';
66 import tippy from 'tippy.js';
67 import moment from 'moment';
68 import { Subscription } from 'rxjs';
69 import { retryWhen, delay, take } from 'rxjs/operators';
70 import { i18n } from './i18next';
71
72 export const wsClient = new LemmyWebsocket();
73
74 export const favIconUrl = '/static/assets/favicon.svg';
75 export const favIconPngUrl = '/static/assets/apple-touch-icon.png';
76 // TODO
77 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
78 export const defaultFavIcon = 'test';
79 export const repoUrl = 'https://github.com/LemmyNet';
80 export const joinLemmyUrl = 'https://join.lemmy.ml';
81 export const supportLemmyUrl = 'https://join.lemmy.ml/sponsors';
82 export const helpGuideUrl = '/docs/about/guide.html';
83 export const markdownHelpUrl = `${helpGuideUrl}#markdown-guide`;
84 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
85 export const archiveUrl = 'https://archive.is';
86 export const elementUrl = 'https://element.io/';
87
88 export const postRefetchSeconds: number = 60 * 1000;
89 export const fetchLimit: number = 20;
90 export const mentionDropdownFetchLimit = 10;
91
92 export const languages = [
93   { code: 'ca', name: 'Català' },
94   { code: 'en', name: 'English' },
95   { code: 'el', name: 'Ελληνικά' },
96   { code: 'eu', name: 'Euskara' },
97   { code: 'eo', name: 'Esperanto' },
98   { code: 'es', name: 'Español' },
99   { code: 'da', name: 'Dansk' },
100   { code: 'de', name: 'Deutsch' },
101   { code: 'ga', name: 'Gaeilge' },
102   { code: 'gl', name: 'Galego' },
103   { code: 'hu', name: 'Magyar Nyelv' },
104   { code: 'ka', name: 'ქართული ენა' },
105   { code: 'ko', name: '한국어' },
106   { code: 'km', name: 'ភាសាខ្មែរ' },
107   { code: 'hi', name: 'मानक हिन्दी' },
108   { code: 'fa', name: 'فارسی' },
109   { code: 'ja', name: '日本語' },
110   { code: 'pl', name: 'Polski' },
111   { code: 'pt_BR', name: 'Português Brasileiro' },
112   { code: 'zh', name: '中文' },
113   { code: 'fi', name: 'Suomi' },
114   { code: 'fr', name: 'Français' },
115   { code: 'sv', name: 'Svenska' },
116   { code: 'sq', name: 'Shqip' },
117   { code: 'sr_Latn', name: 'srpski' },
118   { code: 'tr', name: 'Türkçe' },
119   { code: 'uk', name: 'Українська Mова' },
120   { code: 'ru', name: 'Русский' },
121   { code: 'nl', name: 'Nederlands' },
122   { code: 'it', name: 'Italiano' },
123 ];
124
125 export const themes = [
126   'litera',
127   'materia',
128   'minty',
129   'solar',
130   'united',
131   'cyborg',
132   'darkly',
133   'journal',
134   'sketchy',
135   'vaporwave',
136   'vaporwave-dark',
137   'i386',
138   'litely',
139 ];
140
141 const DEFAULT_ALPHABET =
142   'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
143
144 function getRandomCharFromAlphabet(alphabet: string): string {
145   return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
146 }
147
148 export function randomStr(
149   idDesiredLength: number = 20,
150   alphabet = DEFAULT_ALPHABET
151 ): string {
152   /**
153    * Create n-long array and map it to random chars from given alphabet.
154    * Then join individual chars as string
155    */
156   return Array.from({ length: idDesiredLength })
157     .map(() => {
158       return getRandomCharFromAlphabet(alphabet);
159     })
160     .join('');
161 }
162
163 export function wsJsonToRes<ResponseType>(
164   msg: WebSocketJsonResponse<ResponseType>
165 ): WebSocketResponse<ResponseType> {
166   return {
167     op: wsUserOp(msg),
168     data: msg.data,
169   };
170 }
171
172 export function wsUserOp(msg: any): UserOperation {
173   let opStr: string = msg.op;
174   return UserOperation[opStr];
175 }
176
177 export const md = new markdown_it({
178   html: false,
179   linkify: true,
180   typographer: true,
181 })
182   .use(markdown_it_sub)
183   .use(markdown_it_sup)
184   .use(markdown_it_container, 'spoiler', {
185     validate: function (params: any) {
186       return params.trim().match(/^spoiler\s+(.*)$/);
187     },
188
189     render: function (tokens: any, idx: any) {
190       var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
191
192       if (tokens[idx].nesting === 1) {
193         // opening tag
194         return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
195       } else {
196         // closing tag
197         return '</details>\n';
198       }
199     },
200   })
201   .use(markdownitEmoji, {
202     defs: objectFlip(emojiShortName),
203   });
204
205 export function hotRankComment(comment_view: CommentView): number {
206   return hotRank(comment_view.counts.score, comment_view.comment.published);
207 }
208
209 export function hotRankActivePost(post_view: PostView): number {
210   return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
211 }
212
213 export function hotRankPost(post_view: PostView): number {
214   return hotRank(post_view.counts.score, post_view.post.published);
215 }
216
217 export function hotRank(score: number, timeStr: string): number {
218   // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
219   let date: Date = new Date(timeStr + 'Z'); // Add Z to convert from UTC date
220   let now: Date = new Date();
221   let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
222
223   let rank =
224     (10000 * Math.log10(Math.max(1, 3 + score))) /
225     Math.pow(hoursElapsed + 2, 1.8);
226
227   // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
228
229   return rank;
230 }
231
232 export function mdToHtml(text: string) {
233   return { __html: md.render(text) };
234 }
235
236 export function getUnixTime(text: string): number {
237   return text ? new Date(text).getTime() / 1000 : undefined;
238 }
239
240 export function canMod(
241   user: User_,
242   modIds: number[],
243   creator_id: number,
244   onSelf: boolean = false
245 ): boolean {
246   // You can do moderator actions only on the mods added after you.
247   if (user) {
248     let yourIndex = modIds.findIndex(id => id == user.id);
249     if (yourIndex == -1) {
250       return false;
251     } else {
252       // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
253       modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
254       return !modIds.includes(creator_id);
255     }
256   } else {
257     return false;
258   }
259 }
260
261 export function isMod(modIds: number[], creator_id: number): boolean {
262   return modIds.includes(creator_id);
263 }
264
265 const imageRegex = new RegExp(
266   /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
267 );
268 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
269
270 export function isImage(url: string) {
271   return imageRegex.test(url);
272 }
273
274 export function isVideo(url: string) {
275   return videoRegex.test(url);
276 }
277
278 export function validURL(str: string) {
279   return !!new URL(str);
280 }
281
282 export function communityRSSUrl(actorId: string, sort: string): string {
283   let url = new URL(actorId);
284   return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
285 }
286
287 export function validEmail(email: string) {
288   let re = /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
289   return re.test(String(email).toLowerCase());
290 }
291
292 export function capitalizeFirstLetter(str: string): string {
293   return str.charAt(0).toUpperCase() + str.slice(1);
294 }
295
296 export function routeSortTypeToEnum(sort: string): SortType {
297   return SortType[sort];
298 }
299
300 export function routeListingTypeToEnum(type: string): ListingType {
301   return ListingType[type];
302 }
303
304 export function routeDataTypeToEnum(type: string): DataType {
305   return DataType[capitalizeFirstLetter(type)];
306 }
307
308 export function routeSearchTypeToEnum(type: string): SearchType {
309   return SearchType[type];
310 }
311
312 export async function getPageTitle(url: string) {
313   let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
314   let title = await res.title;
315   return title;
316 }
317
318 export function debounce(
319   func: any,
320   wait: number = 1000,
321   immediate: boolean = false
322 ) {
323   // 'private' variable for instance
324   // The returned function will be able to reference this due to closure.
325   // Each call to the returned function will share this common timer.
326   let timeout: any;
327
328   // Calling debounce returns a new anonymous function
329   return function () {
330     // reference the context and args for the setTimeout function
331     var context = this,
332       args = arguments;
333
334     // Should the function be called now? If immediate is true
335     //   and not already in a timeout then the answer is: Yes
336     var callNow = immediate && !timeout;
337
338     // This is the basic debounce behaviour where you can call this
339     //   function several times, but it will only execute once
340     //   [before or after imposing a delay].
341     //   Each time the returned function is called, the timer starts over.
342     clearTimeout(timeout);
343
344     // Set the new timeout
345     timeout = setTimeout(function () {
346       // Inside the timeout function, clear the timeout variable
347       // which will let the next execution run when in 'immediate' mode
348       timeout = null;
349
350       // Check if the function already ran with the immediate flag
351       if (!immediate) {
352         // Call the original function with apply
353         // apply lets you define the 'this' object as well as the arguments
354         //    (both captured before setTimeout)
355         func.apply(context, args);
356       }
357     }, wait);
358
359     // Immediate mode and no wait timer? Execute the function..
360     if (callNow) func.apply(context, args);
361   };
362 }
363
364 // TODO
365 export function getLanguage(override?: string): string {
366   let user = UserService.Instance.user;
367   let lang = override || (user && user.lang ? user.lang : 'browser');
368
369   if (lang == 'browser' && isBrowser()) {
370     return getBrowserLanguage();
371   } else {
372     return lang;
373   }
374 }
375
376 // TODO
377 export function getBrowserLanguage(): string {
378   return navigator.language;
379 }
380
381 export function getMomentLanguage(): string {
382   let lang = getLanguage();
383   if (lang.startsWith('zh')) {
384     lang = 'zh-cn';
385   } else if (lang.startsWith('sv')) {
386     lang = 'sv';
387   } else if (lang.startsWith('fr')) {
388     lang = 'fr';
389   } else if (lang.startsWith('de')) {
390     lang = 'de';
391   } else if (lang.startsWith('ru')) {
392     lang = 'ru';
393   } else if (lang.startsWith('es')) {
394     lang = 'es';
395   } else if (lang.startsWith('eo')) {
396     lang = 'eo';
397   } else if (lang.startsWith('nl')) {
398     lang = 'nl';
399   } else if (lang.startsWith('it')) {
400     lang = 'it';
401   } else if (lang.startsWith('fi')) {
402     lang = 'fi';
403   } else if (lang.startsWith('ca')) {
404     lang = 'ca';
405   } else if (lang.startsWith('fa')) {
406     lang = 'fa';
407   } else if (lang.startsWith('pl')) {
408     lang = 'pl';
409   } else if (lang.startsWith('pt')) {
410     lang = 'pt-br';
411   } else if (lang.startsWith('ja')) {
412     lang = 'ja';
413   } else if (lang.startsWith('ka')) {
414     lang = 'ka';
415   } else if (lang.startsWith('hi')) {
416     lang = 'hi';
417   } else if (lang.startsWith('el')) {
418     lang = 'el';
419   } else if (lang.startsWith('eu')) {
420     lang = 'eu';
421   } else if (lang.startsWith('gl')) {
422     lang = 'gl';
423   } else if (lang.startsWith('tr')) {
424     lang = 'tr';
425   } else if (lang.startsWith('hu')) {
426     lang = 'hu';
427   } else if (lang.startsWith('uk')) {
428     lang = 'uk';
429   } else if (lang.startsWith('sq')) {
430     lang = 'sq';
431   } else if (lang.startsWith('km')) {
432     lang = 'km';
433   } else if (lang.startsWith('ga')) {
434     lang = 'ga';
435   } else if (lang.startsWith('sr')) {
436     lang = 'sr';
437   } else if (lang.startsWith('ko')) {
438     lang = 'ko';
439   } else if (lang.startsWith('da')) {
440     lang = 'da';
441   } else {
442     lang = 'en';
443   }
444   return lang;
445 }
446
447 export function setTheme(theme: string, forceReload: boolean = false) {
448   if (!isBrowser()) {
449     return;
450   }
451   if (theme === 'browser' && !forceReload) {
452     return;
453   }
454   // This is only run on a force reload
455   if (theme == 'browser') {
456     theme = 'darkly';
457   }
458
459   // Unload all the other themes
460   for (var i = 0; i < themes.length; i++) {
461     let styleSheet = document.getElementById(themes[i]);
462     if (styleSheet) {
463       styleSheet.setAttribute('disabled', 'disabled');
464     }
465   }
466
467   document
468     .getElementById('default-light')
469     ?.setAttribute('disabled', 'disabled');
470   document.getElementById('default-dark')?.setAttribute('disabled', 'disabled');
471
472   // Load the theme dynamically
473   let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
474   loadCss(theme, cssLoc);
475   document.getElementById(theme).removeAttribute('disabled');
476 }
477
478 export function loadCss(id: string, loc: string) {
479   if (!document.getElementById(id)) {
480     var head = document.getElementsByTagName('head')[0];
481     var link = document.createElement('link');
482     link.id = id;
483     link.rel = 'stylesheet';
484     link.type = 'text/css';
485     link.href = loc;
486     link.media = 'all';
487     head.appendChild(link);
488   }
489 }
490
491 export function objectFlip(obj: any) {
492   const ret = {};
493   Object.keys(obj).forEach(key => {
494     ret[obj[key]] = key;
495   });
496   return ret;
497 }
498
499 export function showAvatars(): boolean {
500   return (
501     (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
502     !UserService.Instance.user
503   );
504 }
505
506 export function isCakeDay(published: string): boolean {
507   // moment(undefined) or moment.utc(undefined) returns the current date/time
508   // moment(null) or moment.utc(null) returns null
509   const userCreationDate = moment.utc(published || null).local();
510   const currentDate = moment(new Date());
511
512   return (
513     userCreationDate.date() === currentDate.date() &&
514     userCreationDate.month() === currentDate.month() &&
515     userCreationDate.year() !== currentDate.year()
516   );
517 }
518
519 export function toast(text: string, background: string = 'success') {
520   if (isBrowser()) {
521     let backgroundColor = `var(--${background})`;
522     Toastify({
523       text: text,
524       backgroundColor: backgroundColor,
525       gravity: 'bottom',
526       position: 'left',
527     }).showToast();
528   }
529 }
530
531 export function pictrsDeleteToast(
532   clickToDeleteText: string,
533   deletePictureText: string,
534   deleteUrl: string
535 ) {
536   if (isBrowser()) {
537     let backgroundColor = `var(--light)`;
538     let toast = Toastify({
539       text: clickToDeleteText,
540       backgroundColor: backgroundColor,
541       gravity: 'top',
542       position: 'right',
543       duration: 10000,
544       onClick: () => {
545         if (toast) {
546           window.location.replace(deleteUrl);
547           alert(deletePictureText);
548           toast.hideToast();
549         }
550       },
551       close: true,
552     }).showToast();
553   }
554 }
555
556 interface NotifyInfo {
557   name: string;
558   icon: string;
559   link: string;
560   body: string;
561 }
562
563 export function messageToastify(info: NotifyInfo, router: any) {
564   if (isBrowser()) {
565     let htmlBody = info.body ? md.render(info.body) : '';
566     let backgroundColor = `var(--light)`;
567
568     let toast = Toastify({
569       text: `${htmlBody}<br />${info.name}`,
570       avatar: info.icon,
571       backgroundColor: backgroundColor,
572       className: 'text-dark',
573       close: true,
574       gravity: 'top',
575       position: 'right',
576       duration: 5000,
577       onClick: () => {
578         if (toast) {
579           toast.hideToast();
580           router.history.push(info.link);
581         }
582       },
583     }).showToast();
584   }
585 }
586
587 export function notifyPost(post_view: PostView, router: any) {
588   let info: NotifyInfo = {
589     name: post_view.community.name,
590     icon: post_view.community.icon ? post_view.community.icon : defaultFavIcon,
591     link: `/post/${post_view.post.id}`,
592     body: post_view.post.name,
593   };
594   notify(info, router);
595 }
596
597 export function notifyComment(comment_view: CommentView, router: any) {
598   let info: NotifyInfo = {
599     name: comment_view.creator.name,
600     icon: comment_view.creator.avatar
601       ? comment_view.creator.avatar
602       : defaultFavIcon,
603     link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
604     body: comment_view.comment.content,
605   };
606   notify(info, router);
607 }
608
609 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
610   let info: NotifyInfo = {
611     name: pmv.creator.name,
612     icon: pmv.creator.avatar ? pmv.creator.avatar : defaultFavIcon,
613     link: `/inbox`,
614     body: pmv.private_message.content,
615   };
616   notify(info, router);
617 }
618
619 function notify(info: NotifyInfo, router: any) {
620   messageToastify(info, router);
621
622   if (Notification.permission !== 'granted') Notification.requestPermission();
623   else {
624     var notification = new Notification(info.name, {
625       icon: info.icon,
626       body: info.body,
627     });
628
629     notification.onclick = () => {
630       event.preventDefault();
631       router.history.push(info.link);
632     };
633   }
634 }
635
636 export function setupTribute() {
637   return new Tribute({
638     noMatchTemplate: function () {
639       return '';
640     },
641     collection: [
642       // Emojis
643       {
644         trigger: ':',
645         menuItemTemplate: (item: any) => {
646           let shortName = `:${item.original.key}:`;
647           return `${item.original.val} ${shortName}`;
648         },
649         selectTemplate: (item: any) => {
650           return `:${item.original.key}:`;
651         },
652         values: Object.entries(emojiShortName).map(e => {
653           return { key: e[1], val: e[0] };
654         }),
655         allowSpaces: false,
656         autocompleteMode: true,
657         // TODO
658         // menuItemLimit: mentionDropdownFetchLimit,
659         menuShowMinLength: 2,
660       },
661       // Users
662       {
663         trigger: '@',
664         selectTemplate: (item: any) => {
665           let link = item.original.local
666             ? `[${item.original.key}](/u/${item.original.name})`
667             : `[${item.original.key}](/user/${item.original.id})`;
668           return link;
669         },
670         values: (text: string, cb: any) => {
671           userSearch(text, (users: any) => cb(users));
672         },
673         allowSpaces: false,
674         autocompleteMode: true,
675         // TODO
676         // menuItemLimit: mentionDropdownFetchLimit,
677         menuShowMinLength: 2,
678       },
679
680       // Communities
681       {
682         trigger: '!',
683         selectTemplate: (item: any) => {
684           let link = item.original.local
685             ? `[${item.original.key}](/c/${item.original.name})`
686             : `[${item.original.key}](/community/${item.original.id})`;
687           return link;
688         },
689         values: (text: string, cb: any) => {
690           communitySearch(text, (communities: any) => cb(communities));
691         },
692         allowSpaces: false,
693         autocompleteMode: true,
694         // TODO
695         // menuItemLimit: mentionDropdownFetchLimit,
696         menuShowMinLength: 2,
697       },
698     ],
699   });
700 }
701
702 var tippyInstance;
703 if (isBrowser()) {
704   tippyInstance = tippy('[data-tippy-content]');
705 }
706
707 export function setupTippy() {
708   if (isBrowser()) {
709     tippyInstance.forEach(e => e.destroy());
710     tippyInstance = tippy('[data-tippy-content]', {
711       delay: [500, 0],
712       // Display on "long press"
713       touch: ['hold', 500],
714     });
715   }
716 }
717
718 function userSearch(text: string, cb: any) {
719   if (text) {
720     let form: Search = {
721       q: text,
722       type_: SearchType.Users,
723       sort: SortType.TopAll,
724       page: 1,
725       limit: mentionDropdownFetchLimit,
726       auth: authField(false),
727     };
728
729     WebSocketService.Instance.send(wsClient.search(form));
730
731     let userSub = WebSocketService.Instance.subject.subscribe(
732       msg => {
733         let res = wsJsonToRes(msg);
734         if (res.op == UserOperation.Search) {
735           let data = res.data as SearchResponse;
736           let users = data.users.map(uv => {
737             return {
738               key: `@${uv.user.name}@${hostname(uv.user.actor_id)}`,
739               name: uv.user.name,
740               local: uv.user.local,
741               id: uv.user.id,
742             };
743           });
744           cb(users);
745           userSub.unsubscribe();
746         }
747       },
748       err => console.error(err),
749       () => console.log('complete')
750     );
751   } else {
752     cb([]);
753   }
754 }
755
756 function communitySearch(text: string, cb: any) {
757   if (text) {
758     let form: Search = {
759       q: text,
760       type_: SearchType.Communities,
761       sort: SortType.TopAll,
762       page: 1,
763       limit: mentionDropdownFetchLimit,
764       auth: authField(false),
765     };
766
767     WebSocketService.Instance.send(wsClient.search(form));
768
769     let communitySub = WebSocketService.Instance.subject.subscribe(
770       msg => {
771         let res = wsJsonToRes(msg);
772         if (res.op == UserOperation.Search) {
773           let data = res.data as SearchResponse;
774           let communities = data.communities.map(cv => {
775             return {
776               key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
777               name: cv.community.name,
778               local: cv.community.local,
779               id: cv.community.id,
780             };
781           });
782           cb(communities);
783           communitySub.unsubscribe();
784         }
785       },
786       err => console.error(err),
787       () => console.log('complete')
788     );
789   } else {
790     cb([]);
791   }
792 }
793
794 export function getListingTypeFromProps(props: any): ListingType {
795   return props.match.params.listing_type
796     ? routeListingTypeToEnum(props.match.params.listing_type)
797     : UserService.Instance.user
798     ? Object.values(ListingType)[UserService.Instance.user.default_listing_type]
799     : ListingType.Local;
800 }
801
802 // TODO might need to add a user setting for this too
803 export function getDataTypeFromProps(props: any): DataType {
804   return props.match.params.data_type
805     ? routeDataTypeToEnum(props.match.params.data_type)
806     : DataType.Post;
807 }
808
809 export function getSortTypeFromProps(props: any): SortType {
810   return props.match.params.sort
811     ? routeSortTypeToEnum(props.match.params.sort)
812     : UserService.Instance.user
813     ? Object.values(SortType)[UserService.Instance.user.default_sort_type]
814     : SortType.Active;
815 }
816
817 export function getPageFromProps(props: any): number {
818   return props.match.params.page ? Number(props.match.params.page) : 1;
819 }
820
821 export function getRecipientIdFromProps(props: any): number {
822   return props.match.params.recipient_id
823     ? Number(props.match.params.recipient_id)
824     : 1;
825 }
826
827 export function getIdFromProps(props: any): number {
828   return Number(props.match.params.id);
829 }
830
831 export function getCommentIdFromProps(props: any): number {
832   return Number(props.match.params.comment_id);
833 }
834
835 export function getUsernameFromProps(props: any): string {
836   return props.match.params.username;
837 }
838
839 export function editCommentRes(data: CommentView, comments: CommentView[]) {
840   let found = comments.find(c => c.comment.id == data.comment.id);
841   if (found) {
842     found.comment.content = data.comment.content;
843     found.comment.updated = data.comment.updated;
844     found.comment.removed = data.comment.removed;
845     found.comment.deleted = data.comment.deleted;
846     found.counts.upvotes = data.counts.upvotes;
847     found.counts.downvotes = data.counts.downvotes;
848     found.counts.score = data.counts.score;
849   }
850 }
851
852 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
853   let found = comments.find(c => c.comment.id == data.comment.id);
854   if (found) {
855     found.saved = data.saved;
856   }
857 }
858
859 export function createCommentLikeRes(
860   data: CommentView,
861   comments: CommentView[]
862 ) {
863   let found = comments.find(c => c.comment.id === data.comment.id);
864   if (found) {
865     found.counts.score = data.counts.score;
866     found.counts.upvotes = data.counts.upvotes;
867     found.counts.downvotes = data.counts.downvotes;
868     if (data.my_vote !== null) {
869       found.my_vote = data.my_vote;
870     }
871   }
872 }
873
874 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
875   let found = posts.find(p => p.post.id == data.post.id);
876   if (found) {
877     createPostLikeRes(data, found);
878   }
879 }
880
881 export function createPostLikeRes(data: PostView, post_view: PostView) {
882   if (post_view) {
883     post_view.counts.score = data.counts.score;
884     post_view.counts.upvotes = data.counts.upvotes;
885     post_view.counts.downvotes = data.counts.downvotes;
886     if (data.my_vote !== null) {
887       post_view.my_vote = data.my_vote;
888     }
889   }
890 }
891
892 export function editPostFindRes(data: PostView, posts: PostView[]) {
893   let found = posts.find(p => p.post.id == data.post.id);
894   if (found) {
895     editPostRes(data, found);
896   }
897 }
898
899 export function editPostRes(data: PostView, post: PostView) {
900   if (post) {
901     post.post.url = data.post.url;
902     post.post.name = data.post.name;
903     post.post.nsfw = data.post.nsfw;
904     post.post.deleted = data.post.deleted;
905     post.post.removed = data.post.removed;
906     post.post.stickied = data.post.stickied;
907     post.post.body = data.post.body;
908     post.post.locked = data.post.locked;
909     post.saved = data.saved;
910   }
911 }
912
913 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
914   let nodes: CommentNodeI[] = [];
915   for (let comment of comments) {
916     nodes.push({ comment_view: comment });
917   }
918   return nodes;
919 }
920
921 export function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
922   // First, put removed and deleted comments at the bottom, then do your other sorts
923   if (sort == CommentSortType.Top) {
924     tree.sort(
925       (a, b) =>
926         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
927         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
928         b.comment_view.counts.score - a.comment_view.counts.score
929     );
930   } else if (sort == CommentSortType.New) {
931     tree.sort(
932       (a, b) =>
933         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
934         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
935         b.comment_view.comment.published.localeCompare(
936           a.comment_view.comment.published
937         )
938     );
939   } else if (sort == CommentSortType.Old) {
940     tree.sort(
941       (a, b) =>
942         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
943         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
944         a.comment_view.comment.published.localeCompare(
945           b.comment_view.comment.published
946         )
947     );
948   } else if (sort == CommentSortType.Hot) {
949     tree.sort(
950       (a, b) =>
951         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
952         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
953         hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
954     );
955   }
956
957   // Go through the children recursively
958   for (let node of tree) {
959     if (node.children) {
960       commentSort(node.children, sort);
961     }
962   }
963 }
964
965 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
966   commentSort(tree, convertCommentSortType(sort));
967 }
968
969 function convertCommentSortType(sort: SortType): CommentSortType {
970   if (
971     sort == SortType.TopAll ||
972     sort == SortType.TopDay ||
973     sort == SortType.TopWeek ||
974     sort == SortType.TopMonth ||
975     sort == SortType.TopYear
976   ) {
977     return CommentSortType.Top;
978   } else if (sort == SortType.New) {
979     return CommentSortType.New;
980   } else if (sort == SortType.Hot || sort == SortType.Active) {
981     return CommentSortType.Hot;
982   } else {
983     return CommentSortType.Hot;
984   }
985 }
986
987 export function postSort(
988   posts: PostView[],
989   sort: SortType,
990   communityType: boolean
991 ) {
992   // First, put removed and deleted comments at the bottom, then do your other sorts
993   if (
994     sort == SortType.TopAll ||
995     sort == SortType.TopDay ||
996     sort == SortType.TopWeek ||
997     sort == SortType.TopMonth ||
998     sort == SortType.TopYear
999   ) {
1000     posts.sort(
1001       (a, b) =>
1002         +a.post.removed - +b.post.removed ||
1003         +a.post.deleted - +b.post.deleted ||
1004         (communityType && +b.post.stickied - +a.post.stickied) ||
1005         b.counts.score - a.counts.score
1006     );
1007   } else if (sort == SortType.New) {
1008     posts.sort(
1009       (a, b) =>
1010         +a.post.removed - +b.post.removed ||
1011         +a.post.deleted - +b.post.deleted ||
1012         (communityType && +b.post.stickied - +a.post.stickied) ||
1013         b.post.published.localeCompare(a.post.published)
1014     );
1015   } else if (sort == SortType.Hot) {
1016     posts.sort(
1017       (a, b) =>
1018         +a.post.removed - +b.post.removed ||
1019         +a.post.deleted - +b.post.deleted ||
1020         (communityType && +b.post.stickied - +a.post.stickied) ||
1021         hotRankPost(b) - hotRankPost(a)
1022     );
1023   } else if (sort == SortType.Active) {
1024     posts.sort(
1025       (a, b) =>
1026         +a.post.removed - +b.post.removed ||
1027         +a.post.deleted - +b.post.deleted ||
1028         (communityType && +b.post.stickied - +a.post.stickied) ||
1029         hotRankActivePost(b) - hotRankActivePost(a)
1030     );
1031   }
1032 }
1033
1034 export const colorList: string[] = [
1035   hsl(0),
1036   hsl(100),
1037   hsl(150),
1038   hsl(200),
1039   hsl(250),
1040   hsl(300),
1041 ];
1042
1043 function hsl(num: number) {
1044   return `hsla(${num}, 35%, 50%, 1)`;
1045 }
1046
1047 // function randomHsl() {
1048 //   return `hsla(${Math.random() * 360}, 100%, 50%, 1)`;
1049 // }
1050
1051 export function previewLines(
1052   text: string,
1053   maxChars: number = 300,
1054   maxLines: number = 1
1055 ): string {
1056   return (
1057     text
1058       .slice(0, maxChars)
1059       .split('\n')
1060       // Use lines * 2 because markdown requires 2 lines
1061       .slice(0, maxLines * 2)
1062       .join('\n') + '...'
1063   );
1064 }
1065
1066 export function hostname(url: string): string {
1067   let cUrl = new URL(url);
1068   return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1069 }
1070
1071 export function validTitle(title?: string): boolean {
1072   // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1073   if (title === null || title.length < 3) return true;
1074
1075   const regex = new RegExp(/.*\S.*/, 'g');
1076
1077   return regex.test(title);
1078 }
1079
1080 export function siteBannerCss(banner: string): string {
1081   return ` \
1082     background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1083     background-attachment: fixed; \
1084     background-position: top; \
1085     background-repeat: no-repeat; \
1086     background-size: 100% cover; \
1087
1088     width: 100%; \
1089     max-height: 100vh; \
1090     `;
1091 }
1092
1093 export function isBrowser() {
1094   return typeof window !== 'undefined';
1095 }
1096
1097 export function setIsoData(context: any): IsoData {
1098   let isoData: IsoData = isBrowser()
1099     ? window.isoData
1100     : context.router.staticContext;
1101   return isoData;
1102 }
1103
1104 export function wsSubscribe(parseMessage: any): Subscription {
1105   if (isBrowser()) {
1106     return WebSocketService.Instance.subject
1107       .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1108       .subscribe(
1109         msg => parseMessage(msg),
1110         err => console.error(err),
1111         () => console.log('complete')
1112       );
1113   } else {
1114     return null;
1115   }
1116 }
1117
1118 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1119   if (auth) {
1120     obj.auth = auth;
1121   }
1122 }
1123
1124 export function authField(
1125   throwErr: boolean = true,
1126   auth = UserService.Instance.auth
1127 ): string {
1128   if (auth == null && throwErr) {
1129     toast(i18n.t('not_logged_in'), 'danger');
1130     throw 'Not logged in';
1131   } else {
1132     return auth;
1133   }
1134 }
1135
1136 moment.updateLocale('en', {
1137   relativeTime: {
1138     future: 'in %s',
1139     past: '%s ago',
1140     s: '<1m',
1141     ss: '%ds',
1142     m: '1m',
1143     mm: '%dm',
1144     h: '1h',
1145     hh: '%dh',
1146     d: '1d',
1147     dd: '%dd',
1148     w: '1w',
1149     ww: '%dw',
1150     M: '1M',
1151     MM: '%dM',
1152     y: '1Y',
1153     yy: '%dY',
1154   },
1155 });