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 helpGuideUrl = '/docs/about_guide.html';
77 export const markdownHelpUrl = `${helpGuideUrl}#markdown-guide`;
78 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
79 export const archiveUrl = 'https://archive.is';
80 export const elementUrl = 'https://element.io/';
82 export const postRefetchSeconds: number = 60 * 1000;
83 export const fetchLimit: number = 20;
84 export const mentionDropdownFetchLimit = 10;
86 export const lemmyHttp = new LemmyHttp(httpUri);
88 export const languages = [
89 { code: 'ca', name: 'Català' },
90 { code: 'en', name: 'English' },
91 { code: 'el', name: 'Ελληνικά' },
92 { code: 'eu', name: 'Euskara' },
93 { code: 'eo', name: 'Esperanto' },
94 { code: 'es', name: 'Español' },
95 { code: 'de', name: 'Deutsch' },
96 { code: 'ga', name: 'Gaeilge' },
97 { code: 'gl', name: 'Galego' },
98 { code: 'hu', name: 'Magyar Nyelv' },
99 { code: 'ka', name: 'ქართული ენა' },
100 { code: 'ko', name: '한국어' },
101 { code: 'km', name: 'ភាសាខ្មែរ' },
102 { code: 'hi', name: 'मानक हिन्दी' },
103 { code: 'fa', name: 'فارسی' },
104 { code: 'ja', name: '日本語' },
105 { code: 'pl', name: 'Polski' },
106 { code: 'pt_BR', name: 'Português Brasileiro' },
107 { code: 'zh', name: '中文' },
108 { code: 'fi', name: 'Suomi' },
109 { code: 'fr', name: 'Français' },
110 { code: 'sv', name: 'Svenska' },
111 { code: 'sq', name: 'Shqip' },
112 { code: 'sr_Latn', name: 'srpski' },
113 { code: 'tr', name: 'Türkçe' },
114 { code: 'uk', name: 'Українська Mова' },
115 { code: 'ru', name: 'Русский' },
116 { code: 'nl', name: 'Nederlands' },
117 { code: 'it', name: 'Italiano' },
120 export const themes = [
136 const DEFAULT_ALPHABET =
137 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
139 function getRandomCharFromAlphabet(alphabet: string): string {
140 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
143 export function randomStr(
144 idDesiredLength: number = 20,
145 alphabet = DEFAULT_ALPHABET
148 * Create n-long array and map it to random chars from given alphabet.
149 * Then join individual chars as string
151 return Array.from({ length: idDesiredLength })
153 return getRandomCharFromAlphabet(alphabet);
158 export function wsJsonToRes(msg: WebSocketJsonResponse): WebSocketResponse {
159 let opStr: string = msg.op;
161 op: UserOperation[opStr],
166 export const md = new markdown_it({
171 .use(markdown_it_sub)
172 .use(markdown_it_sup)
173 .use(markdown_it_container, 'spoiler', {
174 validate: function (params: any) {
175 return params.trim().match(/^spoiler\s+(.*)$/);
178 render: function (tokens: any, idx: any) {
179 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
181 if (tokens[idx].nesting === 1) {
183 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
186 return '</details>\n';
190 .use(markdownitEmoji, {
191 defs: objectFlip(emojiShortName),
194 export function hotRankComment(comment: Comment): number {
195 return hotRank(comment.score, comment.published);
198 export function hotRankPost(post: Post): number {
199 return hotRank(post.score, post.newest_activity_time);
202 export function hotRank(score: number, timeStr: string): number {
203 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
204 let date: Date = new Date(timeStr + 'Z'); // Add Z to convert from UTC date
205 let now: Date = new Date();
206 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
209 (10000 * Math.log10(Math.max(1, 3 + score))) /
210 Math.pow(hoursElapsed + 2, 1.8);
212 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
217 export function mdToHtml(text: string) {
218 return { __html: md.render(text) };
221 export function getUnixTime(text: string): number {
222 return text ? new Date(text).getTime() / 1000 : undefined;
225 export function addTypeInfo<T>(
228 ): { type_: string; data: T }[] {
229 return arr.map(e => {
230 return { type_: name, data: e };
234 export function canMod(
238 onSelf: boolean = false
240 // You can do moderator actions only on the mods added after you.
242 let yourIndex = modIds.findIndex(id => id == user.id);
243 if (yourIndex == -1) {
246 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
247 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
248 return !modIds.includes(creator_id);
255 export function isMod(modIds: number[], creator_id: number): boolean {
256 return modIds.includes(creator_id);
259 const imageRegex = new RegExp(
260 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
262 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
264 export function isImage(url: string) {
265 return imageRegex.test(url);
268 export function isVideo(url: string) {
269 return videoRegex.test(url);
273 export function validURL(str: string) {
275 return !!new URL(str);
281 export function communityRSSUrl(actorId: string, sort: string): string {
282 let url = new URL(actorId);
283 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
286 export function validEmail(email: string) {
287 let re = /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
288 return re.test(String(email).toLowerCase());
291 export function capitalizeFirstLetter(str: string): string {
292 return str.charAt(0).toUpperCase() + str.slice(1);
295 export function routeSortTypeToEnum(sort: string): SortType {
296 return SortType[sort];
299 export function routeListingTypeToEnum(type: string): ListingType {
300 return ListingType[type];
303 export function routeDataTypeToEnum(type: string): DataType {
304 return DataType[capitalizeFirstLetter(type)];
307 export function routeSearchTypeToEnum(type: string): SearchType {
308 return SearchType[type];
311 export async function getPageTitle(url: string) {
312 let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
313 let title = await res.title;
317 export function debounce(
320 immediate: boolean = false
322 // 'private' variable for instance
323 // The returned function will be able to reference this due to closure.
324 // Each call to the returned function will share this common timer.
327 // Calling debounce returns a new anonymous function
329 // reference the context and args for the setTimeout function
333 // Should the function be called now? If immediate is true
334 // and not already in a timeout then the answer is: Yes
335 var callNow = immediate && !timeout;
337 // This is the basic debounce behaviour where you can call this
338 // function several times, but it will only execute once
339 // [before or after imposing a delay].
340 // Each time the returned function is called, the timer starts over.
341 clearTimeout(timeout);
343 // Set the new timeout
344 timeout = setTimeout(function () {
345 // Inside the timeout function, clear the timeout variable
346 // which will let the next execution run when in 'immediate' mode
349 // Check if the function already ran with the immediate flag
351 // Call the original function with apply
352 // apply lets you define the 'this' object as well as the arguments
353 // (both captured before setTimeout)
354 func.apply(context, args);
358 // Immediate mode and no wait timer? Execute the function..
359 if (callNow) func.apply(context, args);
364 export function getLanguage(override?: string): string {
365 let user = UserService.Instance.user;
366 let lang = override || (user && user.lang ? user.lang : 'browser');
368 if (lang == 'browser' && isBrowser()) {
369 return getBrowserLanguage();
376 export function getBrowserLanguage(): string {
377 return navigator.language;
380 export function getMomentLanguage(): string {
381 let lang = getLanguage();
382 if (lang.startsWith('zh')) {
384 } else if (lang.startsWith('sv')) {
386 } else if (lang.startsWith('fr')) {
388 } else if (lang.startsWith('de')) {
390 } else if (lang.startsWith('ru')) {
392 } else if (lang.startsWith('es')) {
394 } else if (lang.startsWith('eo')) {
396 } else if (lang.startsWith('nl')) {
398 } else if (lang.startsWith('it')) {
400 } else if (lang.startsWith('fi')) {
402 } else if (lang.startsWith('ca')) {
404 } else if (lang.startsWith('fa')) {
406 } else if (lang.startsWith('pl')) {
408 } else if (lang.startsWith('pt')) {
410 } else if (lang.startsWith('ja')) {
412 } else if (lang.startsWith('ka')) {
414 } else if (lang.startsWith('hi')) {
416 } else if (lang.startsWith('el')) {
418 } else if (lang.startsWith('eu')) {
420 } else if (lang.startsWith('gl')) {
422 } else if (lang.startsWith('tr')) {
424 } else if (lang.startsWith('hu')) {
426 } else if (lang.startsWith('uk')) {
428 } else if (lang.startsWith('sq')) {
430 } else if (lang.startsWith('km')) {
432 } else if (lang.startsWith('ga')) {
434 } else if (lang.startsWith('sr')) {
436 } else if (lang.startsWith('ko')) {
444 export function setTheme(theme: string, forceReload: boolean = false) {
445 if (isBrowser() && (theme !== 'browser' || forceReload)) {
446 // This is only run on a force reload
447 if (theme == 'browser') {
451 // Unload all the other themes
452 for (var i = 0; i < themes.length; i++) {
453 let styleSheet = document.getElementById(themes[i]);
455 styleSheet.setAttribute('disabled', 'disabled');
460 .getElementById('default-light')
461 .setAttribute('disabled', 'disabled');
463 .getElementById('default-dark')
464 .setAttribute('disabled', 'disabled');
466 // Load the theme dynamically
467 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
468 loadCss(theme, cssLoc);
469 document.getElementById(theme).removeAttribute('disabled');
473 export function loadCss(id: string, loc: string) {
474 if (!document.getElementById(id)) {
475 var head = document.getElementsByTagName('head')[0];
476 var link = document.createElement('link');
478 link.rel = 'stylesheet';
479 link.type = 'text/css';
482 head.appendChild(link);
486 export function objectFlip(obj: any) {
488 Object.keys(obj).forEach(key => {
494 export function showAvatars(): boolean {
496 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
497 !UserService.Instance.user
501 export function isCakeDay(published: string): boolean {
502 // moment(undefined) or moment.utc(undefined) returns the current date/time
503 // moment(null) or moment.utc(null) returns null
504 const userCreationDate = moment.utc(published || null).local();
505 const currentDate = moment(new Date());
508 userCreationDate.date() === currentDate.date() &&
509 userCreationDate.month() === currentDate.month() &&
510 userCreationDate.year() !== currentDate.year()
514 export function isCommentType(
515 item: Comment | PrivateMessage | Post
518 (item as Comment).community_id !== undefined &&
519 (item as Comment).content !== undefined
523 export function isPostType(
524 item: Comment | PrivateMessage | Post
526 return (item as Post).stickied !== undefined;
529 export function toast(text: string, background: string = 'success') {
530 let backgroundColor = `var(--${background})`;
533 backgroundColor: backgroundColor,
539 export function pictrsDeleteToast(
540 clickToDeleteText: string,
541 deletePictureText: string,
544 let backgroundColor = `var(--light)`;
545 let toast = Toastify({
546 text: clickToDeleteText,
547 backgroundColor: backgroundColor,
553 window.location.replace(deleteUrl);
554 alert(deletePictureText);
562 interface NotifyInfo {
569 export function messageToastify(info: NotifyInfo, router: any) {
570 let htmlBody = info.body ? md.render(info.body) : '';
571 let backgroundColor = `var(--light)`;
573 let toast = Toastify({
574 text: `${htmlBody}<br />${info.name}`,
576 backgroundColor: backgroundColor,
577 className: 'text-dark',
585 router.history.push(info.link);
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}`,
598 notify(info, router);
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,
608 notify(info, router);
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,
618 notify(info, router);
621 function notify(info: NotifyInfo, router: any) {
622 messageToastify(info, router);
624 if (Notification.permission !== 'granted') Notification.requestPermission();
626 var notification = new Notification(info.name, {
631 notification.onclick = () => {
632 event.preventDefault();
633 router.history.push(info.link);
638 export function setupTribute() {
640 noMatchTemplate: function () {
647 menuItemTemplate: (item: any) => {
648 let shortName = `:${item.original.key}:`;
649 return `${item.original.val} ${shortName}`;
651 selectTemplate: (item: any) => {
652 return `:${item.original.key}:`;
654 values: Object.entries(emojiShortName).map(e => {
655 return { key: e[1], val: e[0] };
658 autocompleteMode: true,
660 // menuItemLimit: mentionDropdownFetchLimit,
661 menuShowMinLength: 2,
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})`;
672 values: (text: string, cb: any) => {
673 userSearch(text, (users: any) => cb(users));
676 autocompleteMode: true,
678 // menuItemLimit: mentionDropdownFetchLimit,
679 menuShowMinLength: 2,
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})`;
691 values: (text: string, cb: any) => {
692 communitySearch(text, (communities: any) => cb(communities));
695 autocompleteMode: true,
697 // menuItemLimit: mentionDropdownFetchLimit,
698 menuShowMinLength: 2,
706 tippyInstance = tippy('[data-tippy-content]');
709 export function setupTippy() {
711 tippyInstance.forEach(e => e.destroy());
712 tippyInstance = tippy('[data-tippy-content]', {
714 // Display on "long press"
715 touch: ['hold', 500],
720 function userSearch(text: string, cb: any) {
722 let form: SearchForm = {
724 type_: SearchType.Users,
725 sort: SortType.TopAll,
727 limit: mentionDropdownFetchLimit,
730 WebSocketService.Instance.search(form);
732 let userSub = WebSocketService.Instance.subject.subscribe(
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 => {
739 key: `@${u.name}@${hostname(u.actor_id)}`,
746 userSub.unsubscribe();
749 err => console.error(err),
750 () => console.log('complete')
757 function communitySearch(text: string, cb: any) {
759 let form: SearchForm = {
761 type_: SearchType.Communities,
762 sort: SortType.TopAll,
764 limit: mentionDropdownFetchLimit,
767 WebSocketService.Instance.search(form);
769 let communitySub = WebSocketService.Instance.subject.subscribe(
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 => {
776 key: `!${c.name}@${hostname(c.actor_id)}`,
783 communitySub.unsubscribe();
786 err => console.error(err),
787 () => console.log('complete')
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]
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)
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]
817 export function getPageFromProps(props: any): number {
818 return props.match.params.page ? Number(props.match.params.page) : 1;
821 export function getRecipientIdFromProps(props: any): number {
822 return props.match.params.recipient_id
823 ? Number(props.match.params.recipient_id)
827 export function getIdFromProps(props: any): number {
828 return Number(props.match.params.id);
831 export function getCommentIdFromProps(props: any): number {
832 return Number(props.match.params.comment_id);
835 export function getUsernameFromProps(props: any): string {
836 return props.match.params.username;
839 export function editCommentRes(data: CommentResponse, comments: Comment[]) {
840 let found = comments.find(c => c.id == data.comment.id);
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;
852 export function saveCommentRes(data: CommentResponse, comments: Comment[]) {
853 let found = comments.find(c => c.id == data.comment.id);
855 found.saved = data.comment.saved;
859 export function createCommentLikeRes(
860 data: CommentResponse,
863 let found: Comment = comments.find(c => c.id === data.comment.id);
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;
874 export function createPostLikeFindRes(data: PostResponse, posts: Post[]) {
875 let found = posts.find(c => c.id == data.post.id);
877 createPostLikeRes(data, found);
881 export function createPostLikeRes(data: PostResponse, post: 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;
892 export function editPostFindRes(data: PostResponse, posts: Post[]) {
893 let found = posts.find(c => c.id == data.post.id);
895 editPostRes(data, found);
899 export function editPostRes(data: PostResponse, post: 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;
913 export function commentsToFlatNodes(comments: Comment[]): CommentNodeI[] {
914 let nodes: CommentNodeI[] = [];
915 for (let comment of comments) {
916 nodes.push({ comment: comment });
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) {
926 +a.comment.removed - +b.comment.removed ||
927 +a.comment.deleted - +b.comment.deleted ||
928 b.comment.score - a.comment.score
930 } else if (sort == CommentSortType.New) {
933 +a.comment.removed - +b.comment.removed ||
934 +a.comment.deleted - +b.comment.deleted ||
935 b.comment.published.localeCompare(a.comment.published)
937 } else if (sort == CommentSortType.Old) {
940 +a.comment.removed - +b.comment.removed ||
941 +a.comment.deleted - +b.comment.deleted ||
942 a.comment.published.localeCompare(b.comment.published)
944 } else if (sort == CommentSortType.Hot) {
947 +a.comment.removed - +b.comment.removed ||
948 +a.comment.deleted - +b.comment.deleted ||
949 hotRankComment(b.comment) - hotRankComment(a.comment)
953 // Go through the children recursively
954 for (let node of tree) {
956 commentSort(node.children, sort);
961 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
962 commentSort(tree, convertCommentSortType(sort));
965 function convertCommentSortType(sort: SortType): CommentSortType {
967 sort == SortType.TopAll ||
968 sort == SortType.TopDay ||
969 sort == SortType.TopWeek ||
970 sort == SortType.TopMonth ||
971 sort == SortType.TopYear
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;
979 return CommentSortType.Hot;
983 export function postSort(
986 communityType: boolean
988 // First, put removed and deleted comments at the bottom, then do your other sorts
990 sort == SortType.TopAll ||
991 sort == SortType.TopDay ||
992 sort == SortType.TopWeek ||
993 sort == SortType.TopMonth ||
994 sort == SortType.TopYear
998 +a.removed - +b.removed ||
999 +a.deleted - +b.deleted ||
1000 (communityType && +b.stickied - +a.stickied) ||
1003 } else if (sort == SortType.New) {
1006 +a.removed - +b.removed ||
1007 +a.deleted - +b.deleted ||
1008 (communityType && +b.stickied - +a.stickied) ||
1009 b.published.localeCompare(a.published)
1011 } else if (sort == SortType.Hot) {
1014 +a.removed - +b.removed ||
1015 +a.deleted - +b.deleted ||
1016 (communityType && +b.stickied - +a.stickied) ||
1017 b.hot_rank - a.hot_rank
1019 } else if (sort == SortType.Active) {
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
1030 export const colorList: string[] = [
1039 function hsl(num: number) {
1040 return `hsla(${num}, 35%, 50%, 1)`;
1043 // function randomHsl() {
1044 // return `hsla(${Math.random() * 360}, 100%, 50%, 1)`;
1047 export function previewLines(
1049 maxChars: number = 300,
1050 maxLines: number = 1
1056 // Use lines * 2 because markdown requires 2 lines
1057 .slice(0, maxLines * 2)
1062 export function hostname(url: string): string {
1063 let cUrl = new URL(url);
1064 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
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;
1071 const regex = new RegExp(/.*\S.*/, 'g');
1073 return regex.test(title);
1076 export function siteBannerCss(banner: string): string {
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; \
1085 max-height: 100vh; \
1089 export function isBrowser() {
1090 return typeof window !== 'undefined';
1093 export function setAuth(obj: any, auth: string) {
1099 export function setIsoData(context: any): IsoData {
1100 let isoData: IsoData = isBrowser()
1102 : context.router.staticContext;
1106 export function wsSubscribe(parseMessage: any): Subscription {
1108 return WebSocketService.Instance.subject
1109 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1111 msg => parseMessage(msg),
1112 err => console.error(err),
1113 () => console.log('complete')
1120 moment.updateLocale('en', {