]> Untitled Git - lemmy-ui.git/blob - src/shared/utils.ts
A few 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 listingTypeFromNum(type_: number): ListingType {
301   return Object.values(ListingType)[type_];
302 }
303
304 export function sortTypeFromNum(type_: number): SortType {
305   return Object.values(SortType)[type_];
306 }
307
308 export function routeListingTypeToEnum(type: string): ListingType {
309   return ListingType[type];
310 }
311
312 export function routeDataTypeToEnum(type: string): DataType {
313   return DataType[capitalizeFirstLetter(type)];
314 }
315
316 export function routeSearchTypeToEnum(type: string): SearchType {
317   return SearchType[type];
318 }
319
320 export async function getPageTitle(url: string) {
321   let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
322   let title = await res.title;
323   return title;
324 }
325
326 export function debounce(
327   func: any,
328   wait: number = 1000,
329   immediate: boolean = false
330 ) {
331   // 'private' variable for instance
332   // The returned function will be able to reference this due to closure.
333   // Each call to the returned function will share this common timer.
334   let timeout: any;
335
336   // Calling debounce returns a new anonymous function
337   return function () {
338     // reference the context and args for the setTimeout function
339     var context = this,
340       args = arguments;
341
342     // Should the function be called now? If immediate is true
343     //   and not already in a timeout then the answer is: Yes
344     var callNow = immediate && !timeout;
345
346     // This is the basic debounce behaviour where you can call this
347     //   function several times, but it will only execute once
348     //   [before or after imposing a delay].
349     //   Each time the returned function is called, the timer starts over.
350     clearTimeout(timeout);
351
352     // Set the new timeout
353     timeout = setTimeout(function () {
354       // Inside the timeout function, clear the timeout variable
355       // which will let the next execution run when in 'immediate' mode
356       timeout = null;
357
358       // Check if the function already ran with the immediate flag
359       if (!immediate) {
360         // Call the original function with apply
361         // apply lets you define the 'this' object as well as the arguments
362         //    (both captured before setTimeout)
363         func.apply(context, args);
364       }
365     }, wait);
366
367     // Immediate mode and no wait timer? Execute the function..
368     if (callNow) func.apply(context, args);
369   };
370 }
371
372 // TODO
373 export function getLanguage(override?: string): string {
374   let user = UserService.Instance.user;
375   let lang = override || (user && user.lang ? user.lang : 'browser');
376
377   if (lang == 'browser' && isBrowser()) {
378     return getBrowserLanguage();
379   } else {
380     return lang;
381   }
382 }
383
384 // TODO
385 export function getBrowserLanguage(): string {
386   return navigator.language;
387 }
388
389 export function getMomentLanguage(): string {
390   let lang = getLanguage();
391   if (lang.startsWith('zh')) {
392     lang = 'zh-cn';
393   } else if (lang.startsWith('sv')) {
394     lang = 'sv';
395   } else if (lang.startsWith('fr')) {
396     lang = 'fr';
397   } else if (lang.startsWith('de')) {
398     lang = 'de';
399   } else if (lang.startsWith('ru')) {
400     lang = 'ru';
401   } else if (lang.startsWith('es')) {
402     lang = 'es';
403   } else if (lang.startsWith('eo')) {
404     lang = 'eo';
405   } else if (lang.startsWith('nl')) {
406     lang = 'nl';
407   } else if (lang.startsWith('it')) {
408     lang = 'it';
409   } else if (lang.startsWith('fi')) {
410     lang = 'fi';
411   } else if (lang.startsWith('ca')) {
412     lang = 'ca';
413   } else if (lang.startsWith('fa')) {
414     lang = 'fa';
415   } else if (lang.startsWith('pl')) {
416     lang = 'pl';
417   } else if (lang.startsWith('pt')) {
418     lang = 'pt-br';
419   } else if (lang.startsWith('ja')) {
420     lang = 'ja';
421   } else if (lang.startsWith('ka')) {
422     lang = 'ka';
423   } else if (lang.startsWith('hi')) {
424     lang = 'hi';
425   } else if (lang.startsWith('el')) {
426     lang = 'el';
427   } else if (lang.startsWith('eu')) {
428     lang = 'eu';
429   } else if (lang.startsWith('gl')) {
430     lang = 'gl';
431   } else if (lang.startsWith('tr')) {
432     lang = 'tr';
433   } else if (lang.startsWith('hu')) {
434     lang = 'hu';
435   } else if (lang.startsWith('uk')) {
436     lang = 'uk';
437   } else if (lang.startsWith('sq')) {
438     lang = 'sq';
439   } else if (lang.startsWith('km')) {
440     lang = 'km';
441   } else if (lang.startsWith('ga')) {
442     lang = 'ga';
443   } else if (lang.startsWith('sr')) {
444     lang = 'sr';
445   } else if (lang.startsWith('ko')) {
446     lang = 'ko';
447   } else if (lang.startsWith('da')) {
448     lang = 'da';
449   } else {
450     lang = 'en';
451   }
452   return lang;
453 }
454
455 export function setTheme(theme: string, forceReload: boolean = false) {
456   if (!isBrowser()) {
457     return;
458   }
459   if (theme === 'browser' && !forceReload) {
460     return;
461   }
462   // This is only run on a force reload
463   if (theme == 'browser') {
464     theme = 'darkly';
465   }
466
467   // Unload all the other themes
468   for (var i = 0; i < themes.length; i++) {
469     let styleSheet = document.getElementById(themes[i]);
470     if (styleSheet) {
471       styleSheet.setAttribute('disabled', 'disabled');
472     }
473   }
474
475   document
476     .getElementById('default-light')
477     ?.setAttribute('disabled', 'disabled');
478   document.getElementById('default-dark')?.setAttribute('disabled', 'disabled');
479
480   // Load the theme dynamically
481   let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
482   loadCss(theme, cssLoc);
483   document.getElementById(theme).removeAttribute('disabled');
484 }
485
486 export function loadCss(id: string, loc: string) {
487   if (!document.getElementById(id)) {
488     var head = document.getElementsByTagName('head')[0];
489     var link = document.createElement('link');
490     link.id = id;
491     link.rel = 'stylesheet';
492     link.type = 'text/css';
493     link.href = loc;
494     link.media = 'all';
495     head.appendChild(link);
496   }
497 }
498
499 export function objectFlip(obj: any) {
500   const ret = {};
501   Object.keys(obj).forEach(key => {
502     ret[obj[key]] = key;
503   });
504   return ret;
505 }
506
507 export function showAvatars(): boolean {
508   return (
509     (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
510     !UserService.Instance.user
511   );
512 }
513
514 export function isCakeDay(published: string): boolean {
515   // moment(undefined) or moment.utc(undefined) returns the current date/time
516   // moment(null) or moment.utc(null) returns null
517   const userCreationDate = moment.utc(published || null).local();
518   const currentDate = moment(new Date());
519
520   return (
521     userCreationDate.date() === currentDate.date() &&
522     userCreationDate.month() === currentDate.month() &&
523     userCreationDate.year() !== currentDate.year()
524   );
525 }
526
527 export function toast(text: string, background: string = 'success') {
528   if (isBrowser()) {
529     let backgroundColor = `var(--${background})`;
530     Toastify({
531       text: text,
532       backgroundColor: backgroundColor,
533       gravity: 'bottom',
534       position: 'left',
535     }).showToast();
536   }
537 }
538
539 export function pictrsDeleteToast(
540   clickToDeleteText: string,
541   deletePictureText: string,
542   deleteUrl: string
543 ) {
544   if (isBrowser()) {
545     let backgroundColor = `var(--light)`;
546     let toast = Toastify({
547       text: clickToDeleteText,
548       backgroundColor: backgroundColor,
549       gravity: 'top',
550       position: 'right',
551       duration: 10000,
552       onClick: () => {
553         if (toast) {
554           window.location.replace(deleteUrl);
555           alert(deletePictureText);
556           toast.hideToast();
557         }
558       },
559       close: true,
560     }).showToast();
561   }
562 }
563
564 interface NotifyInfo {
565   name: string;
566   icon: string;
567   link: string;
568   body: string;
569 }
570
571 export function messageToastify(info: NotifyInfo, router: any) {
572   if (isBrowser()) {
573     let htmlBody = info.body ? md.render(info.body) : '';
574     let backgroundColor = `var(--light)`;
575
576     let toast = Toastify({
577       text: `${htmlBody}<br />${info.name}`,
578       avatar: info.icon,
579       backgroundColor: backgroundColor,
580       className: 'text-dark',
581       close: true,
582       gravity: 'top',
583       position: 'right',
584       duration: 5000,
585       onClick: () => {
586         if (toast) {
587           toast.hideToast();
588           router.history.push(info.link);
589         }
590       },
591     }).showToast();
592   }
593 }
594
595 export function notifyPost(post_view: PostView, router: any) {
596   let info: NotifyInfo = {
597     name: post_view.community.name,
598     icon: post_view.community.icon ? post_view.community.icon : defaultFavIcon,
599     link: `/post/${post_view.post.id}`,
600     body: post_view.post.name,
601   };
602   notify(info, router);
603 }
604
605 export function notifyComment(comment_view: CommentView, router: any) {
606   let info: NotifyInfo = {
607     name: comment_view.creator.name,
608     icon: comment_view.creator.avatar
609       ? comment_view.creator.avatar
610       : defaultFavIcon,
611     link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
612     body: comment_view.comment.content,
613   };
614   notify(info, router);
615 }
616
617 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
618   let info: NotifyInfo = {
619     name: pmv.creator.name,
620     icon: pmv.creator.avatar ? pmv.creator.avatar : defaultFavIcon,
621     link: `/inbox`,
622     body: pmv.private_message.content,
623   };
624   notify(info, router);
625 }
626
627 function notify(info: NotifyInfo, router: any) {
628   messageToastify(info, router);
629
630   if (Notification.permission !== 'granted') Notification.requestPermission();
631   else {
632     var notification = new Notification(info.name, {
633       icon: info.icon,
634       body: info.body,
635     });
636
637     notification.onclick = () => {
638       event.preventDefault();
639       router.history.push(info.link);
640     };
641   }
642 }
643
644 export function setupTribute() {
645   return new Tribute({
646     noMatchTemplate: function () {
647       return '';
648     },
649     collection: [
650       // Emojis
651       {
652         trigger: ':',
653         menuItemTemplate: (item: any) => {
654           let shortName = `:${item.original.key}:`;
655           return `${item.original.val} ${shortName}`;
656         },
657         selectTemplate: (item: any) => {
658           return `:${item.original.key}:`;
659         },
660         values: Object.entries(emojiShortName).map(e => {
661           return { key: e[1], val: e[0] };
662         }),
663         allowSpaces: false,
664         autocompleteMode: true,
665         // TODO
666         // menuItemLimit: mentionDropdownFetchLimit,
667         menuShowMinLength: 2,
668       },
669       // Users
670       {
671         trigger: '@',
672         selectTemplate: (item: any) => {
673           let link = item.original.local
674             ? `[${item.original.key}](/u/${item.original.name})`
675             : `[${item.original.key}](/user/${item.original.id})`;
676           return link;
677         },
678         values: (text: string, cb: any) => {
679           userSearch(text, (users: any) => cb(users));
680         },
681         allowSpaces: false,
682         autocompleteMode: true,
683         // TODO
684         // menuItemLimit: mentionDropdownFetchLimit,
685         menuShowMinLength: 2,
686       },
687
688       // Communities
689       {
690         trigger: '!',
691         selectTemplate: (item: any) => {
692           let link = item.original.local
693             ? `[${item.original.key}](/c/${item.original.name})`
694             : `[${item.original.key}](/community/${item.original.id})`;
695           return link;
696         },
697         values: (text: string, cb: any) => {
698           communitySearch(text, (communities: any) => cb(communities));
699         },
700         allowSpaces: false,
701         autocompleteMode: true,
702         // TODO
703         // menuItemLimit: mentionDropdownFetchLimit,
704         menuShowMinLength: 2,
705       },
706     ],
707   });
708 }
709
710 var tippyInstance;
711 if (isBrowser()) {
712   tippyInstance = tippy('[data-tippy-content]');
713 }
714
715 export function setupTippy() {
716   if (isBrowser()) {
717     tippyInstance.forEach(e => e.destroy());
718     tippyInstance = tippy('[data-tippy-content]', {
719       delay: [500, 0],
720       // Display on "long press"
721       touch: ['hold', 500],
722     });
723   }
724 }
725
726 function userSearch(text: string, cb: any) {
727   if (text) {
728     let form: Search = {
729       q: text,
730       type_: SearchType.Users,
731       sort: SortType.TopAll,
732       page: 1,
733       limit: mentionDropdownFetchLimit,
734       auth: authField(false),
735     };
736
737     WebSocketService.Instance.send(wsClient.search(form));
738
739     let userSub = WebSocketService.Instance.subject.subscribe(
740       msg => {
741         let res = wsJsonToRes(msg);
742         if (res.op == UserOperation.Search) {
743           let data = res.data as SearchResponse;
744           let users = data.users.map(uv => {
745             return {
746               key: `@${uv.user.name}@${hostname(uv.user.actor_id)}`,
747               name: uv.user.name,
748               local: uv.user.local,
749               id: uv.user.id,
750             };
751           });
752           cb(users);
753           userSub.unsubscribe();
754         }
755       },
756       err => console.error(err),
757       () => console.log('complete')
758     );
759   } else {
760     cb([]);
761   }
762 }
763
764 function communitySearch(text: string, cb: any) {
765   if (text) {
766     let form: Search = {
767       q: text,
768       type_: SearchType.Communities,
769       sort: SortType.TopAll,
770       page: 1,
771       limit: mentionDropdownFetchLimit,
772       auth: authField(false),
773     };
774
775     WebSocketService.Instance.send(wsClient.search(form));
776
777     let communitySub = WebSocketService.Instance.subject.subscribe(
778       msg => {
779         let res = wsJsonToRes(msg);
780         if (res.op == UserOperation.Search) {
781           let data = res.data as SearchResponse;
782           let communities = data.communities.map(cv => {
783             return {
784               key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
785               name: cv.community.name,
786               local: cv.community.local,
787               id: cv.community.id,
788             };
789           });
790           cb(communities);
791           communitySub.unsubscribe();
792         }
793       },
794       err => console.error(err),
795       () => console.log('complete')
796     );
797   } else {
798     cb([]);
799   }
800 }
801
802 export function getListingTypeFromProps(props: any): ListingType {
803   return props.match.params.listing_type
804     ? routeListingTypeToEnum(props.match.params.listing_type)
805     : UserService.Instance.user
806     ? Object.values(ListingType)[UserService.Instance.user.default_listing_type]
807     : ListingType.Local;
808 }
809
810 // TODO might need to add a user setting for this too
811 export function getDataTypeFromProps(props: any): DataType {
812   return props.match.params.data_type
813     ? routeDataTypeToEnum(props.match.params.data_type)
814     : DataType.Post;
815 }
816
817 export function getSortTypeFromProps(props: any): SortType {
818   return props.match.params.sort
819     ? routeSortTypeToEnum(props.match.params.sort)
820     : UserService.Instance.user
821     ? Object.values(SortType)[UserService.Instance.user.default_sort_type]
822     : SortType.Active;
823 }
824
825 export function getPageFromProps(props: any): number {
826   return props.match.params.page ? Number(props.match.params.page) : 1;
827 }
828
829 export function getRecipientIdFromProps(props: any): number {
830   return props.match.params.recipient_id
831     ? Number(props.match.params.recipient_id)
832     : 1;
833 }
834
835 export function getIdFromProps(props: any): number {
836   return Number(props.match.params.id);
837 }
838
839 export function getCommentIdFromProps(props: any): number {
840   return Number(props.match.params.comment_id);
841 }
842
843 export function getUsernameFromProps(props: any): string {
844   return props.match.params.username;
845 }
846
847 export function editCommentRes(data: CommentView, comments: CommentView[]) {
848   let found = comments.find(c => c.comment.id == data.comment.id);
849   if (found) {
850     found.comment.content = data.comment.content;
851     found.comment.updated = data.comment.updated;
852     found.comment.removed = data.comment.removed;
853     found.comment.deleted = data.comment.deleted;
854     found.counts.upvotes = data.counts.upvotes;
855     found.counts.downvotes = data.counts.downvotes;
856     found.counts.score = data.counts.score;
857   }
858 }
859
860 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
861   let found = comments.find(c => c.comment.id == data.comment.id);
862   if (found) {
863     found.saved = data.saved;
864   }
865 }
866
867 export function createCommentLikeRes(
868   data: CommentView,
869   comments: CommentView[]
870 ) {
871   let found = comments.find(c => c.comment.id === data.comment.id);
872   if (found) {
873     found.counts.score = data.counts.score;
874     found.counts.upvotes = data.counts.upvotes;
875     found.counts.downvotes = data.counts.downvotes;
876     if (data.my_vote !== null) {
877       found.my_vote = data.my_vote;
878     }
879   }
880 }
881
882 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
883   let found = posts.find(p => p.post.id == data.post.id);
884   if (found) {
885     createPostLikeRes(data, found);
886   }
887 }
888
889 export function createPostLikeRes(data: PostView, post_view: PostView) {
890   if (post_view) {
891     post_view.counts.score = data.counts.score;
892     post_view.counts.upvotes = data.counts.upvotes;
893     post_view.counts.downvotes = data.counts.downvotes;
894     if (data.my_vote !== null) {
895       post_view.my_vote = data.my_vote;
896     }
897   }
898 }
899
900 export function editPostFindRes(data: PostView, posts: PostView[]) {
901   let found = posts.find(p => p.post.id == data.post.id);
902   if (found) {
903     editPostRes(data, found);
904   }
905 }
906
907 export function editPostRes(data: PostView, post: PostView) {
908   if (post) {
909     post.post.url = data.post.url;
910     post.post.name = data.post.name;
911     post.post.nsfw = data.post.nsfw;
912     post.post.deleted = data.post.deleted;
913     post.post.removed = data.post.removed;
914     post.post.stickied = data.post.stickied;
915     post.post.body = data.post.body;
916     post.post.locked = data.post.locked;
917     post.saved = data.saved;
918   }
919 }
920
921 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
922   let nodes: CommentNodeI[] = [];
923   for (let comment of comments) {
924     nodes.push({ comment_view: comment });
925   }
926   return nodes;
927 }
928
929 export function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
930   // First, put removed and deleted comments at the bottom, then do your other sorts
931   if (sort == CommentSortType.Top) {
932     tree.sort(
933       (a, b) =>
934         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
935         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
936         b.comment_view.counts.score - a.comment_view.counts.score
937     );
938   } else if (sort == CommentSortType.New) {
939     tree.sort(
940       (a, b) =>
941         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
942         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
943         b.comment_view.comment.published.localeCompare(
944           a.comment_view.comment.published
945         )
946     );
947   } else if (sort == CommentSortType.Old) {
948     tree.sort(
949       (a, b) =>
950         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
951         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
952         a.comment_view.comment.published.localeCompare(
953           b.comment_view.comment.published
954         )
955     );
956   } else if (sort == CommentSortType.Hot) {
957     tree.sort(
958       (a, b) =>
959         +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
960         +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
961         hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
962     );
963   }
964
965   // Go through the children recursively
966   for (let node of tree) {
967     if (node.children) {
968       commentSort(node.children, sort);
969     }
970   }
971 }
972
973 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
974   commentSort(tree, convertCommentSortType(sort));
975 }
976
977 function convertCommentSortType(sort: SortType): CommentSortType {
978   if (
979     sort == SortType.TopAll ||
980     sort == SortType.TopDay ||
981     sort == SortType.TopWeek ||
982     sort == SortType.TopMonth ||
983     sort == SortType.TopYear
984   ) {
985     return CommentSortType.Top;
986   } else if (sort == SortType.New) {
987     return CommentSortType.New;
988   } else if (sort == SortType.Hot || sort == SortType.Active) {
989     return CommentSortType.Hot;
990   } else {
991     return CommentSortType.Hot;
992   }
993 }
994
995 export function postSort(
996   posts: PostView[],
997   sort: SortType,
998   communityType: boolean
999 ) {
1000   // First, put removed and deleted comments at the bottom, then do your other sorts
1001   if (
1002     sort == SortType.TopAll ||
1003     sort == SortType.TopDay ||
1004     sort == SortType.TopWeek ||
1005     sort == SortType.TopMonth ||
1006     sort == SortType.TopYear
1007   ) {
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.counts.score - a.counts.score
1014     );
1015   } else if (sort == SortType.New) {
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         b.post.published.localeCompare(a.post.published)
1022     );
1023   } else if (sort == SortType.Hot) {
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         hotRankPost(b) - hotRankPost(a)
1030     );
1031   } else if (sort == SortType.Active) {
1032     posts.sort(
1033       (a, b) =>
1034         +a.post.removed - +b.post.removed ||
1035         +a.post.deleted - +b.post.deleted ||
1036         (communityType && +b.post.stickied - +a.post.stickied) ||
1037         hotRankActivePost(b) - hotRankActivePost(a)
1038     );
1039   }
1040 }
1041
1042 export const colorList: string[] = [
1043   hsl(0),
1044   hsl(100),
1045   hsl(150),
1046   hsl(200),
1047   hsl(250),
1048   hsl(300),
1049 ];
1050
1051 function hsl(num: number) {
1052   return `hsla(${num}, 35%, 50%, 1)`;
1053 }
1054
1055 // function randomHsl() {
1056 //   return `hsla(${Math.random() * 360}, 100%, 50%, 1)`;
1057 // }
1058
1059 export function previewLines(
1060   text: string,
1061   maxChars: number = 300,
1062   maxLines: number = 1
1063 ): string {
1064   return (
1065     text
1066       .slice(0, maxChars)
1067       .split('\n')
1068       // Use lines * 2 because markdown requires 2 lines
1069       .slice(0, maxLines * 2)
1070       .join('\n') + '...'
1071   );
1072 }
1073
1074 export function hostname(url: string): string {
1075   let cUrl = new URL(url);
1076   return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1077 }
1078
1079 export function validTitle(title?: string): boolean {
1080   // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1081   if (title === null || title.length < 3) return true;
1082
1083   const regex = new RegExp(/.*\S.*/, 'g');
1084
1085   return regex.test(title);
1086 }
1087
1088 export function siteBannerCss(banner: string): string {
1089   return ` \
1090     background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1091     background-attachment: fixed; \
1092     background-position: top; \
1093     background-repeat: no-repeat; \
1094     background-size: 100% cover; \
1095
1096     width: 100%; \
1097     max-height: 100vh; \
1098     `;
1099 }
1100
1101 export function isBrowser() {
1102   return typeof window !== 'undefined';
1103 }
1104
1105 export function setIsoData(context: any): IsoData {
1106   let isoData: IsoData = isBrowser()
1107     ? window.isoData
1108     : context.router.staticContext;
1109   return isoData;
1110 }
1111
1112 export function wsSubscribe(parseMessage: any): Subscription {
1113   if (isBrowser()) {
1114     return WebSocketService.Instance.subject
1115       .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1116       .subscribe(
1117         msg => parseMessage(msg),
1118         err => console.error(err),
1119         () => console.log('complete')
1120       );
1121   } else {
1122     return null;
1123   }
1124 }
1125
1126 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1127   if (auth) {
1128     obj.auth = auth;
1129   }
1130 }
1131
1132 export function authField(
1133   throwErr: boolean = true,
1134   auth = UserService.Instance.auth
1135 ): string {
1136   if (auth == null && throwErr) {
1137     toast(i18n.t('not_logged_in'), 'danger');
1138     throw 'Not logged in';
1139   } else {
1140     return auth;
1141   }
1142 }
1143
1144 moment.updateLocale('en', {
1145   relativeTime: {
1146     future: 'in %s',
1147     past: '%s ago',
1148     s: '<1m',
1149     ss: '%ds',
1150     m: '1m',
1151     mm: '%dm',
1152     h: '1h',
1153     hh: '%dh',
1154     d: '1d',
1155     dd: '%dd',
1156     w: '1w',
1157     ww: '%dw',
1158     M: '1M',
1159     MM: '%dM',
1160     y: '1Y',
1161     yy: '%dY',
1162   },
1163 });