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,
46 } from 'lemmy-js-client';
48 import { CommentSortType, DataType, IsoData } from './interfaces';
49 import { UserService, WebSocketService } from './services';
53 Tribute = require('tributejs');
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';
67 export const favIconUrl = '/static/assets/favicon.svg';
68 export const favIconPngUrl = '/static/assets/apple-touch-icon.png';
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/';
81 export const postRefetchSeconds: number = 60 * 1000;
82 export const fetchLimit: number = 20;
83 export const mentionDropdownFetchLimit = 10;
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' },
117 export const themes = [
133 const DEFAULT_ALPHABET =
134 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
136 function getRandomCharFromAlphabet(alphabet: string): string {
137 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
140 export function randomStr(
141 idDesiredLength: number = 20,
142 alphabet = DEFAULT_ALPHABET
145 * Create n-long array and map it to random chars from given alphabet.
146 * Then join individual chars as string
148 return Array.from({ length: idDesiredLength })
150 return getRandomCharFromAlphabet(alphabet);
155 export function wsJsonToRes(msg: WebSocketJsonResponse): WebSocketResponse {
156 let opStr: string = msg.op;
158 op: UserOperation[opStr],
163 export const md = new markdown_it({
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+(.*)$/);
175 render: function (tokens: any, idx: any) {
176 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
178 if (tokens[idx].nesting === 1) {
180 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
183 return '</details>\n';
187 .use(markdownitEmoji, {
188 defs: objectFlip(emojiShortName),
191 export function hotRankComment(comment: Comment): number {
192 return hotRank(comment.score, comment.published);
195 export function hotRankPost(post: Post): number {
196 return hotRank(post.score, post.newest_activity_time);
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;
206 (10000 * Math.log10(Math.max(1, 3 + score))) /
207 Math.pow(hoursElapsed + 2, 1.8);
209 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
214 export function mdToHtml(text: string) {
215 return { __html: md.render(text) };
218 export function getUnixTime(text: string): number {
219 return text ? new Date(text).getTime() / 1000 : undefined;
222 export function addTypeInfo<T>(
225 ): { type_: string; data: T }[] {
226 return arr.map(e => {
227 return { type_: name, data: e };
231 export function canMod(
235 onSelf: boolean = false
237 // You can do moderator actions only on the mods added after you.
239 let yourIndex = modIds.findIndex(id => id == user.id);
240 if (yourIndex == -1) {
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);
252 export function isMod(modIds: number[], creator_id: number): boolean {
253 return modIds.includes(creator_id);
256 const imageRegex = new RegExp(
257 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
259 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
261 export function isImage(url: string) {
262 return imageRegex.test(url);
265 export function isVideo(url: string) {
266 return videoRegex.test(url);
269 export function validURL(str: string) {
270 return !!new URL(str);
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}`;
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());
283 export function capitalizeFirstLetter(str: string): string {
284 return str.charAt(0).toUpperCase() + str.slice(1);
287 export function routeSortTypeToEnum(sort: string): SortType {
288 return SortType[sort];
291 export function routeListingTypeToEnum(type: string): ListingType {
292 return ListingType[type];
295 export function routeDataTypeToEnum(type: string): DataType {
296 return DataType[capitalizeFirstLetter(type)];
299 export function routeSearchTypeToEnum(type: string): SearchType {
300 return SearchType[type];
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;
309 export function debounce(
312 immediate: boolean = false
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.
319 // Calling debounce returns a new anonymous function
321 // reference the context and args for the setTimeout function
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;
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);
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
341 // Check if the function already ran with the immediate flag
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);
350 // Immediate mode and no wait timer? Execute the function..
351 if (callNow) func.apply(context, args);
356 export function getLanguage(override?: string): string {
357 let user = UserService.Instance.user;
358 let lang = override || (user && user.lang ? user.lang : 'browser');
360 if (lang == 'browser' && isBrowser()) {
361 return getBrowserLanguage();
368 export function getBrowserLanguage(): string {
369 return navigator.language;
372 export function getMomentLanguage(): string {
373 let lang = getLanguage();
374 if (lang.startsWith('zh')) {
376 } else if (lang.startsWith('sv')) {
378 } else if (lang.startsWith('fr')) {
380 } else if (lang.startsWith('de')) {
382 } else if (lang.startsWith('ru')) {
384 } else if (lang.startsWith('es')) {
386 } else if (lang.startsWith('eo')) {
388 } else if (lang.startsWith('nl')) {
390 } else if (lang.startsWith('it')) {
392 } else if (lang.startsWith('fi')) {
394 } else if (lang.startsWith('ca')) {
396 } else if (lang.startsWith('fa')) {
398 } else if (lang.startsWith('pl')) {
400 } else if (lang.startsWith('pt')) {
402 } else if (lang.startsWith('ja')) {
404 } else if (lang.startsWith('ka')) {
406 } else if (lang.startsWith('hi')) {
408 } else if (lang.startsWith('el')) {
410 } else if (lang.startsWith('eu')) {
412 } else if (lang.startsWith('gl')) {
414 } else if (lang.startsWith('tr')) {
416 } else if (lang.startsWith('hu')) {
418 } else if (lang.startsWith('uk')) {
420 } else if (lang.startsWith('sq')) {
422 } else if (lang.startsWith('km')) {
424 } else if (lang.startsWith('ga')) {
426 } else if (lang.startsWith('sr')) {
428 } else if (lang.startsWith('ko')) {
436 export function setTheme(theme: string, forceReload: boolean = false) {
440 if (theme === 'browser' && !forceReload) {
443 // This is only run on a force reload
444 if (theme == 'browser') {
448 // Unload all the other themes
449 for (var i = 0; i < themes.length; i++) {
450 let styleSheet = document.getElementById(themes[i]);
452 styleSheet.setAttribute('disabled', 'disabled');
457 .getElementById('default-light')
458 ?.setAttribute('disabled', 'disabled');
459 document.getElementById('default-dark')?.setAttribute('disabled', 'disabled');
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');
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');
472 link.rel = 'stylesheet';
473 link.type = 'text/css';
476 head.appendChild(link);
480 export function objectFlip(obj: any) {
482 Object.keys(obj).forEach(key => {
488 export function showAvatars(): boolean {
490 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
491 !UserService.Instance.user
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());
502 userCreationDate.date() === currentDate.date() &&
503 userCreationDate.month() === currentDate.month() &&
504 userCreationDate.year() !== currentDate.year()
508 export function isCommentType(
509 item: Comment | PrivateMessage | Post
512 (item as Comment).community_id !== undefined &&
513 (item as Comment).content !== undefined
517 export function isPostType(
518 item: Comment | PrivateMessage | Post
520 return (item as Post).stickied !== undefined;
523 export function toast(text: string, background: string = 'success') {
525 let backgroundColor = `var(--${background})`;
528 backgroundColor: backgroundColor,
535 export function pictrsDeleteToast(
536 clickToDeleteText: string,
537 deletePictureText: string,
541 let backgroundColor = `var(--light)`;
542 let toast = Toastify({
543 text: clickToDeleteText,
544 backgroundColor: backgroundColor,
550 window.location.replace(deleteUrl);
551 alert(deletePictureText);
560 interface NotifyInfo {
567 export function messageToastify(info: NotifyInfo, router: any) {
569 let htmlBody = info.body ? md.render(info.body) : '';
570 let backgroundColor = `var(--light)`;
572 let toast = Toastify({
573 text: `${htmlBody}<br />${info.name}`,
575 backgroundColor: backgroundColor,
576 className: 'text-dark',
584 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', {