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';
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';
45 export const repoUrl = 'https://github.com/dessalines/lemmy';
46 export const markdownHelpUrl = '/docs/about_guide.html';
47 export const archiveUrl = 'https://archive.is';
49 export const postRefetchSeconds: number = 60 * 1000;
50 export const fetchLimit: number = 20;
51 export const mentionDropdownFetchLimit = 10;
53 export function randomStr() {
56 .replace(/[^a-z]+/g, '')
60 export function wsJsonToRes(msg: WebSocketJsonResponse): WebSocketResponse {
61 let opStr: string = msg.op;
63 op: UserOperation[opStr],
68 export const md = new markdown_it({
73 .use(markdown_it_container, 'spoiler', {
74 validate: function(params: any) {
75 return params.trim().match(/^spoiler\s+(.*)$/);
78 render: function(tokens: any, idx: any) {
79 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
81 if (tokens[idx].nesting === 1) {
83 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
86 return '</details>\n';
90 .use(markdownitEmoji, {
91 defs: objectFlip(emojiShortName),
94 md.renderer.rules.emoji = function(token, idx) {
95 return twemoji.parse(token[idx].content);
98 export function hotRankComment(comment: Comment): number {
99 return hotRank(comment.score, comment.published);
102 export function hotRankPost(post: Post): number {
103 return hotRank(post.score, post.newest_activity_time);
106 export function hotRank(score: number, timeStr: string): number {
107 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
108 let date: Date = new Date(timeStr + 'Z'); // Add Z to convert from UTC date
109 let now: Date = new Date();
110 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
113 (10000 * Math.log10(Math.max(1, 3 + score))) /
114 Math.pow(hoursElapsed + 2, 1.8);
116 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
121 export function mdToHtml(text: string) {
122 return { __html: md.render(text) };
125 export function getUnixTime(text: string): number {
126 return text ? new Date(text).getTime() / 1000 : undefined;
129 export function addTypeInfo<T>(
132 ): Array<{ type_: string; data: T }> {
133 return arr.map(e => {
134 return { type_: name, data: e };
138 export function canMod(
140 modIds: Array<number>,
142 onSelf: boolean = false
144 // You can do moderator actions only on the mods added after you.
146 let yourIndex = modIds.findIndex(id => id == user.id);
147 if (yourIndex == -1) {
150 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
151 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
152 return !modIds.includes(creator_id);
159 export function isMod(modIds: Array<number>, creator_id: number): boolean {
160 return modIds.includes(creator_id);
163 const imageRegex = new RegExp(
164 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg))/
166 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
168 export function isImage(url: string) {
169 return imageRegex.test(url);
172 export function isVideo(url: string) {
173 return videoRegex.test(url);
176 export function validURL(str: string) {
178 return !!new URL(str);
184 export function validEmail(email: string) {
185 let re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
186 return re.test(String(email).toLowerCase());
189 export function capitalizeFirstLetter(str: string): string {
190 return str.charAt(0).toUpperCase() + str.slice(1);
193 export function routeSortTypeToEnum(sort: string): SortType {
196 } else if (sort == 'hot') {
198 } else if (sort == 'topday') {
199 return SortType.TopDay;
200 } else if (sort == 'topweek') {
201 return SortType.TopWeek;
202 } else if (sort == 'topmonth') {
203 return SortType.TopMonth;
204 } else if (sort == 'topyear') {
205 return SortType.TopYear;
206 } else if (sort == 'topall') {
207 return SortType.TopAll;
211 export function routeListingTypeToEnum(type: string): ListingType {
212 return ListingType[capitalizeFirstLetter(type)];
215 export function routeDataTypeToEnum(type: string): DataType {
216 return DataType[capitalizeFirstLetter(type)];
219 export function routeSearchTypeToEnum(type: string): SearchType {
220 return SearchType[capitalizeFirstLetter(type)];
223 export async function getPageTitle(url: string) {
224 let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
225 let title = await res.title;
229 export function debounce(
232 immediate: boolean = false
234 // 'private' variable for instance
235 // The returned function will be able to reference this due to closure.
236 // Each call to the returned function will share this common timer.
239 // Calling debounce returns a new anonymous function
241 // reference the context and args for the setTimeout function
245 // Should the function be called now? If immediate is true
246 // and not already in a timeout then the answer is: Yes
247 var callNow = immediate && !timeout;
249 // This is the basic debounce behaviour where you can call this
250 // function several times, but it will only execute once
251 // [before or after imposing a delay].
252 // Each time the returned function is called, the timer starts over.
253 clearTimeout(timeout);
255 // Set the new timeout
256 timeout = setTimeout(function() {
257 // Inside the timeout function, clear the timeout variable
258 // which will let the next execution run when in 'immediate' mode
261 // Check if the function already ran with the immediate flag
263 // Call the original function with apply
264 // apply lets you define the 'this' object as well as the arguments
265 // (both captured before setTimeout)
266 func.apply(context, args);
270 // Immediate mode and no wait timer? Execute the function..
271 if (callNow) func.apply(context, args);
275 export const languages = [
276 { code: 'ca', name: 'Català' },
277 { code: 'en', name: 'English' },
278 { code: 'eo', name: 'Esperanto' },
279 { code: 'es', name: 'Español' },
280 { code: 'de', name: 'Deutsch' },
281 { code: 'fa', name: 'فارسی' },
282 { code: 'ja', name: '日本語' },
283 { code: 'pt_BR', name: 'Português Brasileiro' },
284 { code: 'zh', name: '中文' },
285 { code: 'fi', name: 'Suomi' },
286 { code: 'fr', name: 'Français' },
287 { code: 'sv', name: 'Svenska' },
288 { code: 'ru', name: 'Русский' },
289 { code: 'nl', name: 'Nederlands' },
290 { code: 'it', name: 'Italiano' },
293 export function getLanguage(): string {
294 let user = UserService.Instance.user;
295 let lang = user && user.lang ? user.lang : 'browser';
297 if (lang == 'browser') {
298 return getBrowserLanguage();
304 export function getBrowserLanguage(): string {
305 return navigator.language;
308 export function getMomentLanguage(): string {
309 let lang = getLanguage();
310 if (lang.startsWith('zh')) {
312 } else if (lang.startsWith('sv')) {
314 } else if (lang.startsWith('fr')) {
316 } else if (lang.startsWith('de')) {
318 } else if (lang.startsWith('ru')) {
320 } else if (lang.startsWith('es')) {
322 } else if (lang.startsWith('eo')) {
324 } else if (lang.startsWith('nl')) {
326 } else if (lang.startsWith('it')) {
328 } else if (lang.startsWith('fi')) {
330 } else if (lang.startsWith('ca')) {
332 } else if (lang.startsWith('fa')) {
334 } else if (lang.startsWith('pt')) {
336 } else if (lang.startsWith('ja')) {
344 export const themes = [
359 export function setTheme(theme: string = 'darkly') {
360 // unload all the other themes
361 for (var i = 0; i < themes.length; i++) {
362 let styleSheet = document.getElementById(themes[i]);
364 styleSheet.setAttribute('disabled', 'disabled');
368 // Load the theme dynamically
369 if (!document.getElementById(theme)) {
370 var head = document.getElementsByTagName('head')[0];
371 var link = document.createElement('link');
373 link.rel = 'stylesheet';
374 link.type = 'text/css';
375 link.href = `/static/assets/css/themes/${theme}.min.css`;
377 head.appendChild(link);
379 document.getElementById(theme).removeAttribute('disabled');
382 export function objectFlip(obj: any) {
384 Object.keys(obj).forEach(key => {
390 export function pictshareAvatarThumbnail(src: string): string {
391 // sample url: http://localhost:8535/pictshare/gs7xuu.jpg
392 let split = src.split('pictshare');
393 let out = `${split[0]}pictshare/96${split[1]}`;
397 export function showAvatars(): boolean {
399 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
400 !UserService.Instance.user
404 /// Converts to image thumbnail (only supports pictshare currently)
405 export function imageThumbnailer(url: string): string {
406 let split = url.split('pictshare');
407 if (split.length > 1) {
408 let out = `${split[0]}pictshare/192${split[1]}`;
415 export function isCommentType(item: Comment | PrivateMessage): item is Comment {
416 return (item as Comment).community_id !== undefined;
419 export function toast(text: string, background: string = 'success') {
420 let backgroundColor = `var(--${background})`;
423 backgroundColor: backgroundColor,
429 export function setupTribute(): Tribute {
435 menuItemTemplate: (item: any) => {
436 let emoji = `:${item.original.key}:`;
437 return `${item.original.val} ${emoji}`;
439 selectTemplate: (item: any) => {
440 return `:${item.original.key}:`;
442 values: Object.entries(emojiShortName).map(e => {
443 return { key: e[1], val: e[0] };
446 autocompleteMode: true,
447 menuItemLimit: mentionDropdownFetchLimit,
452 selectTemplate: (item: any) => {
453 return `[/u/${item.original.key}](/u/${item.original.key})`;
455 values: (text: string, cb: any) => {
456 userSearch(text, (users: any) => cb(users));
459 autocompleteMode: true,
460 menuItemLimit: mentionDropdownFetchLimit,
466 selectTemplate: (item: any) => {
467 return `[/c/${item.original.key}](/c/${item.original.key})`;
469 values: (text: string, cb: any) => {
470 communitySearch(text, (communities: any) => cb(communities));
473 autocompleteMode: true,
474 menuItemLimit: mentionDropdownFetchLimit,
480 function userSearch(text: string, cb: any) {
482 let form: SearchForm = {
484 type_: SearchType[SearchType.Users],
485 sort: SortType[SortType.TopAll],
487 limit: mentionDropdownFetchLimit,
490 WebSocketService.Instance.search(form);
492 this.userSub = WebSocketService.Instance.subject.subscribe(
494 let res = wsJsonToRes(msg);
495 if (res.op == UserOperation.Search) {
496 let data = res.data as SearchResponse;
497 let users = data.users.map(u => {
498 return { key: u.name };
501 this.userSub.unsubscribe();
504 err => console.error(err),
505 () => console.log('complete')
512 function communitySearch(text: string, cb: any) {
514 let form: SearchForm = {
516 type_: SearchType[SearchType.Communities],
517 sort: SortType[SortType.TopAll],
519 limit: mentionDropdownFetchLimit,
522 WebSocketService.Instance.search(form);
524 this.communitySub = WebSocketService.Instance.subject.subscribe(
526 let res = wsJsonToRes(msg);
527 if (res.op == UserOperation.Search) {
528 let data = res.data as SearchResponse;
529 let communities = data.communities.map(u => {
530 return { key: u.name };
533 this.communitySub.unsubscribe();
536 err => console.error(err),
537 () => console.log('complete')
544 export function getListingTypeFromProps(props: any): ListingType {
545 return props.match.params.listing_type
546 ? routeListingTypeToEnum(props.match.params.listing_type)
547 : UserService.Instance.user
548 ? UserService.Instance.user.default_listing_type
552 // TODO might need to add a user setting for this too
553 export function getDataTypeFromProps(props: any): DataType {
554 return props.match.params.data_type
555 ? routeDataTypeToEnum(props.match.params.data_type)
559 export function getSortTypeFromProps(props: any): SortType {
560 return props.match.params.sort
561 ? routeSortTypeToEnum(props.match.params.sort)
562 : UserService.Instance.user
563 ? UserService.Instance.user.default_sort_type
567 export function getPageFromProps(props: any): number {
568 return props.match.params.page ? Number(props.match.params.page) : 1;
571 export function editCommentRes(
572 data: CommentResponse,
573 comments: Array<Comment>
575 let found = comments.find(c => c.id == data.comment.id);
577 found.content = data.comment.content;
578 found.updated = data.comment.updated;
579 found.removed = data.comment.removed;
580 found.deleted = data.comment.deleted;
581 found.upvotes = data.comment.upvotes;
582 found.downvotes = data.comment.downvotes;
583 found.score = data.comment.score;
587 export function saveCommentRes(
588 data: CommentResponse,
589 comments: Array<Comment>
591 let found = comments.find(c => c.id == data.comment.id);
593 found.saved = data.comment.saved;
597 export function createCommentLikeRes(
598 data: CommentResponse,
599 comments: Array<Comment>
601 let found: Comment = comments.find(c => c.id === data.comment.id);
603 found.score = data.comment.score;
604 found.upvotes = data.comment.upvotes;
605 found.downvotes = data.comment.downvotes;
606 if (data.comment.my_vote !== null) {
607 found.my_vote = data.comment.my_vote;
612 export function createPostLikeFindRes(data: PostResponse, posts: Array<Post>) {
613 let found = posts.find(c => c.id == data.post.id);
615 createPostLikeRes(data, found);
619 export function createPostLikeRes(data: PostResponse, post: Post) {
621 post.score = data.post.score;
622 post.upvotes = data.post.upvotes;
623 post.downvotes = data.post.downvotes;
624 if (data.post.my_vote !== null) {
625 post.my_vote = data.post.my_vote;
630 export function editPostFindRes(data: PostResponse, posts: Array<Post>) {
631 let found = posts.find(c => c.id == data.post.id);
633 editPostRes(data, found);
637 export function editPostRes(data: PostResponse, post: Post) {
639 post.url = data.post.url;
640 post.name = data.post.name;
641 post.nsfw = data.post.nsfw;
645 export function commentsToFlatNodes(
646 comments: Array<Comment>
647 ): Array<CommentNode> {
648 let nodes: Array<CommentNode> = [];
649 for (let comment of comments) {
650 nodes.push({ comment: comment });
655 export function commentSort(tree: Array<CommentNode>, sort: CommentSortType) {
656 // First, put removed and deleted comments at the bottom, then do your other sorts
657 if (sort == CommentSortType.Top) {
660 +a.comment.removed - +b.comment.removed ||
661 +a.comment.deleted - +b.comment.deleted ||
662 b.comment.score - a.comment.score
664 } else if (sort == CommentSortType.New) {
667 +a.comment.removed - +b.comment.removed ||
668 +a.comment.deleted - +b.comment.deleted ||
669 b.comment.published.localeCompare(a.comment.published)
671 } else if (sort == CommentSortType.Old) {
674 +a.comment.removed - +b.comment.removed ||
675 +a.comment.deleted - +b.comment.deleted ||
676 a.comment.published.localeCompare(b.comment.published)
678 } else if (sort == CommentSortType.Hot) {
681 +a.comment.removed - +b.comment.removed ||
682 +a.comment.deleted - +b.comment.deleted ||
683 hotRankComment(b.comment) - hotRankComment(a.comment)
687 // Go through the children recursively
688 for (let node of tree) {
690 commentSort(node.children, sort);
695 export function commentSortSortType(tree: Array<CommentNode>, sort: SortType) {
696 commentSort(tree, convertCommentSortType(sort));
699 function convertCommentSortType(sort: SortType): CommentSortType {
701 sort == SortType.TopAll ||
702 sort == SortType.TopDay ||
703 sort == SortType.TopWeek ||
704 sort == SortType.TopMonth ||
705 sort == SortType.TopYear
707 return CommentSortType.Top;
708 } else if (sort == SortType.New) {
709 return CommentSortType.New;
710 } else if (sort == SortType.Hot) {
711 return CommentSortType.Hot;
713 return CommentSortType.Hot;
717 export function postSort(posts: Array<Post>, sort: SortType) {
718 // First, put removed and deleted comments at the bottom, then do your other sorts
720 sort == SortType.TopAll ||
721 sort == SortType.TopDay ||
722 sort == SortType.TopWeek ||
723 sort == SortType.TopMonth ||
724 sort == SortType.TopYear
728 +a.removed - +b.removed || +a.deleted - +b.deleted || b.score - a.score
730 } else if (sort == SortType.New) {
733 +a.removed - +b.removed ||
734 +a.deleted - +b.deleted ||
735 b.published.localeCompare(a.published)
737 } else if (sort == SortType.Hot) {
740 +a.removed - +b.removed ||
741 +a.deleted - +b.deleted ||
742 hotRankPost(b) - hotRankPost(a)