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 listingTypeFromNum(type_: number): ListingType {
301 return Object.values(ListingType)[type_];
304 export function sortTypeFromNum(type_: number): SortType {
305 return Object.values(SortType)[type_];
308 export function routeListingTypeToEnum(type: string): ListingType {
309 return ListingType[type];
312 export function routeDataTypeToEnum(type: string): DataType {
313 return DataType[capitalizeFirstLetter(type)];
316 export function routeSearchTypeToEnum(type: string): SearchType {
317 return SearchType[type];
320 export async function getPageTitle(url: string) {
321 let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
322 let title = await res.title;
326 export function debounce(
329 immediate: boolean = false
331 // 'private' variable for instance
332 // The returned function will be able to reference this due to closure.
333 // Each call to the returned function will share this common timer.
336 // Calling debounce returns a new anonymous function
338 // reference the context and args for the setTimeout function
342 // Should the function be called now? If immediate is true
343 // and not already in a timeout then the answer is: Yes
344 var callNow = immediate && !timeout;
346 // This is the basic debounce behaviour where you can call this
347 // function several times, but it will only execute once
348 // [before or after imposing a delay].
349 // Each time the returned function is called, the timer starts over.
350 clearTimeout(timeout);
352 // Set the new timeout
353 timeout = setTimeout(function () {
354 // Inside the timeout function, clear the timeout variable
355 // which will let the next execution run when in 'immediate' mode
358 // Check if the function already ran with the immediate flag
360 // Call the original function with apply
361 // apply lets you define the 'this' object as well as the arguments
362 // (both captured before setTimeout)
363 func.apply(context, args);
367 // Immediate mode and no wait timer? Execute the function..
368 if (callNow) func.apply(context, args);
373 export function getLanguage(override?: string): string {
374 let user = UserService.Instance.user;
375 let lang = override || (user && user.lang ? user.lang : 'browser');
377 if (lang == 'browser' && isBrowser()) {
378 return getBrowserLanguage();
385 export function getBrowserLanguage(): string {
386 return navigator.language;
389 export function getMomentLanguage(): string {
390 let lang = getLanguage();
391 if (lang.startsWith('zh')) {
393 } else if (lang.startsWith('sv')) {
395 } else if (lang.startsWith('fr')) {
397 } else if (lang.startsWith('de')) {
399 } else if (lang.startsWith('ru')) {
401 } else if (lang.startsWith('es')) {
403 } else if (lang.startsWith('eo')) {
405 } else if (lang.startsWith('nl')) {
407 } else if (lang.startsWith('it')) {
409 } else if (lang.startsWith('fi')) {
411 } else if (lang.startsWith('ca')) {
413 } else if (lang.startsWith('fa')) {
415 } else if (lang.startsWith('pl')) {
417 } else if (lang.startsWith('pt')) {
419 } else if (lang.startsWith('ja')) {
421 } else if (lang.startsWith('ka')) {
423 } else if (lang.startsWith('hi')) {
425 } else if (lang.startsWith('el')) {
427 } else if (lang.startsWith('eu')) {
429 } else if (lang.startsWith('gl')) {
431 } else if (lang.startsWith('tr')) {
433 } else if (lang.startsWith('hu')) {
435 } else if (lang.startsWith('uk')) {
437 } else if (lang.startsWith('sq')) {
439 } else if (lang.startsWith('km')) {
441 } else if (lang.startsWith('ga')) {
443 } else if (lang.startsWith('sr')) {
445 } else if (lang.startsWith('ko')) {
447 } else if (lang.startsWith('da')) {
455 export function setTheme(theme: string, forceReload: boolean = false) {
459 if (theme === 'browser' && !forceReload) {
462 // This is only run on a force reload
463 if (theme == 'browser') {
467 // Unload all the other themes
468 for (var i = 0; i < themes.length; i++) {
469 let styleSheet = document.getElementById(themes[i]);
471 styleSheet.setAttribute('disabled', 'disabled');
476 .getElementById('default-light')
477 ?.setAttribute('disabled', 'disabled');
478 document.getElementById('default-dark')?.setAttribute('disabled', 'disabled');
480 // Load the theme dynamically
481 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
482 loadCss(theme, cssLoc);
483 document.getElementById(theme).removeAttribute('disabled');
486 export function loadCss(id: string, loc: string) {
487 if (!document.getElementById(id)) {
488 var head = document.getElementsByTagName('head')[0];
489 var link = document.createElement('link');
491 link.rel = 'stylesheet';
492 link.type = 'text/css';
495 head.appendChild(link);
499 export function objectFlip(obj: any) {
501 Object.keys(obj).forEach(key => {
507 export function showAvatars(): boolean {
509 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
510 !UserService.Instance.user
514 export function isCakeDay(published: string): boolean {
515 // moment(undefined) or moment.utc(undefined) returns the current date/time
516 // moment(null) or moment.utc(null) returns null
517 const userCreationDate = moment.utc(published || null).local();
518 const currentDate = moment(new Date());
521 userCreationDate.date() === currentDate.date() &&
522 userCreationDate.month() === currentDate.month() &&
523 userCreationDate.year() !== currentDate.year()
527 export function toast(text: string, background: string = 'success') {
529 let backgroundColor = `var(--${background})`;
532 backgroundColor: backgroundColor,
539 export function pictrsDeleteToast(
540 clickToDeleteText: string,
541 deletePictureText: string,
545 let backgroundColor = `var(--light)`;
546 let toast = Toastify({
547 text: clickToDeleteText,
548 backgroundColor: backgroundColor,
554 window.location.replace(deleteUrl);
555 alert(deletePictureText);
564 interface NotifyInfo {
571 export function messageToastify(info: NotifyInfo, router: any) {
573 let htmlBody = info.body ? md.render(info.body) : '';
574 let backgroundColor = `var(--light)`;
576 let toast = Toastify({
577 text: `${htmlBody}<br />${info.name}`,
579 backgroundColor: backgroundColor,
580 className: 'text-dark',
588 router.history.push(info.link);
595 export function notifyPost(post_view: PostView, router: any) {
596 let info: NotifyInfo = {
597 name: post_view.community.name,
598 icon: post_view.community.icon ? post_view.community.icon : defaultFavIcon,
599 link: `/post/${post_view.post.id}`,
600 body: post_view.post.name,
602 notify(info, router);
605 export function notifyComment(comment_view: CommentView, router: any) {
606 let info: NotifyInfo = {
607 name: comment_view.creator.name,
608 icon: comment_view.creator.avatar
609 ? comment_view.creator.avatar
611 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
612 body: comment_view.comment.content,
614 notify(info, router);
617 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
618 let info: NotifyInfo = {
619 name: pmv.creator.name,
620 icon: pmv.creator.avatar ? pmv.creator.avatar : defaultFavIcon,
622 body: pmv.private_message.content,
624 notify(info, router);
627 function notify(info: NotifyInfo, router: any) {
628 messageToastify(info, router);
630 if (Notification.permission !== 'granted') Notification.requestPermission();
632 var notification = new Notification(info.name, {
637 notification.onclick = () => {
638 event.preventDefault();
639 router.history.push(info.link);
644 export function setupTribute() {
646 noMatchTemplate: function () {
653 menuItemTemplate: (item: any) => {
654 let shortName = `:${item.original.key}:`;
655 return `${item.original.val} ${shortName}`;
657 selectTemplate: (item: any) => {
658 return `:${item.original.key}:`;
660 values: Object.entries(emojiShortName).map(e => {
661 return { key: e[1], val: e[0] };
664 autocompleteMode: true,
666 // menuItemLimit: mentionDropdownFetchLimit,
667 menuShowMinLength: 2,
672 selectTemplate: (item: any) => {
673 let link = item.original.local
674 ? `[${item.original.key}](/u/${item.original.name})`
675 : `[${item.original.key}](/user/${item.original.id})`;
678 values: (text: string, cb: any) => {
679 userSearch(text, (users: any) => cb(users));
682 autocompleteMode: true,
684 // menuItemLimit: mentionDropdownFetchLimit,
685 menuShowMinLength: 2,
691 selectTemplate: (item: any) => {
692 let link = item.original.local
693 ? `[${item.original.key}](/c/${item.original.name})`
694 : `[${item.original.key}](/community/${item.original.id})`;
697 values: (text: string, cb: any) => {
698 communitySearch(text, (communities: any) => cb(communities));
701 autocompleteMode: true,
703 // menuItemLimit: mentionDropdownFetchLimit,
704 menuShowMinLength: 2,
712 tippyInstance = tippy('[data-tippy-content]');
715 export function setupTippy() {
717 tippyInstance.forEach(e => e.destroy());
718 tippyInstance = tippy('[data-tippy-content]', {
720 // Display on "long press"
721 touch: ['hold', 500],
726 function userSearch(text: string, cb: any) {
730 type_: SearchType.Users,
731 sort: SortType.TopAll,
733 limit: mentionDropdownFetchLimit,
734 auth: authField(false),
737 WebSocketService.Instance.send(wsClient.search(form));
739 let userSub = WebSocketService.Instance.subject.subscribe(
741 let res = wsJsonToRes(msg);
742 if (res.op == UserOperation.Search) {
743 let data = res.data as SearchResponse;
744 let users = data.users.map(uv => {
746 key: `@${uv.user.name}@${hostname(uv.user.actor_id)}`,
748 local: uv.user.local,
753 userSub.unsubscribe();
756 err => console.error(err),
757 () => console.log('complete')
764 function communitySearch(text: string, cb: any) {
768 type_: SearchType.Communities,
769 sort: SortType.TopAll,
771 limit: mentionDropdownFetchLimit,
772 auth: authField(false),
775 WebSocketService.Instance.send(wsClient.search(form));
777 let communitySub = WebSocketService.Instance.subject.subscribe(
779 let res = wsJsonToRes(msg);
780 if (res.op == UserOperation.Search) {
781 let data = res.data as SearchResponse;
782 let communities = data.communities.map(cv => {
784 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
785 name: cv.community.name,
786 local: cv.community.local,
791 communitySub.unsubscribe();
794 err => console.error(err),
795 () => console.log('complete')
802 export function getListingTypeFromProps(props: any): ListingType {
803 return props.match.params.listing_type
804 ? routeListingTypeToEnum(props.match.params.listing_type)
805 : UserService.Instance.user
806 ? Object.values(ListingType)[UserService.Instance.user.default_listing_type]
810 // TODO might need to add a user setting for this too
811 export function getDataTypeFromProps(props: any): DataType {
812 return props.match.params.data_type
813 ? routeDataTypeToEnum(props.match.params.data_type)
817 export function getSortTypeFromProps(props: any): SortType {
818 return props.match.params.sort
819 ? routeSortTypeToEnum(props.match.params.sort)
820 : UserService.Instance.user
821 ? Object.values(SortType)[UserService.Instance.user.default_sort_type]
825 export function getPageFromProps(props: any): number {
826 return props.match.params.page ? Number(props.match.params.page) : 1;
829 export function getRecipientIdFromProps(props: any): number {
830 return props.match.params.recipient_id
831 ? Number(props.match.params.recipient_id)
835 export function getIdFromProps(props: any): number {
836 return Number(props.match.params.id);
839 export function getCommentIdFromProps(props: any): number {
840 return Number(props.match.params.comment_id);
843 export function getUsernameFromProps(props: any): string {
844 return props.match.params.username;
847 export function editCommentRes(data: CommentView, comments: CommentView[]) {
848 let found = comments.find(c => c.comment.id == data.comment.id);
850 found.comment.content = data.comment.content;
851 found.comment.updated = data.comment.updated;
852 found.comment.removed = data.comment.removed;
853 found.comment.deleted = data.comment.deleted;
854 found.counts.upvotes = data.counts.upvotes;
855 found.counts.downvotes = data.counts.downvotes;
856 found.counts.score = data.counts.score;
860 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
861 let found = comments.find(c => c.comment.id == data.comment.id);
863 found.saved = data.saved;
867 export function createCommentLikeRes(
869 comments: CommentView[]
871 let found = comments.find(c => c.comment.id === data.comment.id);
873 found.counts.score = data.counts.score;
874 found.counts.upvotes = data.counts.upvotes;
875 found.counts.downvotes = data.counts.downvotes;
876 if (data.my_vote !== null) {
877 found.my_vote = data.my_vote;
882 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
883 let found = posts.find(p => p.post.id == data.post.id);
885 createPostLikeRes(data, found);
889 export function createPostLikeRes(data: PostView, post_view: PostView) {
891 post_view.counts.score = data.counts.score;
892 post_view.counts.upvotes = data.counts.upvotes;
893 post_view.counts.downvotes = data.counts.downvotes;
894 if (data.my_vote !== null) {
895 post_view.my_vote = data.my_vote;
900 export function editPostFindRes(data: PostView, posts: PostView[]) {
901 let found = posts.find(p => p.post.id == data.post.id);
903 editPostRes(data, found);
907 export function editPostRes(data: PostView, post: PostView) {
909 post.post.url = data.post.url;
910 post.post.name = data.post.name;
911 post.post.nsfw = data.post.nsfw;
912 post.post.deleted = data.post.deleted;
913 post.post.removed = data.post.removed;
914 post.post.stickied = data.post.stickied;
915 post.post.body = data.post.body;
916 post.post.locked = data.post.locked;
917 post.saved = data.saved;
921 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
922 let nodes: CommentNodeI[] = [];
923 for (let comment of comments) {
924 nodes.push({ comment_view: comment });
929 export function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
930 // First, put removed and deleted comments at the bottom, then do your other sorts
931 if (sort == CommentSortType.Top) {
934 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
935 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
936 b.comment_view.counts.score - a.comment_view.counts.score
938 } else if (sort == CommentSortType.New) {
941 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
942 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
943 b.comment_view.comment.published.localeCompare(
944 a.comment_view.comment.published
947 } else if (sort == CommentSortType.Old) {
950 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
951 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
952 a.comment_view.comment.published.localeCompare(
953 b.comment_view.comment.published
956 } else if (sort == CommentSortType.Hot) {
959 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
960 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
961 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
965 // Go through the children recursively
966 for (let node of tree) {
968 commentSort(node.children, sort);
973 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
974 commentSort(tree, convertCommentSortType(sort));
977 function convertCommentSortType(sort: SortType): CommentSortType {
979 sort == SortType.TopAll ||
980 sort == SortType.TopDay ||
981 sort == SortType.TopWeek ||
982 sort == SortType.TopMonth ||
983 sort == SortType.TopYear
985 return CommentSortType.Top;
986 } else if (sort == SortType.New) {
987 return CommentSortType.New;
988 } else if (sort == SortType.Hot || sort == SortType.Active) {
989 return CommentSortType.Hot;
991 return CommentSortType.Hot;
995 export function postSort(
998 communityType: boolean
1000 // First, put removed and deleted comments at the bottom, then do your other sorts
1002 sort == SortType.TopAll ||
1003 sort == SortType.TopDay ||
1004 sort == SortType.TopWeek ||
1005 sort == SortType.TopMonth ||
1006 sort == SortType.TopYear
1010 +a.post.removed - +b.post.removed ||
1011 +a.post.deleted - +b.post.deleted ||
1012 (communityType && +b.post.stickied - +a.post.stickied) ||
1013 b.counts.score - a.counts.score
1015 } else if (sort == SortType.New) {
1018 +a.post.removed - +b.post.removed ||
1019 +a.post.deleted - +b.post.deleted ||
1020 (communityType && +b.post.stickied - +a.post.stickied) ||
1021 b.post.published.localeCompare(a.post.published)
1023 } else if (sort == SortType.Hot) {
1026 +a.post.removed - +b.post.removed ||
1027 +a.post.deleted - +b.post.deleted ||
1028 (communityType && +b.post.stickied - +a.post.stickied) ||
1029 hotRankPost(b) - hotRankPost(a)
1031 } else if (sort == SortType.Active) {
1034 +a.post.removed - +b.post.removed ||
1035 +a.post.deleted - +b.post.deleted ||
1036 (communityType && +b.post.stickied - +a.post.stickied) ||
1037 hotRankActivePost(b) - hotRankActivePost(a)
1042 export const colorList: string[] = [
1051 function hsl(num: number) {
1052 return `hsla(${num}, 35%, 50%, 1)`;
1055 // function randomHsl() {
1056 // return `hsla(${Math.random() * 360}, 100%, 50%, 1)`;
1059 export function previewLines(
1061 maxChars: number = 300,
1062 maxLines: number = 1
1068 // Use lines * 2 because markdown requires 2 lines
1069 .slice(0, maxLines * 2)
1074 export function hostname(url: string): string {
1075 let cUrl = new URL(url);
1076 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1079 export function validTitle(title?: string): boolean {
1080 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1081 if (title === null || title.length < 3) return true;
1083 const regex = new RegExp(/.*\S.*/, 'g');
1085 return regex.test(title);
1088 export function siteBannerCss(banner: string): string {
1090 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1091 background-attachment: fixed; \
1092 background-position: top; \
1093 background-repeat: no-repeat; \
1094 background-size: 100% cover; \
1097 max-height: 100vh; \
1101 export function isBrowser() {
1102 return typeof window !== 'undefined';
1105 export function setIsoData(context: any): IsoData {
1106 let isoData: IsoData = isBrowser()
1108 : context.router.staticContext;
1112 export function wsSubscribe(parseMessage: any): Subscription {
1114 return WebSocketService.Instance.subject
1115 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1117 msg => parseMessage(msg),
1118 err => console.error(err),
1119 () => console.log('complete')
1126 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1132 export function authField(
1133 throwErr: boolean = true,
1134 auth = UserService.Instance.auth
1136 if (auth == null && throwErr) {
1137 toast(i18n.t('not_logged_in'), 'danger');
1138 throw 'Not logged in';
1144 moment.updateLocale('en', {