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