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 repoUrl = 'https://github.com/LemmyNet';
79 export const joinLemmyUrl = 'https://join.lemmy.ml';
80 export const supportLemmyUrl = 'https://join.lemmy.ml/sponsors';
81 export const docsUrl = '/docs/en/index.html';
82 export const helpGuideUrl = '/docs/en/about/guide.html'; // TODO find a way to redirect to the non-en folder
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: 'oc', name: 'Occitan' },
111 { code: 'pl', name: 'Polski' },
112 { code: 'pt_BR', name: 'Português Brasileiro' },
113 { code: 'zh', name: '中文' },
114 { code: 'fi', name: 'Suomi' },
115 { code: 'fr', name: 'Français' },
116 { code: 'sv', name: 'Svenska' },
117 { code: 'sq', name: 'Shqip' },
118 { code: 'sr_Latn', name: 'srpski' },
119 { code: 'tr', name: 'Türkçe' },
120 { code: 'uk', name: 'Українська Mова' },
121 { code: 'ru', name: 'Русский' },
122 { code: 'nl', name: 'Nederlands' },
123 { code: 'it', name: 'Italiano' },
126 export const themes = [
142 const DEFAULT_ALPHABET =
143 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
145 function getRandomCharFromAlphabet(alphabet: string): string {
146 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
149 export function randomStr(
150 idDesiredLength: number = 20,
151 alphabet = DEFAULT_ALPHABET
154 * Create n-long array and map it to random chars from given alphabet.
155 * Then join individual chars as string
157 return Array.from({ length: idDesiredLength })
159 return getRandomCharFromAlphabet(alphabet);
164 export function wsJsonToRes<ResponseType>(
165 msg: WebSocketJsonResponse<ResponseType>
166 ): WebSocketResponse<ResponseType> {
173 export function wsUserOp(msg: any): UserOperation {
174 let opStr: string = msg.op;
175 return UserOperation[opStr];
178 export const md = new markdown_it({
183 .use(markdown_it_sub)
184 .use(markdown_it_sup)
185 .use(markdown_it_container, 'spoiler', {
186 validate: function (params: any) {
187 return params.trim().match(/^spoiler\s+(.*)$/);
190 render: function (tokens: any, idx: any) {
191 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
193 if (tokens[idx].nesting === 1) {
195 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
198 return '</details>\n';
202 .use(markdownitEmoji, {
203 defs: objectFlip(emojiShortName),
206 export function hotRankComment(comment_view: CommentView): number {
207 return hotRank(comment_view.counts.score, comment_view.comment.published);
210 export function hotRankActivePost(post_view: PostView): number {
211 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
214 export function hotRankPost(post_view: PostView): number {
215 return hotRank(post_view.counts.score, post_view.post.published);
218 export function hotRank(score: number, timeStr: string): number {
219 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
220 let date: Date = new Date(timeStr + 'Z'); // Add Z to convert from UTC date
221 let now: Date = new Date();
222 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
225 (10000 * Math.log10(Math.max(1, 3 + score))) /
226 Math.pow(hoursElapsed + 2, 1.8);
228 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
233 export function mdToHtml(text: string) {
234 return { __html: md.render(text) };
237 export function getUnixTime(text: string): number {
238 return text ? new Date(text).getTime() / 1000 : undefined;
241 export function canMod(
242 user: UserSafeSettings,
245 onSelf: boolean = false
247 // You can do moderator actions only on the mods added after you.
249 let yourIndex = modIds.findIndex(id => id == user.id);
250 if (yourIndex == -1) {
253 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
254 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
255 return !modIds.includes(creator_id);
262 export function isMod(modIds: number[], creator_id: number): boolean {
263 return modIds.includes(creator_id);
266 const imageRegex = new RegExp(
267 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
269 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
271 export function isImage(url: string) {
272 return imageRegex.test(url);
275 export function isVideo(url: string) {
276 return videoRegex.test(url);
279 export function validURL(str: string) {
280 return !!new URL(str);
283 export function communityRSSUrl(actorId: string, sort: string): string {
284 let url = new URL(actorId);
285 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
288 export function validEmail(email: string) {
289 let re = /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
290 return re.test(String(email).toLowerCase());
293 export function capitalizeFirstLetter(str: string): string {
294 return str.charAt(0).toUpperCase() + str.slice(1);
297 export function routeSortTypeToEnum(sort: string): SortType {
298 return SortType[sort];
301 export function listingTypeFromNum(type_: number): ListingType {
302 return Object.values(ListingType)[type_];
305 export function sortTypeFromNum(type_: number): SortType {
306 return Object.values(SortType)[type_];
309 export function routeListingTypeToEnum(type: string): ListingType {
310 return ListingType[type];
313 export function routeDataTypeToEnum(type: string): DataType {
314 return DataType[capitalizeFirstLetter(type)];
317 export function routeSearchTypeToEnum(type: string): SearchType {
318 return SearchType[type];
321 export async function getPageTitle(url: string) {
322 let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
323 let title = await res.title;
327 export function debounce(
330 immediate: boolean = false
332 // 'private' variable for instance
333 // The returned function will be able to reference this due to closure.
334 // Each call to the returned function will share this common timer.
337 // Calling debounce returns a new anonymous function
339 // reference the context and args for the setTimeout function
343 // Should the function be called now? If immediate is true
344 // and not already in a timeout then the answer is: Yes
345 var callNow = immediate && !timeout;
347 // This is the basic debounce behaviour where you can call this
348 // function several times, but it will only execute once
349 // [before or after imposing a delay].
350 // Each time the returned function is called, the timer starts over.
351 clearTimeout(timeout);
353 // Set the new timeout
354 timeout = setTimeout(function () {
355 // Inside the timeout function, clear the timeout variable
356 // which will let the next execution run when in 'immediate' mode
359 // Check if the function already ran with the immediate flag
361 // Call the original function with apply
362 // apply lets you define the 'this' object as well as the arguments
363 // (both captured before setTimeout)
364 func.apply(context, args);
368 // Immediate mode and no wait timer? Execute the function..
369 if (callNow) func.apply(context, args);
374 export function getLanguage(override?: string): string {
375 let user = UserService.Instance.user;
376 let lang = override || (user && user.lang ? user.lang : 'browser');
378 if (lang == 'browser' && isBrowser()) {
379 return getBrowserLanguage();
386 export function getBrowserLanguage(): string {
387 return navigator.language;
390 export function getMomentLanguage(): string {
391 let lang = getLanguage();
392 if (lang.startsWith('zh')) {
394 } else if (lang.startsWith('sv')) {
396 } else if (lang.startsWith('fr')) {
398 } else if (lang.startsWith('de')) {
400 } else if (lang.startsWith('ru')) {
402 } else if (lang.startsWith('es')) {
404 } else if (lang.startsWith('eo')) {
406 } else if (lang.startsWith('nl')) {
408 } else if (lang.startsWith('it')) {
410 } else if (lang.startsWith('fi')) {
412 } else if (lang.startsWith('ca')) {
414 } else if (lang.startsWith('fa')) {
416 } else if (lang.startsWith('pl')) {
418 } else if (lang.startsWith('pt')) {
420 } else if (lang.startsWith('ja')) {
422 } else if (lang.startsWith('ka')) {
424 } else if (lang.startsWith('hi')) {
426 } else if (lang.startsWith('el')) {
428 } else if (lang.startsWith('eu')) {
430 } else if (lang.startsWith('gl')) {
432 } else if (lang.startsWith('tr')) {
434 } else if (lang.startsWith('hu')) {
436 } else if (lang.startsWith('uk')) {
438 } else if (lang.startsWith('sq')) {
440 } else if (lang.startsWith('km')) {
442 } else if (lang.startsWith('ga')) {
444 } else if (lang.startsWith('sr')) {
446 } else if (lang.startsWith('ko')) {
448 } else if (lang.startsWith('da')) {
450 } else if (lang.startsWith('oc')) {
458 export function setTheme(theme: string, forceReload: boolean = false) {
462 if (theme === 'browser' && !forceReload) {
465 // This is only run on a force reload
466 if (theme == 'browser') {
470 // Unload all the other themes
471 for (var i = 0; i < themes.length; i++) {
472 let styleSheet = document.getElementById(themes[i]);
474 styleSheet.setAttribute('disabled', 'disabled');
479 .getElementById('default-light')
480 ?.setAttribute('disabled', 'disabled');
481 document.getElementById('default-dark')?.setAttribute('disabled', 'disabled');
483 // Load the theme dynamically
484 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
485 loadCss(theme, cssLoc);
486 document.getElementById(theme).removeAttribute('disabled');
489 export function loadCss(id: string, loc: string) {
490 if (!document.getElementById(id)) {
491 var head = document.getElementsByTagName('head')[0];
492 var link = document.createElement('link');
494 link.rel = 'stylesheet';
495 link.type = 'text/css';
498 head.appendChild(link);
502 export function objectFlip(obj: any) {
504 Object.keys(obj).forEach(key => {
510 export function showAvatars(): boolean {
512 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
513 !UserService.Instance.user
517 export function isCakeDay(published: string): boolean {
518 // moment(undefined) or moment.utc(undefined) returns the current date/time
519 // moment(null) or moment.utc(null) returns null
520 const userCreationDate = moment.utc(published || null).local();
521 const currentDate = moment(new Date());
524 userCreationDate.date() === currentDate.date() &&
525 userCreationDate.month() === currentDate.month() &&
526 userCreationDate.year() !== currentDate.year()
530 export function toast(text: string, background: string = 'success') {
532 let backgroundColor = `var(--${background})`;
535 backgroundColor: backgroundColor,
542 export function pictrsDeleteToast(
543 clickToDeleteText: string,
544 deletePictureText: string,
548 let backgroundColor = `var(--light)`;
549 let toast = Toastify({
550 text: clickToDeleteText,
551 backgroundColor: backgroundColor,
557 window.location.replace(deleteUrl);
558 alert(deletePictureText);
567 interface NotifyInfo {
574 export function messageToastify(info: NotifyInfo, router: any) {
576 let htmlBody = info.body ? md.render(info.body) : '';
577 let backgroundColor = `var(--light)`;
579 let toast = Toastify({
580 text: `${htmlBody}<br />${info.name}`,
581 avatar: info.icon ? info.icon : null,
582 backgroundColor: backgroundColor,
583 className: 'text-dark',
591 router.history.push(info.link);
598 export function notifyPost(post_view: PostView, router: any) {
599 let info: NotifyInfo = {
600 name: post_view.community.name,
601 icon: post_view.community.icon,
602 link: `/post/${post_view.post.id}`,
603 body: post_view.post.name,
605 notify(info, router);
608 export function notifyComment(comment_view: CommentView, router: any) {
609 let info: NotifyInfo = {
610 name: comment_view.creator.name,
611 icon: comment_view.creator.avatar,
612 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
613 body: comment_view.comment.content,
615 notify(info, router);
618 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
619 let info: NotifyInfo = {
620 name: pmv.creator.name,
621 icon: pmv.creator.avatar,
623 body: pmv.private_message.content,
625 notify(info, router);
628 function notify(info: NotifyInfo, router: any) {
629 messageToastify(info, router);
631 if (Notification.permission !== 'granted') Notification.requestPermission();
633 var notification = new Notification(info.name, {
638 notification.onclick = () => {
639 event.preventDefault();
640 router.history.push(info.link);
645 export function setupTribute() {
647 noMatchTemplate: function () {
654 menuItemTemplate: (item: any) => {
655 let shortName = `:${item.original.key}:`;
656 return `${item.original.val} ${shortName}`;
658 selectTemplate: (item: any) => {
659 return `:${item.original.key}:`;
661 values: Object.entries(emojiShortName).map(e => {
662 return { key: e[1], val: e[0] };
665 autocompleteMode: true,
667 // menuItemLimit: mentionDropdownFetchLimit,
668 menuShowMinLength: 2,
673 selectTemplate: (item: any) => {
674 let link = item.original.local
675 ? `[${item.original.key}](/u/${item.original.name})`
676 : `[${item.original.key}](/user/${item.original.id})`;
679 values: (text: string, cb: any) => {
680 userSearch(text, (users: any) => cb(users));
683 autocompleteMode: true,
685 // menuItemLimit: mentionDropdownFetchLimit,
686 menuShowMinLength: 2,
692 selectTemplate: (item: any) => {
693 let link = item.original.local
694 ? `[${item.original.key}](/c/${item.original.name})`
695 : `[${item.original.key}](/community/${item.original.id})`;
698 values: (text: string, cb: any) => {
699 communitySearch(text, (communities: any) => cb(communities));
702 autocompleteMode: true,
704 // menuItemLimit: mentionDropdownFetchLimit,
705 menuShowMinLength: 2,
713 tippyInstance = tippy('[data-tippy-content]');
716 export function setupTippy() {
718 tippyInstance.forEach(e => e.destroy());
719 tippyInstance = tippy('[data-tippy-content]', {
721 // Display on "long press"
722 touch: ['hold', 500],
727 function userSearch(text: string, cb: any) {
731 type_: SearchType.Users,
732 sort: SortType.TopAll,
734 limit: mentionDropdownFetchLimit,
735 auth: authField(false),
738 WebSocketService.Instance.send(wsClient.search(form));
740 let userSub = WebSocketService.Instance.subject.subscribe(
742 let res = wsJsonToRes(msg);
743 if (res.op == UserOperation.Search) {
744 let data = res.data as SearchResponse;
745 let users = data.users.map(uv => {
747 key: `@${uv.user.name}@${hostname(uv.user.actor_id)}`,
749 local: uv.user.local,
754 userSub.unsubscribe();
757 err => console.error(err),
758 () => console.log('complete')
765 function communitySearch(text: string, cb: any) {
769 type_: SearchType.Communities,
770 sort: SortType.TopAll,
772 limit: mentionDropdownFetchLimit,
773 auth: authField(false),
776 WebSocketService.Instance.send(wsClient.search(form));
778 let communitySub = WebSocketService.Instance.subject.subscribe(
780 let res = wsJsonToRes(msg);
781 if (res.op == UserOperation.Search) {
782 let data = res.data as SearchResponse;
783 let communities = data.communities.map(cv => {
785 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
786 name: cv.community.name,
787 local: cv.community.local,
792 communitySub.unsubscribe();
795 err => console.error(err),
796 () => console.log('complete')
803 export function getListingTypeFromProps(props: any): ListingType {
804 return props.match.params.listing_type
805 ? routeListingTypeToEnum(props.match.params.listing_type)
806 : UserService.Instance.user
807 ? Object.values(ListingType)[UserService.Instance.user.default_listing_type]
811 // TODO might need to add a user setting for this too
812 export function getDataTypeFromProps(props: any): DataType {
813 return props.match.params.data_type
814 ? routeDataTypeToEnum(props.match.params.data_type)
818 export function getSortTypeFromProps(props: any): SortType {
819 return props.match.params.sort
820 ? routeSortTypeToEnum(props.match.params.sort)
821 : UserService.Instance.user
822 ? Object.values(SortType)[UserService.Instance.user.default_sort_type]
826 export function getPageFromProps(props: any): number {
827 return props.match.params.page ? Number(props.match.params.page) : 1;
830 export function getRecipientIdFromProps(props: any): number {
831 return props.match.params.recipient_id
832 ? Number(props.match.params.recipient_id)
836 export function getIdFromProps(props: any): number {
837 return Number(props.match.params.id);
840 export function getCommentIdFromProps(props: any): number {
841 return Number(props.match.params.comment_id);
844 export function getUsernameFromProps(props: any): string {
845 return props.match.params.username;
848 export function editCommentRes(data: CommentView, comments: CommentView[]) {
849 let found = comments.find(c => c.comment.id == data.comment.id);
851 found.comment.content = data.comment.content;
852 found.comment.updated = data.comment.updated;
853 found.comment.removed = data.comment.removed;
854 found.comment.deleted = data.comment.deleted;
855 found.counts.upvotes = data.counts.upvotes;
856 found.counts.downvotes = data.counts.downvotes;
857 found.counts.score = data.counts.score;
861 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
862 let found = comments.find(c => c.comment.id == data.comment.id);
864 found.saved = data.saved;
868 export function createCommentLikeRes(
870 comments: CommentView[]
872 let found = comments.find(c => c.comment.id === data.comment.id);
874 found.counts.score = data.counts.score;
875 found.counts.upvotes = data.counts.upvotes;
876 found.counts.downvotes = data.counts.downvotes;
877 if (data.my_vote !== null) {
878 found.my_vote = data.my_vote;
883 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
884 let found = posts.find(p => p.post.id == data.post.id);
886 createPostLikeRes(data, found);
890 export function createPostLikeRes(data: PostView, post_view: PostView) {
892 post_view.counts.score = data.counts.score;
893 post_view.counts.upvotes = data.counts.upvotes;
894 post_view.counts.downvotes = data.counts.downvotes;
895 if (data.my_vote !== null) {
896 post_view.my_vote = data.my_vote;
901 export function editPostFindRes(data: PostView, posts: PostView[]) {
902 let found = posts.find(p => p.post.id == data.post.id);
904 editPostRes(data, found);
908 export function editPostRes(data: PostView, post: PostView) {
910 post.post.url = data.post.url;
911 post.post.name = data.post.name;
912 post.post.nsfw = data.post.nsfw;
913 post.post.deleted = data.post.deleted;
914 post.post.removed = data.post.removed;
915 post.post.stickied = data.post.stickied;
916 post.post.body = data.post.body;
917 post.post.locked = data.post.locked;
918 post.saved = data.saved;
922 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
923 let nodes: CommentNodeI[] = [];
924 for (let comment of comments) {
925 nodes.push({ comment_view: comment });
930 export function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
931 // First, put removed and deleted comments at the bottom, then do your other sorts
932 if (sort == CommentSortType.Top) {
935 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
936 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
937 b.comment_view.counts.score - a.comment_view.counts.score
939 } else if (sort == CommentSortType.New) {
942 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
943 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
944 b.comment_view.comment.published.localeCompare(
945 a.comment_view.comment.published
948 } else if (sort == CommentSortType.Old) {
951 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
952 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
953 a.comment_view.comment.published.localeCompare(
954 b.comment_view.comment.published
957 } else if (sort == CommentSortType.Hot) {
960 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
961 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
962 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
966 // Go through the children recursively
967 for (let node of tree) {
969 commentSort(node.children, sort);
974 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
975 commentSort(tree, convertCommentSortType(sort));
978 function convertCommentSortType(sort: SortType): CommentSortType {
980 sort == SortType.TopAll ||
981 sort == SortType.TopDay ||
982 sort == SortType.TopWeek ||
983 sort == SortType.TopMonth ||
984 sort == SortType.TopYear
986 return CommentSortType.Top;
987 } else if (sort == SortType.New) {
988 return CommentSortType.New;
989 } else if (sort == SortType.Hot || sort == SortType.Active) {
990 return CommentSortType.Hot;
992 return CommentSortType.Hot;
996 export function postSort(
999 communityType: boolean
1001 // First, put removed and deleted comments at the bottom, then do your other sorts
1003 sort == SortType.TopAll ||
1004 sort == SortType.TopDay ||
1005 sort == SortType.TopWeek ||
1006 sort == SortType.TopMonth ||
1007 sort == SortType.TopYear
1011 +a.post.removed - +b.post.removed ||
1012 +a.post.deleted - +b.post.deleted ||
1013 (communityType && +b.post.stickied - +a.post.stickied) ||
1014 b.counts.score - a.counts.score
1016 } else if (sort == SortType.New) {
1019 +a.post.removed - +b.post.removed ||
1020 +a.post.deleted - +b.post.deleted ||
1021 (communityType && +b.post.stickied - +a.post.stickied) ||
1022 b.post.published.localeCompare(a.post.published)
1024 } else if (sort == SortType.Hot) {
1027 +a.post.removed - +b.post.removed ||
1028 +a.post.deleted - +b.post.deleted ||
1029 (communityType && +b.post.stickied - +a.post.stickied) ||
1030 hotRankPost(b) - hotRankPost(a)
1032 } else if (sort == SortType.Active) {
1035 +a.post.removed - +b.post.removed ||
1036 +a.post.deleted - +b.post.deleted ||
1037 (communityType && +b.post.stickied - +a.post.stickied) ||
1038 hotRankActivePost(b) - hotRankActivePost(a)
1043 export const colorList: string[] = [
1052 function hsl(num: number) {
1053 return `hsla(${num}, 35%, 50%, 1)`;
1056 // function randomHsl() {
1057 // return `hsla(${Math.random() * 360}, 100%, 50%, 1)`;
1060 export function previewLines(
1062 maxChars: number = 300,
1063 maxLines: number = 1
1069 // Use lines * 2 because markdown requires 2 lines
1070 .slice(0, maxLines * 2)
1075 export function hostname(url: string): string {
1076 let cUrl = new URL(url);
1077 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1080 export function validTitle(title?: string): boolean {
1081 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1082 if (title === null || title.length < 3) return true;
1084 const regex = new RegExp(/.*\S.*/, 'g');
1086 return regex.test(title);
1089 export function siteBannerCss(banner: string): string {
1091 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1092 background-attachment: fixed; \
1093 background-position: top; \
1094 background-repeat: no-repeat; \
1095 background-size: 100% cover; \
1098 max-height: 100vh; \
1102 export function isBrowser() {
1103 return typeof window !== 'undefined';
1106 export function setIsoData(context: any): IsoData {
1107 let isoData: IsoData = isBrowser()
1109 : context.router.staticContext;
1113 export function wsSubscribe(parseMessage: any): Subscription {
1115 return WebSocketService.Instance.subject
1116 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1118 msg => parseMessage(msg),
1119 err => console.error(err),
1120 () => console.log('complete')
1127 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1133 export function authField(
1134 throwErr: boolean = true,
1135 auth = UserService.Instance.auth
1137 if (auth == null && throwErr) {
1138 toast(i18n.t('not_logged_in'), 'danger');
1139 throw 'Not logged in';
1145 moment.updateLocale('en', {