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 helpGuideUrl = '/docs/about_guide.html';
75 export const markdownHelpUrl = `${helpGuideUrl}#markdown-guide`;
76 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
77 export const archiveUrl = 'https://archive.is';
78 export const elementUrl = 'https://element.io/';
80 export const postRefetchSeconds: number = 60 * 1000;
81 export const fetchLimit: number = 20;
82 export const mentionDropdownFetchLimit = 10;
84 export const languages = [
85 { code: 'ca', name: 'Català' },
86 { code: 'en', name: 'English' },
87 { code: 'el', name: 'Ελληνικά' },
88 { code: 'eu', name: 'Euskara' },
89 { code: 'eo', name: 'Esperanto' },
90 { code: 'es', name: 'Español' },
91 { code: 'de', name: 'Deutsch' },
92 { code: 'ga', name: 'Gaeilge' },
93 { code: 'gl', name: 'Galego' },
94 { code: 'hu', name: 'Magyar Nyelv' },
95 { code: 'ka', name: 'ქართული ენა' },
96 { code: 'ko', name: '한국어' },
97 { code: 'km', name: 'ភាសាខ្មែរ' },
98 { code: 'hi', name: 'मानक हिन्दी' },
99 { code: 'fa', name: 'فارسی' },
100 { code: 'ja', name: '日本語' },
101 { code: 'pl', name: 'Polski' },
102 { code: 'pt_BR', name: 'Português Brasileiro' },
103 { code: 'zh', name: '中文' },
104 { code: 'fi', name: 'Suomi' },
105 { code: 'fr', name: 'Français' },
106 { code: 'sv', name: 'Svenska' },
107 { code: 'sq', name: 'Shqip' },
108 { code: 'sr_Latn', name: 'srpski' },
109 { code: 'tr', name: 'Türkçe' },
110 { code: 'uk', name: 'Українська Mова' },
111 { code: 'ru', name: 'Русский' },
112 { code: 'nl', name: 'Nederlands' },
113 { code: 'it', name: 'Italiano' },
116 export const themes = [
132 const DEFAULT_ALPHABET =
133 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
135 function getRandomCharFromAlphabet(alphabet: string): string {
136 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
139 export function randomStr(
140 idDesiredLength: number = 20,
141 alphabet = DEFAULT_ALPHABET
144 * Create n-long array and map it to random chars from given alphabet.
145 * Then join individual chars as string
147 return Array.from({ length: idDesiredLength })
149 return getRandomCharFromAlphabet(alphabet);
154 export function wsJsonToRes(msg: WebSocketJsonResponse): WebSocketResponse {
155 let opStr: string = msg.op;
157 op: UserOperation[opStr],
162 export const md = new markdown_it({
167 .use(markdown_it_sub)
168 .use(markdown_it_sup)
169 .use(markdown_it_container, 'spoiler', {
170 validate: function (params: any) {
171 return params.trim().match(/^spoiler\s+(.*)$/);
174 render: function (tokens: any, idx: any) {
175 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
177 if (tokens[idx].nesting === 1) {
179 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
182 return '</details>\n';
186 .use(markdownitEmoji, {
187 defs: objectFlip(emojiShortName),
190 export function hotRankComment(comment: Comment): number {
191 return hotRank(comment.score, comment.published);
194 export function hotRankPost(post: Post): number {
195 return hotRank(post.score, post.newest_activity_time);
198 export function hotRank(score: number, timeStr: string): number {
199 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
200 let date: Date = new Date(timeStr + 'Z'); // Add Z to convert from UTC date
201 let now: Date = new Date();
202 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
205 (10000 * Math.log10(Math.max(1, 3 + score))) /
206 Math.pow(hoursElapsed + 2, 1.8);
208 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
213 export function mdToHtml(text: string) {
214 return { __html: md.render(text) };
217 export function getUnixTime(text: string): number {
218 return text ? new Date(text).getTime() / 1000 : undefined;
221 export function addTypeInfo<T>(
224 ): { type_: string; data: T }[] {
225 return arr.map(e => {
226 return { type_: name, data: e };
230 export function canMod(
234 onSelf: boolean = false
236 // You can do moderator actions only on the mods added after you.
238 let yourIndex = modIds.findIndex(id => id == user.id);
239 if (yourIndex == -1) {
242 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
243 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
244 return !modIds.includes(creator_id);
251 export function isMod(modIds: number[], creator_id: number): boolean {
252 return modIds.includes(creator_id);
255 const imageRegex = new RegExp(
256 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
258 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
260 export function isImage(url: string) {
261 return imageRegex.test(url);
264 export function isVideo(url: string) {
265 return videoRegex.test(url);
268 export function validURL(str: string) {
269 return !!new URL(str);
272 export function communityRSSUrl(actorId: string, sort: string): string {
273 let url = new URL(actorId);
274 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
277 export function validEmail(email: string) {
278 let re = /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
279 return re.test(String(email).toLowerCase());
282 export function capitalizeFirstLetter(str: string): string {
283 return str.charAt(0).toUpperCase() + str.slice(1);
286 export function routeSortTypeToEnum(sort: string): SortType {
287 return SortType[sort];
290 export function routeListingTypeToEnum(type: string): ListingType {
291 return ListingType[type];
294 export function routeDataTypeToEnum(type: string): DataType {
295 return DataType[capitalizeFirstLetter(type)];
298 export function routeSearchTypeToEnum(type: string): SearchType {
299 return SearchType[type];
302 export async function getPageTitle(url: string) {
303 let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
304 let title = await res.title;
308 export function debounce(
311 immediate: boolean = false
313 // 'private' variable for instance
314 // The returned function will be able to reference this due to closure.
315 // Each call to the returned function will share this common timer.
318 // Calling debounce returns a new anonymous function
320 // reference the context and args for the setTimeout function
324 // Should the function be called now? If immediate is true
325 // and not already in a timeout then the answer is: Yes
326 var callNow = immediate && !timeout;
328 // This is the basic debounce behaviour where you can call this
329 // function several times, but it will only execute once
330 // [before or after imposing a delay].
331 // Each time the returned function is called, the timer starts over.
332 clearTimeout(timeout);
334 // Set the new timeout
335 timeout = setTimeout(function () {
336 // Inside the timeout function, clear the timeout variable
337 // which will let the next execution run when in 'immediate' mode
340 // Check if the function already ran with the immediate flag
342 // Call the original function with apply
343 // apply lets you define the 'this' object as well as the arguments
344 // (both captured before setTimeout)
345 func.apply(context, args);
349 // Immediate mode and no wait timer? Execute the function..
350 if (callNow) func.apply(context, args);
355 export function getLanguage(override?: string): string {
356 let user = UserService.Instance.user;
357 let lang = override || (user && user.lang ? user.lang : 'browser');
359 if (lang == 'browser' && isBrowser()) {
360 return getBrowserLanguage();
367 export function getBrowserLanguage(): string {
368 return navigator.language;
371 export function getMomentLanguage(): string {
372 let lang = getLanguage();
373 if (lang.startsWith('zh')) {
375 } else if (lang.startsWith('sv')) {
377 } else if (lang.startsWith('fr')) {
379 } else if (lang.startsWith('de')) {
381 } else if (lang.startsWith('ru')) {
383 } else if (lang.startsWith('es')) {
385 } else if (lang.startsWith('eo')) {
387 } else if (lang.startsWith('nl')) {
389 } else if (lang.startsWith('it')) {
391 } else if (lang.startsWith('fi')) {
393 } else if (lang.startsWith('ca')) {
395 } else if (lang.startsWith('fa')) {
397 } else if (lang.startsWith('pl')) {
399 } else if (lang.startsWith('pt')) {
401 } else if (lang.startsWith('ja')) {
403 } else if (lang.startsWith('ka')) {
405 } else if (lang.startsWith('hi')) {
407 } else if (lang.startsWith('el')) {
409 } else if (lang.startsWith('eu')) {
411 } else if (lang.startsWith('gl')) {
413 } else if (lang.startsWith('tr')) {
415 } else if (lang.startsWith('hu')) {
417 } else if (lang.startsWith('uk')) {
419 } else if (lang.startsWith('sq')) {
421 } else if (lang.startsWith('km')) {
423 } else if (lang.startsWith('ga')) {
425 } else if (lang.startsWith('sr')) {
427 } else if (lang.startsWith('ko')) {
435 export function setTheme(theme: string, forceReload: boolean = false) {
439 if (theme === 'browser' && !forceReload) {
442 // This is only run on a force reload
443 if (theme == 'browser') {
447 // Unload all the other themes
448 for (var i = 0; i < themes.length; i++) {
449 let styleSheet = document.getElementById(themes[i]);
451 styleSheet.setAttribute('disabled', 'disabled');
456 .getElementById('default-light')
457 ?.setAttribute('disabled', 'disabled');
458 document.getElementById('default-dark')?.setAttribute('disabled', 'disabled');
460 // Load the theme dynamically
461 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
462 loadCss(theme, cssLoc);
463 document.getElementById(theme).removeAttribute('disabled');
466 export function loadCss(id: string, loc: string) {
467 if (!document.getElementById(id)) {
468 var head = document.getElementsByTagName('head')[0];
469 var link = document.createElement('link');
471 link.rel = 'stylesheet';
472 link.type = 'text/css';
475 head.appendChild(link);
479 export function objectFlip(obj: any) {
481 Object.keys(obj).forEach(key => {
487 export function showAvatars(): boolean {
489 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
490 !UserService.Instance.user
494 export function isCakeDay(published: string): boolean {
495 // moment(undefined) or moment.utc(undefined) returns the current date/time
496 // moment(null) or moment.utc(null) returns null
497 const userCreationDate = moment.utc(published || null).local();
498 const currentDate = moment(new Date());
501 userCreationDate.date() === currentDate.date() &&
502 userCreationDate.month() === currentDate.month() &&
503 userCreationDate.year() !== currentDate.year()
507 export function isCommentType(
508 item: Comment | PrivateMessage | Post
511 (item as Comment).community_id !== undefined &&
512 (item as Comment).content !== undefined
516 export function isPostType(
517 item: Comment | PrivateMessage | Post
519 return (item as Post).stickied !== undefined;
522 export function toast(text: string, background: string = 'success') {
523 let backgroundColor = `var(--${background})`;
526 backgroundColor: backgroundColor,
532 export function pictrsDeleteToast(
533 clickToDeleteText: string,
534 deletePictureText: string,
537 let backgroundColor = `var(--light)`;
538 let toast = Toastify({
539 text: clickToDeleteText,
540 backgroundColor: backgroundColor,
546 window.location.replace(deleteUrl);
547 alert(deletePictureText);
555 interface NotifyInfo {
562 export function messageToastify(info: NotifyInfo, router: any) {
563 let htmlBody = info.body ? md.render(info.body) : '';
564 let backgroundColor = `var(--light)`;
566 let toast = Toastify({
567 text: `${htmlBody}<br />${info.name}`,
569 backgroundColor: backgroundColor,
570 className: 'text-dark',
578 router.history.push(info.link);
584 export function notifyPost(post: Post, router: any) {
585 let info: NotifyInfo = {
586 name: post.community_name,
587 icon: post.community_icon ? post.community_icon : defaultFavIcon,
588 link: `/post/${post.id}`,
591 notify(info, router);
594 export function notifyComment(comment: Comment, router: any) {
595 let info: NotifyInfo = {
596 name: comment.creator_name,
597 icon: comment.creator_avatar ? comment.creator_avatar : defaultFavIcon,
598 link: `/post/${comment.post_id}/comment/${comment.id}`,
599 body: comment.content,
601 notify(info, router);
604 export function notifyPrivateMessage(pm: PrivateMessage, router: any) {
605 let info: NotifyInfo = {
606 name: pm.creator_name,
607 icon: pm.creator_avatar ? pm.creator_avatar : defaultFavIcon,
611 notify(info, router);
614 function notify(info: NotifyInfo, router: any) {
615 messageToastify(info, router);
617 if (Notification.permission !== 'granted') Notification.requestPermission();
619 var notification = new Notification(info.name, {
624 notification.onclick = () => {
625 event.preventDefault();
626 router.history.push(info.link);
631 export function setupTribute() {
633 noMatchTemplate: function () {
640 menuItemTemplate: (item: any) => {
641 let shortName = `:${item.original.key}:`;
642 return `${item.original.val} ${shortName}`;
644 selectTemplate: (item: any) => {
645 return `:${item.original.key}:`;
647 values: Object.entries(emojiShortName).map(e => {
648 return { key: e[1], val: e[0] };
651 autocompleteMode: true,
653 // menuItemLimit: mentionDropdownFetchLimit,
654 menuShowMinLength: 2,
659 selectTemplate: (item: any) => {
660 let link = item.original.local
661 ? `[${item.original.key}](/u/${item.original.name})`
662 : `[${item.original.key}](/user/${item.original.id})`;
665 values: (text: string, cb: any) => {
666 userSearch(text, (users: any) => cb(users));
669 autocompleteMode: true,
671 // menuItemLimit: mentionDropdownFetchLimit,
672 menuShowMinLength: 2,
678 selectTemplate: (item: any) => {
679 let link = item.original.local
680 ? `[${item.original.key}](/c/${item.original.name})`
681 : `[${item.original.key}](/community/${item.original.id})`;
684 values: (text: string, cb: any) => {
685 communitySearch(text, (communities: any) => cb(communities));
688 autocompleteMode: true,
690 // menuItemLimit: mentionDropdownFetchLimit,
691 menuShowMinLength: 2,
699 tippyInstance = tippy('[data-tippy-content]');
702 export function setupTippy() {
704 tippyInstance.forEach(e => e.destroy());
705 tippyInstance = tippy('[data-tippy-content]', {
707 // Display on "long press"
708 touch: ['hold', 500],
713 function userSearch(text: string, cb: any) {
715 let form: SearchForm = {
717 type_: SearchType.Users,
718 sort: SortType.TopAll,
720 limit: mentionDropdownFetchLimit,
723 WebSocketService.Instance.search(form);
725 let userSub = WebSocketService.Instance.subject.subscribe(
727 let res = wsJsonToRes(msg);
728 if (res.op == UserOperation.Search) {
729 let data = res.data as SearchResponse;
730 let users = data.users.map(u => {
732 key: `@${u.name}@${hostname(u.actor_id)}`,
739 userSub.unsubscribe();
742 err => console.error(err),
743 () => console.log('complete')
750 function communitySearch(text: string, cb: any) {
752 let form: SearchForm = {
754 type_: SearchType.Communities,
755 sort: SortType.TopAll,
757 limit: mentionDropdownFetchLimit,
760 WebSocketService.Instance.search(form);
762 let communitySub = WebSocketService.Instance.subject.subscribe(
764 let res = wsJsonToRes(msg);
765 if (res.op == UserOperation.Search) {
766 let data = res.data as SearchResponse;
767 let communities = data.communities.map(c => {
769 key: `!${c.name}@${hostname(c.actor_id)}`,
776 communitySub.unsubscribe();
779 err => console.error(err),
780 () => console.log('complete')
787 export function getListingTypeFromProps(props: any): ListingType {
788 return props.match.params.listing_type
789 ? routeListingTypeToEnum(props.match.params.listing_type)
790 : UserService.Instance.user
791 ? Object.values(ListingType)[UserService.Instance.user.default_listing_type]
795 // TODO might need to add a user setting for this too
796 export function getDataTypeFromProps(props: any): DataType {
797 return props.match.params.data_type
798 ? routeDataTypeToEnum(props.match.params.data_type)
802 export function getSortTypeFromProps(props: any): SortType {
803 return props.match.params.sort
804 ? routeSortTypeToEnum(props.match.params.sort)
805 : UserService.Instance.user
806 ? Object.values(SortType)[UserService.Instance.user.default_sort_type]
810 export function getPageFromProps(props: any): number {
811 return props.match.params.page ? Number(props.match.params.page) : 1;
814 export function getRecipientIdFromProps(props: any): number {
815 return props.match.params.recipient_id
816 ? Number(props.match.params.recipient_id)
820 export function getIdFromProps(props: any): number {
821 return Number(props.match.params.id);
824 export function getCommentIdFromProps(props: any): number {
825 return Number(props.match.params.comment_id);
828 export function getUsernameFromProps(props: any): string {
829 return props.match.params.username;
832 export function editCommentRes(data: CommentResponse, comments: Comment[]) {
833 let found = comments.find(c => c.id == data.comment.id);
835 found.content = data.comment.content;
836 found.updated = data.comment.updated;
837 found.removed = data.comment.removed;
838 found.deleted = data.comment.deleted;
839 found.upvotes = data.comment.upvotes;
840 found.downvotes = data.comment.downvotes;
841 found.score = data.comment.score;
845 export function saveCommentRes(data: CommentResponse, comments: Comment[]) {
846 let found = comments.find(c => c.id == data.comment.id);
848 found.saved = data.comment.saved;
852 export function createCommentLikeRes(
853 data: CommentResponse,
856 let found: Comment = comments.find(c => c.id === data.comment.id);
858 found.score = data.comment.score;
859 found.upvotes = data.comment.upvotes;
860 found.downvotes = data.comment.downvotes;
861 if (data.comment.my_vote !== null) {
862 found.my_vote = data.comment.my_vote;
867 export function createPostLikeFindRes(data: PostResponse, posts: Post[]) {
868 let found = posts.find(c => c.id == data.post.id);
870 createPostLikeRes(data, found);
874 export function createPostLikeRes(data: PostResponse, post: Post) {
876 post.score = data.post.score;
877 post.upvotes = data.post.upvotes;
878 post.downvotes = data.post.downvotes;
879 if (data.post.my_vote !== null) {
880 post.my_vote = data.post.my_vote;
885 export function editPostFindRes(data: PostResponse, posts: Post[]) {
886 let found = posts.find(c => c.id == data.post.id);
888 editPostRes(data, found);
892 export function editPostRes(data: PostResponse, post: Post) {
894 post.url = data.post.url;
895 post.name = data.post.name;
896 post.nsfw = data.post.nsfw;
897 post.deleted = data.post.deleted;
898 post.removed = data.post.removed;
899 post.stickied = data.post.stickied;
900 post.body = data.post.body;
901 post.locked = data.post.locked;
902 post.saved = data.post.saved;
906 export function commentsToFlatNodes(comments: Comment[]): CommentNodeI[] {
907 let nodes: CommentNodeI[] = [];
908 for (let comment of comments) {
909 nodes.push({ comment: comment });
914 export function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
915 // First, put removed and deleted comments at the bottom, then do your other sorts
916 if (sort == CommentSortType.Top) {
919 +a.comment.removed - +b.comment.removed ||
920 +a.comment.deleted - +b.comment.deleted ||
921 b.comment.score - a.comment.score
923 } else if (sort == CommentSortType.New) {
926 +a.comment.removed - +b.comment.removed ||
927 +a.comment.deleted - +b.comment.deleted ||
928 b.comment.published.localeCompare(a.comment.published)
930 } else if (sort == CommentSortType.Old) {
933 +a.comment.removed - +b.comment.removed ||
934 +a.comment.deleted - +b.comment.deleted ||
935 a.comment.published.localeCompare(b.comment.published)
937 } else if (sort == CommentSortType.Hot) {
940 +a.comment.removed - +b.comment.removed ||
941 +a.comment.deleted - +b.comment.deleted ||
942 hotRankComment(b.comment) - hotRankComment(a.comment)
946 // Go through the children recursively
947 for (let node of tree) {
949 commentSort(node.children, sort);
954 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
955 commentSort(tree, convertCommentSortType(sort));
958 function convertCommentSortType(sort: SortType): CommentSortType {
960 sort == SortType.TopAll ||
961 sort == SortType.TopDay ||
962 sort == SortType.TopWeek ||
963 sort == SortType.TopMonth ||
964 sort == SortType.TopYear
966 return CommentSortType.Top;
967 } else if (sort == SortType.New) {
968 return CommentSortType.New;
969 } else if (sort == SortType.Hot || sort == SortType.Active) {
970 return CommentSortType.Hot;
972 return CommentSortType.Hot;
976 export function postSort(
979 communityType: boolean
981 // First, put removed and deleted comments at the bottom, then do your other sorts
983 sort == SortType.TopAll ||
984 sort == SortType.TopDay ||
985 sort == SortType.TopWeek ||
986 sort == SortType.TopMonth ||
987 sort == SortType.TopYear
991 +a.removed - +b.removed ||
992 +a.deleted - +b.deleted ||
993 (communityType && +b.stickied - +a.stickied) ||
996 } else if (sort == SortType.New) {
999 +a.removed - +b.removed ||
1000 +a.deleted - +b.deleted ||
1001 (communityType && +b.stickied - +a.stickied) ||
1002 b.published.localeCompare(a.published)
1004 } else if (sort == SortType.Hot) {
1007 +a.removed - +b.removed ||
1008 +a.deleted - +b.deleted ||
1009 (communityType && +b.stickied - +a.stickied) ||
1010 b.hot_rank - a.hot_rank
1012 } else if (sort == SortType.Active) {
1015 +a.removed - +b.removed ||
1016 +a.deleted - +b.deleted ||
1017 (communityType && +b.stickied - +a.stickied) ||
1018 b.hot_rank_active - a.hot_rank_active
1023 export const colorList: string[] = [
1032 function hsl(num: number) {
1033 return `hsla(${num}, 35%, 50%, 1)`;
1036 // function randomHsl() {
1037 // return `hsla(${Math.random() * 360}, 100%, 50%, 1)`;
1040 export function previewLines(
1042 maxChars: number = 300,
1043 maxLines: number = 1
1049 // Use lines * 2 because markdown requires 2 lines
1050 .slice(0, maxLines * 2)
1055 export function hostname(url: string): string {
1056 let cUrl = new URL(url);
1057 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1060 export function validTitle(title?: string): boolean {
1061 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1062 if (title === null || title.length < 3) return true;
1064 const regex = new RegExp(/.*\S.*/, 'g');
1066 return regex.test(title);
1069 export function siteBannerCss(banner: string): string {
1071 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1072 background-attachment: fixed; \
1073 background-position: top; \
1074 background-repeat: no-repeat; \
1075 background-size: 100% cover; \
1078 max-height: 100vh; \
1082 export function isBrowser() {
1083 return typeof window !== 'undefined';
1086 export function setAuth(obj: any, auth: string) {
1092 export function setIsoData(context: any): IsoData {
1093 let isoData: IsoData = isBrowser()
1095 : context.router.staticContext;
1099 export function wsSubscribe(parseMessage: any): Subscription {
1101 return WebSocketService.Instance.subject
1102 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1104 msg => parseMessage(msg),
1105 err => console.error(err),
1106 () => console.log('complete')
1113 moment.updateLocale('en', {