1 import 'moment/locale/es';
2 import 'moment/locale/eo';
3 import 'moment/locale/de';
4 import 'moment/locale/zh-cn';
5 import 'moment/locale/fr';
6 import 'moment/locale/sv';
7 import 'moment/locale/ru';
8 import 'moment/locale/nl';
9 import 'moment/locale/it';
10 import 'moment/locale/fi';
11 import 'moment/locale/ca';
12 import 'moment/locale/fa';
13 import 'moment/locale/pt-br';
14 import 'moment/locale/ja';
19 CommentNode as CommentNodeI,
29 WebSocketJsonResponse,
34 } from './interfaces';
35 import { UserService, WebSocketService } from './services';
37 import Tribute from 'tributejs/src/Tribute.js';
38 import markdown_it from 'markdown-it';
39 import markdownitEmoji from 'markdown-it-emoji/light';
40 import markdown_it_container from 'markdown-it-container';
41 import twemoji from 'twemoji';
42 import emojiShortName from 'emoji-short-name';
43 import Toastify from 'toastify-js';
44 import tippy from 'tippy.js';
46 export const repoUrl = 'https://github.com/dessalines/lemmy';
47 export const helpGuideUrl = '/docs/about_guide.html';
48 export const markdownHelpUrl = `${helpGuideUrl}#markdown-guide`;
49 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
50 export const archiveUrl = 'https://archive.is';
52 export const postRefetchSeconds: number = 60 * 1000;
53 export const fetchLimit: number = 20;
54 export const mentionDropdownFetchLimit = 10;
56 export const languages = [
57 { code: 'ca', name: 'Català' },
58 { code: 'en', name: 'English' },
59 { code: 'eo', name: 'Esperanto' },
60 { code: 'es', name: 'Español' },
61 { code: 'de', name: 'Deutsch' },
62 { code: 'fa', name: 'فارسی' },
63 { code: 'ja', name: '日本語' },
64 { code: 'pt_BR', name: 'Português Brasileiro' },
65 { code: 'zh', name: '中文' },
66 { code: 'fi', name: 'Suomi' },
67 { code: 'fr', name: 'Français' },
68 { code: 'sv', name: 'Svenska' },
69 { code: 'ru', name: 'Русский' },
70 { code: 'nl', name: 'Nederlands' },
71 { code: 'it', name: 'Italiano' },
74 export const themes = [
89 export function randomStr() {
92 .replace(/[^a-z]+/g, '')
96 export function wsJsonToRes(msg: WebSocketJsonResponse): WebSocketResponse {
97 let opStr: string = msg.op;
99 op: UserOperation[opStr],
104 export const md = new markdown_it({
109 .use(markdown_it_container, 'spoiler', {
110 validate: function(params: any) {
111 return params.trim().match(/^spoiler\s+(.*)$/);
114 render: function(tokens: any, idx: any) {
115 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
117 if (tokens[idx].nesting === 1) {
119 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
122 return '</details>\n';
126 .use(markdownitEmoji, {
127 defs: objectFlip(emojiShortName),
130 md.renderer.rules.emoji = function(token, idx) {
131 return twemoji.parse(token[idx].content);
134 export function hotRankComment(comment: Comment): number {
135 return hotRank(comment.score, comment.published);
138 export function hotRankPost(post: Post): number {
139 return hotRank(post.score, post.newest_activity_time);
142 export function hotRank(score: number, timeStr: string): number {
143 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
144 let date: Date = new Date(timeStr + 'Z'); // Add Z to convert from UTC date
145 let now: Date = new Date();
146 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
149 (10000 * Math.log10(Math.max(1, 3 + score))) /
150 Math.pow(hoursElapsed + 2, 1.8);
152 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
157 export function mdToHtml(text: string) {
158 return { __html: md.render(text) };
161 export function getUnixTime(text: string): number {
162 return text ? new Date(text).getTime() / 1000 : undefined;
165 export function addTypeInfo<T>(
168 ): Array<{ type_: string; data: T }> {
169 return arr.map(e => {
170 return { type_: name, data: e };
174 export function canMod(
176 modIds: Array<number>,
178 onSelf: boolean = false
180 // You can do moderator actions only on the mods added after you.
182 let yourIndex = modIds.findIndex(id => id == user.id);
183 if (yourIndex == -1) {
186 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
187 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
188 return !modIds.includes(creator_id);
195 export function isMod(modIds: Array<number>, creator_id: number): boolean {
196 return modIds.includes(creator_id);
199 const imageRegex = new RegExp(
200 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg))/
202 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
204 export function isImage(url: string) {
205 return imageRegex.test(url);
208 export function isVideo(url: string) {
209 return videoRegex.test(url);
212 export function validURL(str: string) {
214 return !!new URL(str);
220 export function validEmail(email: string) {
221 let re = /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
222 return re.test(String(email).toLowerCase());
225 export function capitalizeFirstLetter(str: string): string {
226 return str.charAt(0).toUpperCase() + str.slice(1);
229 export function routeSortTypeToEnum(sort: string): SortType {
232 } else if (sort == 'hot') {
234 } else if (sort == 'topday') {
235 return SortType.TopDay;
236 } else if (sort == 'topweek') {
237 return SortType.TopWeek;
238 } else if (sort == 'topmonth') {
239 return SortType.TopMonth;
240 } else if (sort == 'topyear') {
241 return SortType.TopYear;
242 } else if (sort == 'topall') {
243 return SortType.TopAll;
247 export function routeListingTypeToEnum(type: string): ListingType {
248 return ListingType[capitalizeFirstLetter(type)];
251 export function routeDataTypeToEnum(type: string): DataType {
252 return DataType[capitalizeFirstLetter(type)];
255 export function routeSearchTypeToEnum(type: string): SearchType {
256 return SearchType[capitalizeFirstLetter(type)];
259 export async function getPageTitle(url: string) {
260 let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
261 let title = await res.title;
265 export function debounce(
268 immediate: boolean = false
270 // 'private' variable for instance
271 // The returned function will be able to reference this due to closure.
272 // Each call to the returned function will share this common timer.
275 // Calling debounce returns a new anonymous function
277 // reference the context and args for the setTimeout function
281 // Should the function be called now? If immediate is true
282 // and not already in a timeout then the answer is: Yes
283 var callNow = immediate && !timeout;
285 // This is the basic debounce behaviour where you can call this
286 // function several times, but it will only execute once
287 // [before or after imposing a delay].
288 // Each time the returned function is called, the timer starts over.
289 clearTimeout(timeout);
291 // Set the new timeout
292 timeout = setTimeout(function() {
293 // Inside the timeout function, clear the timeout variable
294 // which will let the next execution run when in 'immediate' mode
297 // Check if the function already ran with the immediate flag
299 // Call the original function with apply
300 // apply lets you define the 'this' object as well as the arguments
301 // (both captured before setTimeout)
302 func.apply(context, args);
306 // Immediate mode and no wait timer? Execute the function..
307 if (callNow) func.apply(context, args);
311 export function getLanguage(): string {
312 let user = UserService.Instance.user;
313 let lang = user && user.lang ? user.lang : 'browser';
315 if (lang == 'browser') {
316 return getBrowserLanguage();
322 export function getBrowserLanguage(): string {
323 return navigator.language;
326 export function getMomentLanguage(): string {
327 let lang = getLanguage();
328 if (lang.startsWith('zh')) {
330 } else if (lang.startsWith('sv')) {
332 } else if (lang.startsWith('fr')) {
334 } else if (lang.startsWith('de')) {
336 } else if (lang.startsWith('ru')) {
338 } else if (lang.startsWith('es')) {
340 } else if (lang.startsWith('eo')) {
342 } else if (lang.startsWith('nl')) {
344 } else if (lang.startsWith('it')) {
346 } else if (lang.startsWith('fi')) {
348 } else if (lang.startsWith('ca')) {
350 } else if (lang.startsWith('fa')) {
352 } else if (lang.startsWith('pt')) {
354 } else if (lang.startsWith('ja')) {
362 export function setTheme(theme: string = 'darkly') {
363 // unload all the other themes
364 for (var i = 0; i < themes.length; i++) {
365 let styleSheet = document.getElementById(themes[i]);
367 styleSheet.setAttribute('disabled', 'disabled');
371 // Load the theme dynamically
372 if (!document.getElementById(theme)) {
373 var head = document.getElementsByTagName('head')[0];
374 var link = document.createElement('link');
376 link.rel = 'stylesheet';
377 link.type = 'text/css';
378 link.href = `/static/assets/css/themes/${theme}.min.css`;
380 head.appendChild(link);
382 document.getElementById(theme).removeAttribute('disabled');
385 export function objectFlip(obj: any) {
387 Object.keys(obj).forEach(key => {
393 export function pictshareAvatarThumbnail(src: string): string {
394 // sample url: http://localhost:8535/pictshare/gs7xuu.jpg
395 let split = src.split('pictshare');
396 let out = `${split[0]}pictshare/96${split[1]}`;
400 export function showAvatars(): boolean {
402 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
403 !UserService.Instance.user
407 // Converts to image thumbnail
408 export function pictshareImage(
410 thumbnail: boolean = false
412 let root = `/pictshare`;
414 // Necessary for other servers / domains
415 if (hash.includes('pictshare')) {
416 let split = hash.split('/pictshare/');
417 root = `${split[0]}/pictshare`;
421 let out = `${root}/${thumbnail ? '192/' : ''}${hash}`;
425 export function isCommentType(item: Comment | PrivateMessage): item is Comment {
426 return (item as Comment).community_id !== undefined;
429 export function toast(text: string, background: string = 'success') {
430 let backgroundColor = `var(--${background})`;
433 backgroundColor: backgroundColor,
439 export function messageToastify(
446 let backgroundColor = `var(--light)`;
448 text: `${body}<br />${creator}`,
450 backgroundColor: backgroundColor,
456 router.history.push(link);
461 export function setupTribute(): Tribute {
467 menuItemTemplate: (item: any) => {
468 let emoji = `:${item.original.key}:`;
469 return `${item.original.val} ${emoji}`;
471 selectTemplate: (item: any) => {
472 return `:${item.original.key}:`;
474 values: Object.entries(emojiShortName).map(e => {
475 return { key: e[1], val: e[0] };
478 autocompleteMode: true,
479 menuItemLimit: mentionDropdownFetchLimit,
480 menuShowMinLength: 2,
485 selectTemplate: (item: any) => {
486 return `[/u/${item.original.key}](/u/${item.original.key})`;
488 values: (text: string, cb: any) => {
489 userSearch(text, (users: any) => cb(users));
492 autocompleteMode: true,
493 menuItemLimit: mentionDropdownFetchLimit,
494 menuShowMinLength: 2,
500 selectTemplate: (item: any) => {
501 return `[/c/${item.original.key}](/c/${item.original.key})`;
503 values: (text: string, cb: any) => {
504 communitySearch(text, (communities: any) => cb(communities));
507 autocompleteMode: true,
508 menuItemLimit: mentionDropdownFetchLimit,
509 menuShowMinLength: 2,
515 let tippyInstance = tippy('[data-tippy-content]');
517 export function setupTippy() {
518 tippyInstance.forEach(e => e.destroy());
519 tippyInstance = tippy('[data-tippy-content]', {
521 // Display on "long press"
522 touch: ['hold', 500],
526 function userSearch(text: string, cb: any) {
528 let form: SearchForm = {
530 type_: SearchType[SearchType.Users],
531 sort: SortType[SortType.TopAll],
533 limit: mentionDropdownFetchLimit,
536 WebSocketService.Instance.search(form);
538 this.userSub = WebSocketService.Instance.subject.subscribe(
540 let res = wsJsonToRes(msg);
541 if (res.op == UserOperation.Search) {
542 let data = res.data as SearchResponse;
543 let users = data.users.map(u => {
544 return { key: u.name };
547 this.userSub.unsubscribe();
550 err => console.error(err),
551 () => console.log('complete')
558 function communitySearch(text: string, cb: any) {
560 let form: SearchForm = {
562 type_: SearchType[SearchType.Communities],
563 sort: SortType[SortType.TopAll],
565 limit: mentionDropdownFetchLimit,
568 WebSocketService.Instance.search(form);
570 this.communitySub = WebSocketService.Instance.subject.subscribe(
572 let res = wsJsonToRes(msg);
573 if (res.op == UserOperation.Search) {
574 let data = res.data as SearchResponse;
575 let communities = data.communities.map(u => {
576 return { key: u.name };
579 this.communitySub.unsubscribe();
582 err => console.error(err),
583 () => console.log('complete')
590 export function getListingTypeFromProps(props: any): ListingType {
591 return props.match.params.listing_type
592 ? routeListingTypeToEnum(props.match.params.listing_type)
593 : UserService.Instance.user
594 ? UserService.Instance.user.default_listing_type
598 // TODO might need to add a user setting for this too
599 export function getDataTypeFromProps(props: any): DataType {
600 return props.match.params.data_type
601 ? routeDataTypeToEnum(props.match.params.data_type)
605 export function getSortTypeFromProps(props: any): SortType {
606 return props.match.params.sort
607 ? routeSortTypeToEnum(props.match.params.sort)
608 : UserService.Instance.user
609 ? UserService.Instance.user.default_sort_type
613 export function getPageFromProps(props: any): number {
614 return props.match.params.page ? Number(props.match.params.page) : 1;
617 export function editCommentRes(
618 data: CommentResponse,
619 comments: Array<Comment>
621 let found = comments.find(c => c.id == data.comment.id);
623 found.content = data.comment.content;
624 found.updated = data.comment.updated;
625 found.removed = data.comment.removed;
626 found.deleted = data.comment.deleted;
627 found.upvotes = data.comment.upvotes;
628 found.downvotes = data.comment.downvotes;
629 found.score = data.comment.score;
633 export function saveCommentRes(
634 data: CommentResponse,
635 comments: Array<Comment>
637 let found = comments.find(c => c.id == data.comment.id);
639 found.saved = data.comment.saved;
643 export function createCommentLikeRes(
644 data: CommentResponse,
645 comments: Array<Comment>
647 let found: Comment = comments.find(c => c.id === data.comment.id);
649 found.score = data.comment.score;
650 found.upvotes = data.comment.upvotes;
651 found.downvotes = data.comment.downvotes;
652 if (data.comment.my_vote !== null) {
653 found.my_vote = data.comment.my_vote;
658 export function createPostLikeFindRes(data: PostResponse, posts: Array<Post>) {
659 let found = posts.find(c => c.id == data.post.id);
661 createPostLikeRes(data, found);
665 export function createPostLikeRes(data: PostResponse, post: Post) {
667 post.score = data.post.score;
668 post.upvotes = data.post.upvotes;
669 post.downvotes = data.post.downvotes;
670 if (data.post.my_vote !== null) {
671 post.my_vote = data.post.my_vote;
676 export function editPostFindRes(data: PostResponse, posts: Array<Post>) {
677 let found = posts.find(c => c.id == data.post.id);
679 editPostRes(data, found);
683 export function editPostRes(data: PostResponse, post: Post) {
685 post.url = data.post.url;
686 post.name = data.post.name;
687 post.nsfw = data.post.nsfw;
691 export function commentsToFlatNodes(
692 comments: Array<Comment>
693 ): Array<CommentNodeI> {
694 let nodes: Array<CommentNodeI> = [];
695 for (let comment of comments) {
696 nodes.push({ comment: comment });
701 export function commentSort(tree: Array<CommentNodeI>, sort: CommentSortType) {
702 // First, put removed and deleted comments at the bottom, then do your other sorts
703 if (sort == CommentSortType.Top) {
706 +a.comment.removed - +b.comment.removed ||
707 +a.comment.deleted - +b.comment.deleted ||
708 b.comment.score - a.comment.score
710 } else if (sort == CommentSortType.New) {
713 +a.comment.removed - +b.comment.removed ||
714 +a.comment.deleted - +b.comment.deleted ||
715 b.comment.published.localeCompare(a.comment.published)
717 } else if (sort == CommentSortType.Old) {
720 +a.comment.removed - +b.comment.removed ||
721 +a.comment.deleted - +b.comment.deleted ||
722 a.comment.published.localeCompare(b.comment.published)
724 } else if (sort == CommentSortType.Hot) {
727 +a.comment.removed - +b.comment.removed ||
728 +a.comment.deleted - +b.comment.deleted ||
729 hotRankComment(b.comment) - hotRankComment(a.comment)
733 // Go through the children recursively
734 for (let node of tree) {
736 commentSort(node.children, sort);
741 export function commentSortSortType(tree: Array<CommentNodeI>, sort: SortType) {
742 commentSort(tree, convertCommentSortType(sort));
745 function convertCommentSortType(sort: SortType): CommentSortType {
747 sort == SortType.TopAll ||
748 sort == SortType.TopDay ||
749 sort == SortType.TopWeek ||
750 sort == SortType.TopMonth ||
751 sort == SortType.TopYear
753 return CommentSortType.Top;
754 } else if (sort == SortType.New) {
755 return CommentSortType.New;
756 } else if (sort == SortType.Hot) {
757 return CommentSortType.Hot;
759 return CommentSortType.Hot;
763 export function postSort(
766 communityType: boolean
768 // First, put removed and deleted comments at the bottom, then do your other sorts
770 sort == SortType.TopAll ||
771 sort == SortType.TopDay ||
772 sort == SortType.TopWeek ||
773 sort == SortType.TopMonth ||
774 sort == SortType.TopYear
778 +a.removed - +b.removed ||
779 +a.deleted - +b.deleted ||
780 (communityType && +b.stickied - +a.stickied) ||
783 } else if (sort == SortType.New) {
786 +a.removed - +b.removed ||
787 +a.deleted - +b.deleted ||
788 (communityType && +b.stickied - +a.stickied) ||
789 b.published.localeCompare(a.published)
791 } else if (sort == SortType.Hot) {
794 +a.removed - +b.removed ||
795 +a.deleted - +b.deleted ||
796 (communityType && +b.stickied - +a.stickied) ||
797 hotRankPost(b) - hotRankPost(a)
802 export const colorList: Array<string> = [
811 function hsl(num: number) {
812 return `hsla(${num}, 35%, 50%, 1)`;
815 function randomHsl() {
816 return `hsla(${Math.random() * 360}, 100%, 50%, 1)`;