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';
33 CommentNode as CommentNodeI,
41 WebSocketJsonResponse,
47 } from 'lemmy-js-client';
49 import { httpUri } from './env';
51 import { CommentSortType, DataType, IsoData } from './interfaces';
52 import { UserService, WebSocketService } from './services';
56 Tribute = require('tributejs');
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';
70 export const favIconUrl = '/static/assets/favicon.svg';
71 export const favIconPngUrl = '/static/assets/apple-touch-icon.png';
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/';
83 export const postRefetchSeconds: number = 60 * 1000;
84 export const fetchLimit: number = 20;
85 export const mentionDropdownFetchLimit = 10;
87 export const lemmyHttp = new LemmyHttp(httpUri);
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' },
121 export const themes = [
137 const DEFAULT_ALPHABET =
138 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
140 function getRandomCharFromAlphabet(alphabet: string): string {
141 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
144 export function randomStr(
145 idDesiredLength: number = 20,
146 alphabet = DEFAULT_ALPHABET
149 * Create n-long array and map it to random chars from given alphabet.
150 * Then join individual chars as string
152 return Array.from({ length: idDesiredLength })
154 return getRandomCharFromAlphabet(alphabet);
159 export function wsJsonToRes(msg: WebSocketJsonResponse): WebSocketResponse {
160 let opStr: string = msg.op;
162 op: UserOperation[opStr],
167 export const md = new markdown_it({
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+(.*)$/);
179 render: function (tokens: any, idx: any) {
180 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
182 if (tokens[idx].nesting === 1) {
184 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
187 return '</details>\n';
191 .use(markdownitEmoji, {
192 defs: objectFlip(emojiShortName),
195 export function hotRankComment(comment: Comment): number {
196 return hotRank(comment.score, comment.published);
199 export function hotRankPost(post: Post): number {
200 return hotRank(post.score, post.newest_activity_time);
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;
210 (10000 * Math.log10(Math.max(1, 3 + score))) /
211 Math.pow(hoursElapsed + 2, 1.8);
213 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
218 export function mdToHtml(text: string) {
219 return { __html: md.render(text) };
222 export function getUnixTime(text: string): number {
223 return text ? new Date(text).getTime() / 1000 : undefined;
226 export function addTypeInfo<T>(
229 ): { type_: string; data: T }[] {
230 return arr.map(e => {
231 return { type_: name, data: e };
235 export function canMod(
239 onSelf: boolean = false
241 // You can do moderator actions only on the mods added after you.
243 let yourIndex = modIds.findIndex(id => id == user.id);
244 if (yourIndex == -1) {
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);
256 export function isMod(modIds: number[], creator_id: number): boolean {
257 return modIds.includes(creator_id);
260 const imageRegex = new RegExp(
261 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
263 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
265 export function isImage(url: string) {
266 return imageRegex.test(url);
269 export function isVideo(url: string) {
270 return videoRegex.test(url);
273 export function validURL(str: string) {
274 return !!new URL(str);
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}`;
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());
287 export function capitalizeFirstLetter(str: string): string {
288 return str.charAt(0).toUpperCase() + str.slice(1);
291 export function routeSortTypeToEnum(sort: string): SortType {
292 return SortType[sort];
295 export function routeListingTypeToEnum(type: string): ListingType {
296 return ListingType[type];
299 export function routeDataTypeToEnum(type: string): DataType {
300 return DataType[capitalizeFirstLetter(type)];
303 export function routeSearchTypeToEnum(type: string): SearchType {
304 return SearchType[type];
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;
313 export function debounce(
316 immediate: boolean = false
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.
323 // Calling debounce returns a new anonymous function
325 // reference the context and args for the setTimeout function
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;
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);
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
345 // Check if the function already ran with the immediate flag
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);
354 // Immediate mode and no wait timer? Execute the function..
355 if (callNow) func.apply(context, args);
360 export function getLanguage(override?: string): string {
361 let user = UserService.Instance.user;
362 let lang = override || (user && user.lang ? user.lang : 'browser');
364 if (lang == 'browser' && isBrowser()) {
365 return getBrowserLanguage();
372 export function getBrowserLanguage(): string {
373 return navigator.language;
376 export function getMomentLanguage(): string {
377 let lang = getLanguage();
378 if (lang.startsWith('zh')) {
380 } else if (lang.startsWith('sv')) {
382 } else if (lang.startsWith('fr')) {
384 } else if (lang.startsWith('de')) {
386 } else if (lang.startsWith('ru')) {
388 } else if (lang.startsWith('es')) {
390 } else if (lang.startsWith('eo')) {
392 } else if (lang.startsWith('nl')) {
394 } else if (lang.startsWith('it')) {
396 } else if (lang.startsWith('fi')) {
398 } else if (lang.startsWith('ca')) {
400 } else if (lang.startsWith('fa')) {
402 } else if (lang.startsWith('pl')) {
404 } else if (lang.startsWith('pt')) {
406 } else if (lang.startsWith('ja')) {
408 } else if (lang.startsWith('ka')) {
410 } else if (lang.startsWith('hi')) {
412 } else if (lang.startsWith('el')) {
414 } else if (lang.startsWith('eu')) {
416 } else if (lang.startsWith('gl')) {
418 } else if (lang.startsWith('tr')) {
420 } else if (lang.startsWith('hu')) {
422 } else if (lang.startsWith('uk')) {
424 } else if (lang.startsWith('sq')) {
426 } else if (lang.startsWith('km')) {
428 } else if (lang.startsWith('ga')) {
430 } else if (lang.startsWith('sr')) {
432 } else if (lang.startsWith('ko')) {
440 export function setTheme(theme: string, forceReload: boolean = false) {
444 if (theme === 'browser' && !forceReload) {
447 // This is only run on a force reload
448 if (theme == 'browser') {
452 // Unload all the other themes
453 for (var i = 0; i < themes.length; i++) {
454 let styleSheet = document.getElementById(themes[i]);
456 styleSheet.setAttribute('disabled', 'disabled');
461 .getElementById('default-light')
462 ?.setAttribute('disabled', 'disabled');
463 document.getElementById('default-dark')?.setAttribute('disabled', 'disabled');
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');
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');
476 link.rel = 'stylesheet';
477 link.type = 'text/css';
480 head.appendChild(link);
484 export function objectFlip(obj: any) {
486 Object.keys(obj).forEach(key => {
492 export function showAvatars(): boolean {
494 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
495 !UserService.Instance.user
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());
506 userCreationDate.date() === currentDate.date() &&
507 userCreationDate.month() === currentDate.month() &&
508 userCreationDate.year() !== currentDate.year()
512 export function isCommentType(
513 item: Comment | PrivateMessage | Post
516 (item as Comment).community_id !== undefined &&
517 (item as Comment).content !== undefined
521 export function isPostType(
522 item: Comment | PrivateMessage | Post
524 return (item as Post).stickied !== undefined;
527 export function toast(text: string, background: string = 'success') {
528 let backgroundColor = `var(--${background})`;
531 backgroundColor: backgroundColor,
537 export function pictrsDeleteToast(
538 clickToDeleteText: string,
539 deletePictureText: string,
542 let backgroundColor = `var(--light)`;
543 let toast = Toastify({
544 text: clickToDeleteText,
545 backgroundColor: backgroundColor,
551 window.location.replace(deleteUrl);
552 alert(deletePictureText);
560 interface NotifyInfo {
567 export function messageToastify(info: NotifyInfo, router: any) {
568 let htmlBody = info.body ? md.render(info.body) : '';
569 let backgroundColor = `var(--light)`;
571 let toast = Toastify({
572 text: `${htmlBody}<br />${info.name}`,
574 backgroundColor: backgroundColor,
575 className: 'text-dark',
583 router.history.push(info.link);
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}`,
596 notify(info, router);
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,
606 notify(info, router);
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,
616 notify(info, router);
619 function notify(info: NotifyInfo, router: any) {
620 messageToastify(info, router);
622 if (Notification.permission !== 'granted') Notification.requestPermission();
624 var notification = new Notification(info.name, {
629 notification.onclick = () => {
630 event.preventDefault();
631 router.history.push(info.link);
636 export function setupTribute() {
638 noMatchTemplate: function () {
645 menuItemTemplate: (item: any) => {
646 let shortName = `:${item.original.key}:`;
647 return `${item.original.val} ${shortName}`;
649 selectTemplate: (item: any) => {
650 return `:${item.original.key}:`;
652 values: Object.entries(emojiShortName).map(e => {
653 return { key: e[1], val: e[0] };
656 autocompleteMode: true,
658 // menuItemLimit: mentionDropdownFetchLimit,
659 menuShowMinLength: 2,
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})`;
670 values: (text: string, cb: any) => {
671 userSearch(text, (users: any) => cb(users));
674 autocompleteMode: true,
676 // menuItemLimit: mentionDropdownFetchLimit,
677 menuShowMinLength: 2,
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})`;
689 values: (text: string, cb: any) => {
690 communitySearch(text, (communities: any) => cb(communities));
693 autocompleteMode: true,
695 // menuItemLimit: mentionDropdownFetchLimit,
696 menuShowMinLength: 2,
704 tippyInstance = tippy('[data-tippy-content]');
707 export function setupTippy() {
709 tippyInstance.forEach(e => e.destroy());
710 tippyInstance = tippy('[data-tippy-content]', {
712 // Display on "long press"
713 touch: ['hold', 500],
718 function userSearch(text: string, cb: any) {
720 let form: SearchForm = {
722 type_: SearchType.Users,
723 sort: SortType.TopAll,
725 limit: mentionDropdownFetchLimit,
728 WebSocketService.Instance.search(form);
730 let userSub = WebSocketService.Instance.subject.subscribe(
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 => {
737 key: `@${u.name}@${hostname(u.actor_id)}`,
744 userSub.unsubscribe();
747 err => console.error(err),
748 () => console.log('complete')
755 function communitySearch(text: string, cb: any) {
757 let form: SearchForm = {
759 type_: SearchType.Communities,
760 sort: SortType.TopAll,
762 limit: mentionDropdownFetchLimit,
765 WebSocketService.Instance.search(form);
767 let communitySub = WebSocketService.Instance.subject.subscribe(
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 => {
774 key: `!${c.name}@${hostname(c.actor_id)}`,
781 communitySub.unsubscribe();
784 err => console.error(err),
785 () => console.log('complete')
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]
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)
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]
815 export function getPageFromProps(props: any): number {
816 return props.match.params.page ? Number(props.match.params.page) : 1;
819 export function getRecipientIdFromProps(props: any): number {
820 return props.match.params.recipient_id
821 ? Number(props.match.params.recipient_id)
825 export function getIdFromProps(props: any): number {
826 return Number(props.match.params.id);
829 export function getCommentIdFromProps(props: any): number {
830 return Number(props.match.params.comment_id);
833 export function getUsernameFromProps(props: any): string {
834 return props.match.params.username;
837 export function editCommentRes(data: CommentResponse, comments: Comment[]) {
838 let found = comments.find(c => c.id == data.comment.id);
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;
850 export function saveCommentRes(data: CommentResponse, comments: Comment[]) {
851 let found = comments.find(c => c.id == data.comment.id);
853 found.saved = data.comment.saved;
857 export function createCommentLikeRes(
858 data: CommentResponse,
861 let found: Comment = comments.find(c => c.id === data.comment.id);
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;
872 export function createPostLikeFindRes(data: PostResponse, posts: Post[]) {
873 let found = posts.find(c => c.id == data.post.id);
875 createPostLikeRes(data, found);
879 export function createPostLikeRes(data: PostResponse, post: 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;
890 export function editPostFindRes(data: PostResponse, posts: Post[]) {
891 let found = posts.find(c => c.id == data.post.id);
893 editPostRes(data, found);
897 export function editPostRes(data: PostResponse, post: 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;
911 export function commentsToFlatNodes(comments: Comment[]): CommentNodeI[] {
912 let nodes: CommentNodeI[] = [];
913 for (let comment of comments) {
914 nodes.push({ comment: comment });
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) {
924 +a.comment.removed - +b.comment.removed ||
925 +a.comment.deleted - +b.comment.deleted ||
926 b.comment.score - a.comment.score
928 } else if (sort == CommentSortType.New) {
931 +a.comment.removed - +b.comment.removed ||
932 +a.comment.deleted - +b.comment.deleted ||
933 b.comment.published.localeCompare(a.comment.published)
935 } else if (sort == CommentSortType.Old) {
938 +a.comment.removed - +b.comment.removed ||
939 +a.comment.deleted - +b.comment.deleted ||
940 a.comment.published.localeCompare(b.comment.published)
942 } else if (sort == CommentSortType.Hot) {
945 +a.comment.removed - +b.comment.removed ||
946 +a.comment.deleted - +b.comment.deleted ||
947 hotRankComment(b.comment) - hotRankComment(a.comment)
951 // Go through the children recursively
952 for (let node of tree) {
954 commentSort(node.children, sort);
959 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
960 commentSort(tree, convertCommentSortType(sort));
963 function convertCommentSortType(sort: SortType): CommentSortType {
965 sort == SortType.TopAll ||
966 sort == SortType.TopDay ||
967 sort == SortType.TopWeek ||
968 sort == SortType.TopMonth ||
969 sort == SortType.TopYear
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;
977 return CommentSortType.Hot;
981 export function postSort(
984 communityType: boolean
986 // First, put removed and deleted comments at the bottom, then do your other sorts
988 sort == SortType.TopAll ||
989 sort == SortType.TopDay ||
990 sort == SortType.TopWeek ||
991 sort == SortType.TopMonth ||
992 sort == SortType.TopYear
996 +a.removed - +b.removed ||
997 +a.deleted - +b.deleted ||
998 (communityType && +b.stickied - +a.stickied) ||
1001 } else if (sort == SortType.New) {
1004 +a.removed - +b.removed ||
1005 +a.deleted - +b.deleted ||
1006 (communityType && +b.stickied - +a.stickied) ||
1007 b.published.localeCompare(a.published)
1009 } else if (sort == SortType.Hot) {
1012 +a.removed - +b.removed ||
1013 +a.deleted - +b.deleted ||
1014 (communityType && +b.stickied - +a.stickied) ||
1015 b.hot_rank - a.hot_rank
1017 } else if (sort == SortType.Active) {
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
1028 export const colorList: string[] = [
1037 function hsl(num: number) {
1038 return `hsla(${num}, 35%, 50%, 1)`;
1041 // function randomHsl() {
1042 // return `hsla(${Math.random() * 360}, 100%, 50%, 1)`;
1045 export function previewLines(
1047 maxChars: number = 300,
1048 maxLines: number = 1
1054 // Use lines * 2 because markdown requires 2 lines
1055 .slice(0, maxLines * 2)
1060 export function hostname(url: string): string {
1061 let cUrl = new URL(url);
1062 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
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;
1069 const regex = new RegExp(/.*\S.*/, 'g');
1071 return regex.test(title);
1074 export function siteBannerCss(banner: string): string {
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; \
1083 max-height: 100vh; \
1087 export function isBrowser() {
1088 return typeof window !== 'undefined';
1091 export function setAuth(obj: any, auth: string) {
1097 export function setIsoData(context: any): IsoData {
1098 let isoData: IsoData = isBrowser()
1100 : context.router.staticContext;
1104 export function wsSubscribe(parseMessage: any): Subscription {
1106 return WebSocketService.Instance.subject
1107 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1109 msg => parseMessage(msg),
1110 err => console.error(err),
1111 () => console.log('complete')
1118 moment.updateLocale('en', {