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';
30 import 'moment/locale/hr';
40 WebSocketJsonResponse,
48 } from 'lemmy-js-client';
54 CommentNode as CommentNodeI,
55 } from './interfaces';
56 import { UserService, WebSocketService } from './services';
60 Tribute = require('tributejs');
62 import markdown_it from 'markdown-it';
63 import markdown_it_sub from 'markdown-it-sub';
64 import markdown_it_sup from 'markdown-it-sup';
65 import markdownitEmoji from 'markdown-it-emoji/light';
66 import markdown_it_container from 'markdown-it-container';
67 import emojiShortName from 'emoji-short-name';
68 import Toastify from 'toastify-js';
69 import tippy from 'tippy.js';
70 import moment from 'moment';
71 import { Subscription } from 'rxjs';
72 import { retryWhen, delay, take } from 'rxjs/operators';
73 import { i18n } from './i18next';
75 export const wsClient = new LemmyWebsocket();
77 export const favIconUrl = '/static/assets/favicon.svg';
78 export const favIconPngUrl = '/static/assets/apple-touch-icon.png';
80 // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
81 export const repoUrl = 'https://github.com/LemmyNet';
82 export const joinLemmyUrl = 'https://join.lemmy.ml';
83 export const supportLemmyUrl = 'https://join.lemmy.ml/sponsors';
84 export const docsUrl = 'https://join.lemmy.ml/docs/en/index.html';
85 export const helpGuideUrl = 'https://join.lemmy.ml/docs/en/about/guide.html'; // TODO find a way to redirect to the non-en folder
86 export const markdownHelpUrl = `${helpGuideUrl}#markdown-guide`;
87 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
88 export const archiveUrl = 'https://archive.is';
89 export const elementUrl = 'https://element.io/';
91 export const postRefetchSeconds: number = 60 * 1000;
92 export const fetchLimit: number = 20;
93 export const mentionDropdownFetchLimit = 10;
95 export const languages = [
96 { code: 'ca', name: 'Català' },
97 { code: 'en', name: 'English' },
98 { code: 'el', name: 'Ελληνικά' },
99 { code: 'eu', name: 'Euskara' },
100 { code: 'eo', name: 'Esperanto' },
101 { code: 'es', name: 'Español' },
102 { code: 'da', name: 'Dansk' },
103 { code: 'de', name: 'Deutsch' },
104 { code: 'ga', name: 'Gaeilge' },
105 { code: 'gl', name: 'Galego' },
106 { code: 'hr', name: 'hrvatski' },
107 { code: 'hu', name: 'Magyar Nyelv' },
108 { code: 'ka', name: 'ქართული ენა' },
109 { code: 'ko', name: '한국어' },
110 { code: 'km', name: 'ភាសាខ្មែរ' },
111 { code: 'hi', name: 'मानक हिन्दी' },
112 { code: 'fa', name: 'فارسی' },
113 { code: 'ja', name: '日本語' },
114 { code: 'oc', name: 'Occitan' },
115 { code: 'pl', name: 'Polski' },
116 { code: 'pt_BR', name: 'Português Brasileiro' },
117 { code: 'zh', name: '中文' },
118 { code: 'fi', name: 'Suomi' },
119 { code: 'fr', name: 'Français' },
120 { code: 'sv', name: 'Svenska' },
121 { code: 'sq', name: 'Shqip' },
122 { code: 'sr_Latn', name: 'srpski' },
123 { code: 'tr', name: 'Türkçe' },
124 { code: 'uk', name: 'Українська Mова' },
125 { code: 'ru', name: 'Русский' },
126 { code: 'nl', name: 'Nederlands' },
127 { code: 'it', name: 'Italiano' },
130 export const themes = [
146 const DEFAULT_ALPHABET =
147 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
149 function getRandomCharFromAlphabet(alphabet: string): string {
150 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
153 export function randomStr(
154 idDesiredLength: number = 20,
155 alphabet = DEFAULT_ALPHABET
158 * Create n-long array and map it to random chars from given alphabet.
159 * Then join individual chars as string
161 return Array.from({ length: idDesiredLength })
163 return getRandomCharFromAlphabet(alphabet);
168 export function wsJsonToRes<ResponseType>(
169 msg: WebSocketJsonResponse<ResponseType>
170 ): WebSocketResponse<ResponseType> {
177 export function wsUserOp(msg: any): UserOperation {
178 let opStr: string = msg.op;
179 return UserOperation[opStr];
182 export const md = new markdown_it({
187 .use(markdown_it_sub)
188 .use(markdown_it_sup)
189 .use(markdown_it_container, 'spoiler', {
190 validate: function (params: any) {
191 return params.trim().match(/^spoiler\s+(.*)$/);
194 render: function (tokens: any, idx: any) {
195 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
197 if (tokens[idx].nesting === 1) {
199 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
202 return '</details>\n';
206 .use(markdownitEmoji, {
207 defs: objectFlip(emojiShortName),
210 export function hotRankComment(comment_view: CommentView): number {
211 return hotRank(comment_view.counts.score, comment_view.comment.published);
214 export function hotRankActivePost(post_view: PostView): number {
215 return hotRank(post_view.counts.score, post_view.counts.newest_comment_time);
218 export function hotRankPost(post_view: PostView): number {
219 return hotRank(post_view.counts.score, post_view.post.published);
222 export function hotRank(score: number, timeStr: string): number {
223 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
224 let date: Date = new Date(timeStr + 'Z'); // Add Z to convert from UTC date
225 let now: Date = new Date();
226 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
229 (10000 * Math.log10(Math.max(1, 3 + score))) /
230 Math.pow(hoursElapsed + 2, 1.8);
232 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
237 export function mdToHtml(text: string) {
238 return { __html: md.render(text) };
241 export function getUnixTime(text: string): number {
242 return text ? new Date(text).getTime() / 1000 : undefined;
245 export function canMod(
246 user: UserSafeSettings,
249 onSelf: boolean = false
251 // You can do moderator actions only on the mods added after you.
253 let yourIndex = modIds.findIndex(id => id == user.id);
254 if (yourIndex == -1) {
257 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
258 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
259 return !modIds.includes(creator_id);
266 export function isMod(modIds: number[], creator_id: number): boolean {
267 return modIds.includes(creator_id);
270 const imageRegex = new RegExp(
271 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
273 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
275 export function isImage(url: string) {
276 return imageRegex.test(url);
279 export function isVideo(url: string) {
280 return videoRegex.test(url);
283 export function validURL(str: string) {
284 return !!new URL(str);
287 export function communityRSSUrl(actorId: string, sort: string): string {
288 let url = new URL(actorId);
289 return `${url.origin}/feeds${url.pathname}.xml?sort=${sort}`;
292 export function validEmail(email: string) {
293 let re = /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
294 return re.test(String(email).toLowerCase());
297 export function capitalizeFirstLetter(str: string): string {
298 return str.charAt(0).toUpperCase() + str.slice(1);
301 export function routeSortTypeToEnum(sort: string): SortType {
302 return SortType[sort];
305 export function listingTypeFromNum(type_: number): ListingType {
306 return Object.values(ListingType)[type_];
309 export function sortTypeFromNum(type_: number): SortType {
310 return Object.values(SortType)[type_];
313 export function routeListingTypeToEnum(type: string): ListingType {
314 return ListingType[type];
317 export function routeDataTypeToEnum(type: string): DataType {
318 return DataType[capitalizeFirstLetter(type)];
321 export function routeSearchTypeToEnum(type: string): SearchType {
322 return SearchType[type];
325 export async function getPageTitle(url: string) {
326 let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
327 let title = await res.title;
331 export function debounce(
334 immediate: boolean = false
336 // 'private' variable for instance
337 // The returned function will be able to reference this due to closure.
338 // Each call to the returned function will share this common timer.
341 // Calling debounce returns a new anonymous function
343 // reference the context and args for the setTimeout function
347 // Should the function be called now? If immediate is true
348 // and not already in a timeout then the answer is: Yes
349 var callNow = immediate && !timeout;
351 // This is the basic debounce behaviour where you can call this
352 // function several times, but it will only execute once
353 // [before or after imposing a delay].
354 // Each time the returned function is called, the timer starts over.
355 clearTimeout(timeout);
357 // Set the new timeout
358 timeout = setTimeout(function () {
359 // Inside the timeout function, clear the timeout variable
360 // which will let the next execution run when in 'immediate' mode
363 // Check if the function already ran with the immediate flag
365 // Call the original function with apply
366 // apply lets you define the 'this' object as well as the arguments
367 // (both captured before setTimeout)
368 func.apply(context, args);
372 // Immediate mode and no wait timer? Execute the function..
373 if (callNow) func.apply(context, args);
378 export function getLanguage(override?: string): string {
379 let user = UserService.Instance.user;
380 let lang = override || (user && user.lang ? user.lang : 'browser');
382 if (lang == 'browser' && isBrowser()) {
383 return getBrowserLanguage();
390 export function getBrowserLanguage(): string {
391 return navigator.language;
394 export function getMomentLanguage(): string {
395 let lang = getLanguage();
396 if (lang.startsWith('zh')) {
398 } else if (lang.startsWith('sv')) {
400 } else if (lang.startsWith('fr')) {
402 } else if (lang.startsWith('de')) {
404 } else if (lang.startsWith('ru')) {
406 } else if (lang.startsWith('es')) {
408 } else if (lang.startsWith('eo')) {
410 } else if (lang.startsWith('nl')) {
412 } else if (lang.startsWith('it')) {
414 } else if (lang.startsWith('fi')) {
416 } else if (lang.startsWith('ca')) {
418 } else if (lang.startsWith('fa')) {
420 } else if (lang.startsWith('pl')) {
422 } else if (lang.startsWith('pt')) {
424 } else if (lang.startsWith('ja')) {
426 } else if (lang.startsWith('ka')) {
428 } else if (lang.startsWith('hi')) {
430 } else if (lang.startsWith('el')) {
432 } else if (lang.startsWith('eu')) {
434 } else if (lang.startsWith('gl')) {
436 } else if (lang.startsWith('tr')) {
438 } else if (lang.startsWith('hu')) {
440 } else if (lang.startsWith('uk')) {
442 } else if (lang.startsWith('sq')) {
444 } else if (lang.startsWith('km')) {
446 } else if (lang.startsWith('ga')) {
448 } else if (lang.startsWith('sr')) {
450 } else if (lang.startsWith('ko')) {
452 } else if (lang.startsWith('da')) {
454 } else if (lang.startsWith('oc')) {
456 } else if (lang.startsWith('hr')) {
464 export function setTheme(theme: string, forceReload: boolean = false) {
468 if (theme === 'browser' && !forceReload) {
471 // This is only run on a force reload
472 if (theme == 'browser') {
476 // Unload all the other themes
477 for (var i = 0; i < themes.length; i++) {
478 let styleSheet = document.getElementById(themes[i]);
480 styleSheet.setAttribute('disabled', 'disabled');
485 .getElementById('default-light')
486 ?.setAttribute('disabled', 'disabled');
487 document.getElementById('default-dark')?.setAttribute('disabled', 'disabled');
489 // Load the theme dynamically
490 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
491 loadCss(theme, cssLoc);
492 document.getElementById(theme).removeAttribute('disabled');
495 export function loadCss(id: string, loc: string) {
496 if (!document.getElementById(id)) {
497 var head = document.getElementsByTagName('head')[0];
498 var link = document.createElement('link');
500 link.rel = 'stylesheet';
501 link.type = 'text/css';
504 head.appendChild(link);
508 export function objectFlip(obj: any) {
510 Object.keys(obj).forEach(key => {
516 export function showAvatars(): boolean {
518 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
519 !UserService.Instance.user
523 export function isCakeDay(published: string): boolean {
524 // moment(undefined) or moment.utc(undefined) returns the current date/time
525 // moment(null) or moment.utc(null) returns null
526 const userCreationDate = moment.utc(published || null).local();
527 const currentDate = moment(new Date());
530 userCreationDate.date() === currentDate.date() &&
531 userCreationDate.month() === currentDate.month() &&
532 userCreationDate.year() !== currentDate.year()
536 export function toast(text: string, background: string = 'success') {
538 let backgroundColor = `var(--${background})`;
541 backgroundColor: backgroundColor,
548 export function pictrsDeleteToast(
549 clickToDeleteText: string,
550 deletePictureText: string,
554 let backgroundColor = `var(--light)`;
555 let toast = Toastify({
556 text: clickToDeleteText,
557 backgroundColor: backgroundColor,
563 window.location.replace(deleteUrl);
564 alert(deletePictureText);
573 interface NotifyInfo {
580 export function messageToastify(info: NotifyInfo, router: any) {
582 let htmlBody = info.body ? md.render(info.body) : '';
583 let backgroundColor = `var(--light)`;
585 let toast = Toastify({
586 text: `${htmlBody}<br />${info.name}`,
587 avatar: info.icon ? info.icon : null,
588 backgroundColor: backgroundColor,
589 className: 'text-dark',
597 router.history.push(info.link);
604 export function notifyPost(post_view: PostView, router: any) {
605 let info: NotifyInfo = {
606 name: post_view.community.name,
607 icon: post_view.community.icon,
608 link: `/post/${post_view.post.id}`,
609 body: post_view.post.name,
611 notify(info, router);
614 export function notifyComment(comment_view: CommentView, router: any) {
615 let info: NotifyInfo = {
616 name: comment_view.creator.name,
617 icon: comment_view.creator.avatar,
618 link: `/post/${comment_view.post.id}/comment/${comment_view.comment.id}`,
619 body: comment_view.comment.content,
621 notify(info, router);
624 export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
625 let info: NotifyInfo = {
626 name: pmv.creator.name,
627 icon: pmv.creator.avatar,
629 body: pmv.private_message.content,
631 notify(info, router);
634 function notify(info: NotifyInfo, router: any) {
635 messageToastify(info, router);
637 if (Notification.permission !== 'granted') Notification.requestPermission();
639 var notification = new Notification(info.name, {
644 notification.onclick = (ev: Event): any => {
646 router.history.push(info.link);
651 export function setupTribute() {
653 noMatchTemplate: function () {
660 menuItemTemplate: (item: any) => {
661 let shortName = `:${item.original.key}:`;
662 return `${item.original.val} ${shortName}`;
664 selectTemplate: (item: any) => {
665 return `:${item.original.key}:`;
667 values: Object.entries(emojiShortName).map(e => {
668 return { key: e[1], val: e[0] };
671 autocompleteMode: true,
673 // menuItemLimit: mentionDropdownFetchLimit,
674 menuShowMinLength: 2,
679 selectTemplate: (item: any) => {
680 let it: UserTribute = item.original;
681 return `[${it.key}](${it.view.user.actor_id})`;
683 values: (text: string, cb: (users: UserTribute[]) => any) => {
684 userSearch(text, (users: UserTribute[]) => cb(users));
687 autocompleteMode: true,
689 // menuItemLimit: mentionDropdownFetchLimit,
690 menuShowMinLength: 2,
696 selectTemplate: (item: any) => {
697 let it: CommunityTribute = item.original;
698 return `[${it.key}](${it.view.community.actor_id})`;
700 values: (text: string, cb: any) => {
701 communitySearch(text, (communities: CommunityTribute[]) =>
706 autocompleteMode: true,
708 // menuItemLimit: mentionDropdownFetchLimit,
709 menuShowMinLength: 2,
715 var tippyInstance: any;
717 tippyInstance = tippy('[data-tippy-content]');
720 export function setupTippy() {
722 tippyInstance.forEach((e: any) => e.destroy());
723 tippyInstance = tippy('[data-tippy-content]', {
725 // Display on "long press"
726 touch: ['hold', 500],
731 interface UserTribute {
736 function userSearch(text: string, cb: (users: UserTribute[]) => any) {
740 type_: SearchType.Users,
741 sort: SortType.TopAll,
743 limit: mentionDropdownFetchLimit,
744 auth: authField(false),
747 WebSocketService.Instance.send(wsClient.search(form));
749 let userSub = WebSocketService.Instance.subject.subscribe(
751 let res = wsJsonToRes(msg);
752 if (res.op == UserOperation.Search) {
753 let data = res.data as SearchResponse;
754 let users: UserTribute[] = data.users.map(uv => {
755 let tribute: UserTribute = {
756 key: `@${uv.user.name}@${hostname(uv.user.actor_id)}`,
762 userSub.unsubscribe();
765 err => console.error(err),
766 () => console.log('complete')
773 interface CommunityTribute {
778 function communitySearch(
780 cb: (communities: CommunityTribute[]) => any
785 type_: SearchType.Communities,
786 sort: SortType.TopAll,
788 limit: mentionDropdownFetchLimit,
789 auth: authField(false),
792 WebSocketService.Instance.send(wsClient.search(form));
794 let communitySub = WebSocketService.Instance.subject.subscribe(
796 let res = wsJsonToRes(msg);
797 if (res.op == UserOperation.Search) {
798 let data = res.data as SearchResponse;
799 let communities: CommunityTribute[] = data.communities.map(cv => {
800 let tribute: CommunityTribute = {
801 key: `!${cv.community.name}@${hostname(cv.community.actor_id)}`,
807 communitySub.unsubscribe();
810 err => console.error(err),
811 () => console.log('complete')
818 export function getListingTypeFromProps(props: any): ListingType {
819 return props.match.params.listing_type
820 ? routeListingTypeToEnum(props.match.params.listing_type)
821 : UserService.Instance.user
822 ? Object.values(ListingType)[UserService.Instance.user.default_listing_type]
826 // TODO might need to add a user setting for this too
827 export function getDataTypeFromProps(props: any): DataType {
828 return props.match.params.data_type
829 ? routeDataTypeToEnum(props.match.params.data_type)
833 export function getSortTypeFromProps(props: any): SortType {
834 return props.match.params.sort
835 ? routeSortTypeToEnum(props.match.params.sort)
836 : UserService.Instance.user
837 ? Object.values(SortType)[UserService.Instance.user.default_sort_type]
841 export function getPageFromProps(props: any): number {
842 return props.match.params.page ? Number(props.match.params.page) : 1;
845 export function getRecipientIdFromProps(props: any): number {
846 return props.match.params.recipient_id
847 ? Number(props.match.params.recipient_id)
851 export function getIdFromProps(props: any): number {
852 return Number(props.match.params.id);
855 export function getCommentIdFromProps(props: any): number {
856 return Number(props.match.params.comment_id);
859 export function getUsernameFromProps(props: any): string {
860 return props.match.params.username;
863 export function editCommentRes(data: CommentView, comments: CommentView[]) {
864 let found = comments.find(c => c.comment.id == data.comment.id);
866 found.comment.content = data.comment.content;
867 found.comment.updated = data.comment.updated;
868 found.comment.removed = data.comment.removed;
869 found.comment.deleted = data.comment.deleted;
870 found.counts.upvotes = data.counts.upvotes;
871 found.counts.downvotes = data.counts.downvotes;
872 found.counts.score = data.counts.score;
876 export function saveCommentRes(data: CommentView, comments: CommentView[]) {
877 let found = comments.find(c => c.comment.id == data.comment.id);
879 found.saved = data.saved;
883 export function createCommentLikeRes(
885 comments: CommentView[]
887 let found = comments.find(c => c.comment.id === data.comment.id);
889 found.counts.score = data.counts.score;
890 found.counts.upvotes = data.counts.upvotes;
891 found.counts.downvotes = data.counts.downvotes;
892 if (data.my_vote !== null) {
893 found.my_vote = data.my_vote;
898 export function createPostLikeFindRes(data: PostView, posts: PostView[]) {
899 let found = posts.find(p => p.post.id == data.post.id);
901 createPostLikeRes(data, found);
905 export function createPostLikeRes(data: PostView, post_view: PostView) {
907 post_view.counts.score = data.counts.score;
908 post_view.counts.upvotes = data.counts.upvotes;
909 post_view.counts.downvotes = data.counts.downvotes;
910 if (data.my_vote !== null) {
911 post_view.my_vote = data.my_vote;
916 export function editPostFindRes(data: PostView, posts: PostView[]) {
917 let found = posts.find(p => p.post.id == data.post.id);
919 editPostRes(data, found);
923 export function editPostRes(data: PostView, post: PostView) {
925 post.post.url = data.post.url;
926 post.post.name = data.post.name;
927 post.post.nsfw = data.post.nsfw;
928 post.post.deleted = data.post.deleted;
929 post.post.removed = data.post.removed;
930 post.post.stickied = data.post.stickied;
931 post.post.body = data.post.body;
932 post.post.locked = data.post.locked;
933 post.saved = data.saved;
937 export function commentsToFlatNodes(comments: CommentView[]): CommentNodeI[] {
938 let nodes: CommentNodeI[] = [];
939 for (let comment of comments) {
940 nodes.push({ comment_view: comment });
945 export function commentSort(tree: CommentNodeI[], sort: CommentSortType) {
946 // First, put removed and deleted comments at the bottom, then do your other sorts
947 if (sort == CommentSortType.Top) {
950 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
951 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
952 b.comment_view.counts.score - a.comment_view.counts.score
954 } else if (sort == CommentSortType.New) {
957 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
958 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
959 b.comment_view.comment.published.localeCompare(
960 a.comment_view.comment.published
963 } else if (sort == CommentSortType.Old) {
966 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
967 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
968 a.comment_view.comment.published.localeCompare(
969 b.comment_view.comment.published
972 } else if (sort == CommentSortType.Hot) {
975 +a.comment_view.comment.removed - +b.comment_view.comment.removed ||
976 +a.comment_view.comment.deleted - +b.comment_view.comment.deleted ||
977 hotRankComment(b.comment_view) - hotRankComment(a.comment_view)
981 // Go through the children recursively
982 for (let node of tree) {
984 commentSort(node.children, sort);
989 export function commentSortSortType(tree: CommentNodeI[], sort: SortType) {
990 commentSort(tree, convertCommentSortType(sort));
993 function convertCommentSortType(sort: SortType): CommentSortType {
995 sort == SortType.TopAll ||
996 sort == SortType.TopDay ||
997 sort == SortType.TopWeek ||
998 sort == SortType.TopMonth ||
999 sort == SortType.TopYear
1001 return CommentSortType.Top;
1002 } else if (sort == SortType.New) {
1003 return CommentSortType.New;
1004 } else if (sort == SortType.Hot || sort == SortType.Active) {
1005 return CommentSortType.Hot;
1007 return CommentSortType.Hot;
1011 export function postSort(
1014 communityType: boolean
1016 // First, put removed and deleted comments at the bottom, then do your other sorts
1018 sort == SortType.TopAll ||
1019 sort == SortType.TopDay ||
1020 sort == SortType.TopWeek ||
1021 sort == SortType.TopMonth ||
1022 sort == SortType.TopYear
1026 +a.post.removed - +b.post.removed ||
1027 +a.post.deleted - +b.post.deleted ||
1028 (communityType && +b.post.stickied - +a.post.stickied) ||
1029 b.counts.score - a.counts.score
1031 } else if (sort == SortType.New) {
1034 +a.post.removed - +b.post.removed ||
1035 +a.post.deleted - +b.post.deleted ||
1036 (communityType && +b.post.stickied - +a.post.stickied) ||
1037 b.post.published.localeCompare(a.post.published)
1039 } else if (sort == SortType.Hot) {
1042 +a.post.removed - +b.post.removed ||
1043 +a.post.deleted - +b.post.deleted ||
1044 (communityType && +b.post.stickied - +a.post.stickied) ||
1045 hotRankPost(b) - hotRankPost(a)
1047 } else if (sort == SortType.Active) {
1050 +a.post.removed - +b.post.removed ||
1051 +a.post.deleted - +b.post.deleted ||
1052 (communityType && +b.post.stickied - +a.post.stickied) ||
1053 hotRankActivePost(b) - hotRankActivePost(a)
1058 export const colorList: string[] = [
1067 function hsl(num: number) {
1068 return `hsla(${num}, 35%, 50%, 1)`;
1071 // function randomHsl() {
1072 // return `hsla(${Math.random() * 360}, 100%, 50%, 1)`;
1075 export function previewLines(
1077 maxChars: number = 300,
1078 maxLines: number = 1
1084 // Use lines * 2 because markdown requires 2 lines
1085 .slice(0, maxLines * 2)
1090 export function hostname(url: string): string {
1091 let cUrl = new URL(url);
1092 return cUrl.port ? `${cUrl.hostname}:${cUrl.port}` : `${cUrl.hostname}`;
1095 export function validTitle(title?: string): boolean {
1096 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1097 if (title === null || title.length < 3) return true;
1099 const regex = new RegExp(/.*\S.*/, 'g');
1101 return regex.test(title);
1104 export function siteBannerCss(banner: string): string {
1106 background-image: linear-gradient( rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8) ) ,url("${banner}"); \
1107 background-attachment: fixed; \
1108 background-position: top; \
1109 background-repeat: no-repeat; \
1110 background-size: 100% cover; \
1113 max-height: 100vh; \
1117 export function isBrowser() {
1118 return typeof window !== 'undefined';
1121 export function setIsoData(context: any): IsoData {
1122 let isoData: IsoData = isBrowser()
1124 : context.router.staticContext;
1128 export function wsSubscribe(parseMessage: any): Subscription {
1130 return WebSocketService.Instance.subject
1131 .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
1133 msg => parseMessage(msg),
1134 err => console.error(err),
1135 () => console.log('complete')
1142 export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
1148 export function authField(
1149 throwErr: boolean = true,
1150 auth = UserService.Instance.auth
1152 if (auth == null && throwErr) {
1153 toast(i18n.t('not_logged_in'), 'danger');
1154 throw 'Not logged in';
1160 moment.updateLocale('en', {
1181 export function saveScrollPosition(context: any) {
1182 let path: string = context.router.route.location.pathname;
1183 let y = window.scrollY;
1184 sessionStorage.setItem(`scrollPosition_${path}`, y.toString());
1187 export function restoreScrollPosition(context: any) {
1188 let path: string = context.router.route.location.pathname;
1189 let y = Number(sessionStorage.getItem(`scrollPosition_${path}`));
1190 window.scrollTo(0, y);