1 import 'moment/locale/es';
2 import 'moment/locale/el';
3 import 'moment/locale/eu';
4 import 'moment/locale/eo';
5 import 'moment/locale/de';
6 import 'moment/locale/zh-cn';
7 import 'moment/locale/fr';
8 import 'moment/locale/sv';
9 import 'moment/locale/ru';
10 import 'moment/locale/nl';
11 import 'moment/locale/it';
12 import 'moment/locale/fi';
13 import 'moment/locale/ca';
14 import 'moment/locale/fa';
15 import 'moment/locale/pl';
16 import 'moment/locale/pt-br';
17 import 'moment/locale/ja';
18 import 'moment/locale/ka';
19 import 'moment/locale/hi';
20 import 'moment/locale/gl';
21 import 'moment/locale/tr';
22 import 'moment/locale/hu';
23 import 'moment/locale/uk';
24 import 'moment/locale/sq';
25 import 'moment/locale/km';
26 import 'moment/locale/ga';
27 import 'moment/locale/sr';
28 import 'moment/locale/ko';
29 import 'moment/locale/da';
39 WebSocketJsonResponse,
45 } from 'lemmy-js-client';
51 CommentNode as CommentNodeI,
52 } from './interfaces';
53 import { UserService, WebSocketService } from './services';
57 Tribute = require('tributejs');
59 import markdown_it from 'markdown-it';
60 import markdown_it_sub from 'markdown-it-sub';
61 import markdown_it_sup from 'markdown-it-sup';
62 import markdownitEmoji from 'markdown-it-emoji/light';
63 import markdown_it_container from 'markdown-it-container';
64 import emojiShortName from 'emoji-short-name';
65 import Toastify from 'toastify-js';
66 import tippy from 'tippy.js';
67 import moment from 'moment';
68 import { Subscription } from 'rxjs';
69 import { retryWhen, delay, take } from 'rxjs/operators';
70 import { i18n } from './i18next';
72 export const wsClient = new LemmyWebsocket();
74 export const favIconUrl = '/static/assets/favicon.svg';
75 export const favIconPngUrl = '/static/assets/apple-touch-icon.png';
77 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
78 export const defaultFavIcon = 'test';
79 export const repoUrl = 'https://github.com/LemmyNet';
80 export const joinLemmyUrl = 'https://join.lemmy.ml';
81 export const supportLemmyUrl = 'https://join.lemmy.ml/sponsors';
82 export const helpGuideUrl = '/docs/about/guide.html';
83 export const markdownHelpUrl = `${helpGuideUrl}#markdown-guide`;
84 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
85 export const archiveUrl = 'https://archive.is';
86 export const elementUrl = 'https://element.io/';
88 export const postRefetchSeconds: number = 60 * 1000;
89 export const fetchLimit: number = 20;
90 export const mentionDropdownFetchLimit = 10;
92 export const languages = [
93 { code: 'ca', name: 'Català' },
94 { code: 'en', name: 'English' },
95 { code: 'el', name: 'Ελληνικά' },
96 { code: 'eu', name: 'Euskara' },
97 { code: 'eo', name: 'Esperanto' },
98 { code: 'es', name: 'Español' },
99 { code: 'da', name: 'Dansk' },
100 { code: 'de', name: 'Deutsch' },
101 { code: 'ga', name: 'Gaeilge' },
102 { code: 'gl', name: 'Galego' },
103 { code: 'hu', name: 'Magyar Nyelv' },
104 { code: 'ka', name: 'ქართული ენა' },
105 { code: 'ko', name: '한국어' },
106 { code: 'km', name: 'ភាសាខ្មែរ' },
107 { code: 'hi', name: 'मानक हिन्दी' },
108 { code: 'fa', name: 'فارسی' },
109 { code: 'ja', name: '日本語' },
110 { code: 'pl', name: 'Polski' },
111 { code: 'pt_BR', name: 'Português Brasileiro' },
112 { code: 'zh', name: '中文' },
113 { code: 'fi', name: 'Suomi' },
114 { code: 'fr', name: 'Français' },
115 { code: 'sv', name: 'Svenska' },
116 { code: 'sq', name: 'Shqip' },
117 { code: 'sr_Latn', name: 'srpski' },
118 { code: 'tr', name: 'Türkçe' },
119 { code: 'uk', name: 'Українська Mова' },
120 { code: 'ru', name: 'Русский' },
121 { code: 'nl', name: 'Nederlands' },
122 { code: 'it', name: 'Italiano' },
125 export const themes = [
141 const DEFAULT_ALPHABET =
142 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
144 function getRandomCharFromAlphabet(alphabet: string): string {
145 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
148 export function randomStr(
149 idDesiredLength: number = 20,
150 alphabet = DEFAULT_ALPHABET
153 * Create n-long array and map it to random chars from given alphabet.
154 * Then join individual chars as string
156 return Array.from({ length: idDesiredLength })
158 return getRandomCharFromAlphabet(alphabet);
163 export function wsJsonToRes<ResponseType>(
164 msg: WebSocketJsonResponse<ResponseType>
165 ): WebSocketResponse<ResponseType> {
172 export function wsUserOp(msg: any): UserOperation {
173 let opStr: string = msg.op;
174 return UserOperation[opStr];
177 export const md = new markdown_it({
182 .use(markdown_it_sub)
183 .use(markdown_it_sup)
184 .use(markdown_it_container, 'spoiler', {
185 validate: function (params: any) {
186 return params.trim().match(/^spoiler\s+(.*)$/);
189 render: function (tokens: any, idx: any) {
190 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
192 if (tokens[idx].nesting === 1) {
194 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
197 return '</details>\n';
201 .use(markdownitEmoji, {
202 defs: objectFlip(emojiShortName),
205 export function hotRankComment(comment_view: CommentView): number {
206 return hotRank(comment_view.counts.score, comment_view.comment.published);
209 export function hotRankActivePost(post_view: PostView): number {
210 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
213 export function hotRankPost(post_view: PostView): number {
214 return hotRank(post_view.counts.score, post_view.post.published);
217 export function hotRank(score: number, timeStr: string): number {
218 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
219 let date: Date = new Date(timeStr + 'Z'); // Add Z to convert from UTC date
220 let now: Date = new Date();
221 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
224 (10000 * Math.log10(Math.max(1, 3 + score))) /
225 Math.pow(hoursElapsed + 2, 1.8);
227 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
232 export function mdToHtml(text: string) {
233 return { __html: md.render(text) };
236 export function getUnixTime(text: string): number {
237 return text ? new Date(text).getTime() / 1000 : undefined;
240 export function canMod(
244 onSelf: boolean = false
246 // You can do moderator actions only on the mods added after you.
248 let yourIndex = modIds.findIndex(id => id == user.id);
249 if (yourIndex == -1) {
252 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
253 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
254 return !modIds.includes(creator_id);
261 export function isMod(modIds: number[], creator_id: number): boolean {
262 return modIds.includes(creator_id);
265 const imageRegex = new RegExp(
266 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
268 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
270 export function isImage(url: string) {
271 return imageRegex.test(url);
274 export function isVideo(url: string) {
275 return videoRegex.test(url);
278 export function validURL(str: string) {
279 return !!new URL(str);
282 export function communityRSSUrl(actorId: string, sort: string): string {
283 let url = new URL(actorId);
284 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
287 export function validEmail(email: string) {
288 let re = /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
289 return re.test(String(email).toLowerCase());
292 export function capitalizeFirstLetter(str: string): string {
293 return str.charAt(0).toUpperCase() + str.slice(1);
296 export function routeSortTypeToEnum(sort: string): SortType {
297 return SortType[sort];
300 export function routeListingTypeToEnum(type: string): ListingType {
301 return ListingType[type];
304 export function routeDataTypeToEnum(type: string): DataType {
305 return DataType[capitalizeFirstLetter(type)];
308 export function routeSearchTypeToEnum(type: string): SearchType {
309 return SearchType[type];
312 export async function getPageTitle(url: string) {
313 let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
314 let title = await res.title;
318 export function debounce(
321 immediate: boolean = false
323 // 'private' variable for instance
324 // The returned function will be able to reference this due to closure.
325 // Each call to the returned function will share this common timer.
328 // Calling debounce returns a new anonymous function
330 // reference the context and args for the setTimeout function
334 // Should the function be called now? If immediate is true
335 // and not already in a timeout then the answer is: Yes
336 var callNow = immediate && !timeout;
338 // This is the basic debounce behaviour where you can call this
339 // function several times, but it will only execute once
340 // [before or after imposing a delay].
341 // Each time the returned function is called, the timer starts over.
342 clearTimeout(timeout);
344 // Set the new timeout
345 timeout = setTimeout(function () {
346 // Inside the timeout function, clear the timeout variable
347 // which will let the next execution run when in 'immediate' mode
350 // Check if the function already ran with the immediate flag
352 // Call the original function with apply
353 // apply lets you define the 'this' object as well as the arguments
354 // (both captured before setTimeout)
355 func.apply(context, args);
359 // Immediate mode and no wait timer? Execute the function..
360 if (callNow) func.apply(context, args);
365 export function getLanguage(override?: string): string {
366 let user = UserService.Instance.user;
367 let lang = override || (user && user.lang ? user.lang : 'browser');
369 if (lang == 'browser' && isBrowser()) {
370 return getBrowserLanguage();
377 export function getBrowserLanguage(): string {
378 return navigator.language;
381 export function getMomentLanguage(): string {
382 let lang = getLanguage();
383 if (lang.startsWith('zh')) {
385 } else if (lang.startsWith('sv')) {
387 } else if (lang.startsWith('fr')) {
389 } else if (lang.startsWith('de')) {
391 } else if (lang.startsWith('ru')) {
393 } else if (lang.startsWith('es')) {
395 } else if (lang.startsWith('eo')) {
397 } else if (lang.startsWith('nl')) {
399 } else if (lang.startsWith('it')) {
401 } else if (lang.startsWith('fi')) {
403 } else if (lang.startsWith('ca')) {
405 } else if (lang.startsWith('fa')) {
407 } else if (lang.startsWith('pl')) {
409 } else if (lang.startsWith('pt')) {
411 } else if (lang.startsWith('ja')) {
413 } else if (lang.startsWith('ka')) {
415 } else if (lang.startsWith('hi')) {
417 } else if (lang.startsWith('el')) {
419 } else if (lang.startsWith('eu')) {
421 } else if (lang.startsWith('gl')) {
423 } else if (lang.startsWith('tr')) {
425 } else if (lang.startsWith('hu')) {
427 } else if (lang.startsWith('uk')) {
429 } else if (lang.startsWith('sq')) {
431 } else if (lang.startsWith('km')) {
433 } else if (lang.startsWith('ga')) {
435 } else if (lang.startsWith('sr')) {
437 } else if (lang.startsWith('ko')) {
439 } else if (lang.startsWith('da')) {
447 export function setTheme(theme: string, forceReload: boolean = false) {
451 if (theme === 'browser' && !forceReload) {
454 // This is only run on a force reload
455 if (theme == 'browser') {
459 // Unload all the other themes
460 for (var i = 0; i < themes.length; i++) {
461 let styleSheet = document.getElementById(themes[i]);
463 styleSheet.setAttribute('disabled', 'disabled');
468 .getElementById('default-light')
469 ?.setAttribute('disabled', 'disabled');
470 document.getElementById('default-dark')?.setAttribute('disabled', 'disabled');
472 // Load the theme dynamically
473 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
474 loadCss(theme, cssLoc);
475 document.getElementById(theme).removeAttribute('disabled');
478 export function loadCss(id: string, loc: string) {
479 if (!document.getElementById(id)) {
480 var head = document.getElementsByTagName('head')[0];
481 var link = document.createElement('link');
483 link.rel = 'stylesheet';
484 link.type = 'text/css';
487 head.appendChild(link);
491 export function objectFlip(obj: any) {
493 Object.keys(obj).forEach(key => {
499 export function showAvatars(): boolean {
501 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
502 !UserService.Instance.user
506 export function isCakeDay(published: string): boolean {
507 // moment(undefined) or moment.utc(undefined) returns the current date/time
508 // moment(null) or moment.utc(null) returns null
509 const userCreationDate = moment.utc(published || null).local();
510 const currentDate = moment(new Date());
513 userCreationDate.date() === currentDate.date() &&
514 userCreationDate.month() === currentDate.month() &&
515 userCreationDate.year() !== currentDate.year()
519 export function toast(text: string, background: string = 'success') {
521 let backgroundColor = `var(--${background})`;
524 backgroundColor: backgroundColor,
531 export function pictrsDeleteToast(
532 clickToDeleteText: string,
533 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);
556 interface NotifyInfo {
563 export function messageToastify(info: NotifyInfo, router: any) {
565 let htmlBody = info.body ? md.render(info.body) : '';
566 let backgroundColor = `var(--light)`;
568 let toast = Toastify({
569 text: `${htmlBody}<br />${info.name}`,
571 backgroundColor: backgroundColor,
572 className: 'text-dark',
580 router.history.push(info.link);
587 export function notifyPost(post_view: PostView, router: any) {
588 let info: NotifyInfo = {
589 name: post_view.community.name,
590 icon: post_view.community.icon ? post_view.community.icon : defaultFavIcon,
591 link: `/post/${post_view.post.id}`,
592 body: post_view.post.name,
594 notify(info, router);
597 export function notifyComment(comment_view: CommentView, router: any) {
598 let info: NotifyInfo = {
599 name: comment_view.creator.name,
600 icon: comment_view.creator.avatar
601 ? comment_view.creator.avatar
603 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
604 body: comment_view.comment.content,
606 notify(info, router);
609 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
610 let info: NotifyInfo = {
611 name: pmv.creator.name,
612 icon: pmv.creator.avatar ? pmv.creator.avatar : defaultFavIcon,
614 body: pmv.private_message.content,
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) {
722 type_: SearchType.Users,
723 sort: SortType.TopAll,
725 limit: mentionDropdownFetchLimit,
726 auth: authField(false),
729 WebSocketService.Instance.send(wsClient.search(form));
731 let userSub = WebSocketService.Instance.subject.subscribe(
733 let res = wsJsonToRes(msg);
734 if (res.op == UserOperation.Search) {
735 let data = res.data as SearchResponse;
736 let users = data.users.map(uv => {
738 key: `@${uv.user.name}@${hostname(uv.user.actor_id)}`,
740 local: uv.user.local,
745 userSub.unsubscribe();
748 err => console.error(err),
749 () => console.log('complete')
756 function communitySearch(text: string, cb: any) {
760 type_: SearchType.Communities,
761 sort: SortType.TopAll,
763 limit: mentionDropdownFetchLimit,
764 auth: authField(false),
767 WebSocketService.Instance.send(wsClient.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(cv => {
776 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
777 name: cv.community.name,
778 local: cv.community.local,
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: CommentView, comments: CommentView[]) {
840 let found = comments.find(c => c.comment.id == data.comment.id);
842 found.comment.content = data.comment.content;
843 found.comment.updated = data.comment.updated;
844 found.comment.removed = data.comment.removed;
845 found.comment.deleted = data.comment.deleted;
846 found.counts.upvotes = data.counts.upvotes;
847 found.counts.downvotes = data.counts.downvotes;
848 found.counts.score = data.counts.score;
852 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
853 let found = comments.find(c => c.comment.id == data.comment.id);
855 found.saved = data.saved;
859 export function createCommentLikeRes(
861 comments: CommentView[]
863 let found = comments.find(c => c.comment.id === data.comment.id);
865 found.counts.score = data.counts.score;
866 found.counts.upvotes = data.counts.upvotes;
867 found.counts.downvotes = data.counts.downvotes;
868 if (data.my_vote !== null) {
869 found.my_vote = data.my_vote;
874 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
875 let found = posts.find(p => p.post.id == data.post.id);
877 createPostLikeRes(data, found);
881 export function createPostLikeRes(data: PostView, post_view: PostView) {
883 post_view.counts.score = data.counts.score;
884 post_view.counts.upvotes = data.counts.upvotes;
885 post_view.counts.downvotes = data.counts.downvotes;
886 if (data.my_vote !== null) {
887 post_view.my_vote = data.my_vote;
892 export function editPostFindRes(data: PostView, posts: PostView[]) {
893 let found = posts.find(p => p.post.id == data.post.id);
895 editPostRes(data, found);
899 export function editPostRes(data: PostView, post: PostView) {
901 post.post.url = data.post.url;
902 post.post.name = data.post.name;
903 post.post.nsfw = data.post.nsfw;
904 post.post.deleted = data.post.deleted;
905 post.post.removed = data.post.removed;
906 post.post.stickied = data.post.stickied;
907 post.post.body = data.post.body;
908 post.post.locked = data.post.locked;
909 post.saved = data.saved;
913 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
914 let nodes: CommentNodeI[] = [];
915 for (let comment of comments) {
916 nodes.push({ comment_view: 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_view.comment.removed - +b.comment_view.comment.removed ||
927 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
928 b.comment_view.counts.score - a.comment_view.counts.score
930 } else if (sort == CommentSortType.New) {
933 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
934 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
935 b.comment_view.comment.published.localeCompare(
936 a.comment_view.comment.published
939 } else if (sort == CommentSortType.Old) {
942 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
943 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
944 a.comment_view.comment.published.localeCompare(
945 b.comment_view.comment.published
948 } else if (sort == CommentSortType.Hot) {
951 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
952 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
953 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
957 // Go through the children recursively
958 for (let node of tree) {
960 commentSort(node.children, sort);
965 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
966 commentSort(tree, convertCommentSortType(sort));
969 function convertCommentSortType(sort: SortType): CommentSortType {
971 sort == SortType.TopAll ||
972 sort == SortType.TopDay ||
973 sort == SortType.TopWeek ||
974 sort == SortType.TopMonth ||
975 sort == SortType.TopYear
977 return CommentSortType.Top;
978 } else if (sort == SortType.New) {
979 return CommentSortType.New;
980 } else if (sort == SortType.Hot || sort == SortType.Active) {
981 return CommentSortType.Hot;
983 return CommentSortType.Hot;
987 export function postSort(
990 communityType: boolean
992 // First, put removed and deleted comments at the bottom, then do your other sorts
994 sort == SortType.TopAll ||
995 sort == SortType.TopDay ||
996 sort == SortType.TopWeek ||
997 sort == SortType.TopMonth ||
998 sort == SortType.TopYear
1002 +a.post.removed - +b.post.removed ||
1003 +a.post.deleted - +b.post.deleted ||
1004 (communityType && +b.post.stickied - +a.post.stickied) ||
1005 b.counts.score - a.counts.score
1007 } else if (sort == SortType.New) {
1010 +a.post.removed - +b.post.removed ||
1011 +a.post.deleted - +b.post.deleted ||
1012 (communityType && +b.post.stickied - +a.post.stickied) ||
1013 b.post.published.localeCompare(a.post.published)
1015 } else if (sort == SortType.Hot) {
1018 +a.post.removed - +b.post.removed ||
1019 +a.post.deleted - +b.post.deleted ||
1020 (communityType && +b.post.stickied - +a.post.stickied) ||
1021 hotRankPost(b) - hotRankPost(a)
1023 } else if (sort == SortType.Active) {
1026 +a.post.removed - +b.post.removed ||
1027 +a.post.deleted - +b.post.deleted ||
1028 (communityType && +b.post.stickied - +a.post.stickied) ||
1029 hotRankActivePost(b) - hotRankActivePost(a)
1034 export const colorList: string[] = [
1043 function hsl(num: number) {
1044 return `hsla(${num}, 35%, 50%, 1)`;
1047 // function randomHsl() {
1048 // return `hsla(${Math.random() * 360}, 100%, 50%, 1)`;
1051 export function previewLines(
1053 maxChars: number = 300,
1054 maxLines: number = 1
1060 // Use lines * 2 because markdown requires 2 lines
1061 .slice(0, maxLines * 2)
1066 export function hostname(url: string): string {
1067 let cUrl = new URL(url);
1068 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1071 export function validTitle(title?: string): boolean {
1072 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1073 if (title === null || title.length < 3) return true;
1075 const regex = new RegExp(/.*\S.*/, 'g');
1077 return regex.test(title);
1080 export function siteBannerCss(banner: string): string {
1082 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1083 background-attachment: fixed; \
1084 background-position: top; \
1085 background-repeat: no-repeat; \
1086 background-size: 100% cover; \
1089 max-height: 100vh; \
1093 export function isBrowser() {
1094 return typeof window !== 'undefined';
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 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1124 export function authField(
1125 throwErr: boolean = true,
1126 auth = UserService.Instance.auth
1128 if (auth == null && throwErr) {
1129 toast(i18n.t('not_logged_in'), 'danger');
1130 throw 'Not logged in';
1136 moment.updateLocale('en', {