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