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';
44 import tippy from 'tippy.js';
46 export const repoUrl = 'https://github.com/dessalines/lemmy';
47 export const markdownHelpUrl = '/docs/about_guide.html';
48 export const archiveUrl = 'https://archive.is';
50 export const postRefetchSeconds: number = 60 * 1000;
51 export const fetchLimit: number = 20;
52 export const mentionDropdownFetchLimit = 10;
54 export function randomStr() {
57 .replace(/[^a-z]+/g, '')
61 export function wsJsonToRes(msg: WebSocketJsonResponse): WebSocketResponse {
62 let opStr: string = msg.op;
64 op: UserOperation[opStr],
69 export const md = new markdown_it({
74 .use(markdown_it_container, 'spoiler', {
75 validate: function(params: any) {
76 return params.trim().match(/^spoiler\s+(.*)$/);
79 render: function(tokens: any, idx: any) {
80 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
82 if (tokens[idx].nesting === 1) {
84 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
87 return '</details>\n';
91 .use(markdownitEmoji, {
92 defs: objectFlip(emojiShortName),
95 md.renderer.rules.emoji = function(token, idx) {
96 return twemoji.parse(token[idx].content);
99 export function hotRankComment(comment: Comment): number {
100 return hotRank(comment.score, comment.published);
103 export function hotRankPost(post: Post): number {
104 return hotRank(post.score, post.newest_activity_time);
107 export function hotRank(score: number, timeStr: string): number {
108 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
109 let date: Date = new Date(timeStr + 'Z'); // Add Z to convert from UTC date
110 let now: Date = new Date();
111 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
114 (10000 * Math.log10(Math.max(1, 3 + score))) /
115 Math.pow(hoursElapsed + 2, 1.8);
117 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
122 export function mdToHtml(text: string) {
123 return { __html: md.render(text) };
126 export function getUnixTime(text: string): number {
127 return text ? new Date(text).getTime() / 1000 : undefined;
130 export function addTypeInfo<T>(
133 ): Array<{ type_: string; data: T }> {
134 return arr.map(e => {
135 return { type_: name, data: e };
139 export function canMod(
141 modIds: Array<number>,
143 onSelf: boolean = false
145 // You can do moderator actions only on the mods added after you.
147 let yourIndex = modIds.findIndex(id => id == user.id);
148 if (yourIndex == -1) {
151 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
152 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
153 return !modIds.includes(creator_id);
160 export function isMod(modIds: Array<number>, creator_id: number): boolean {
161 return modIds.includes(creator_id);
164 const imageRegex = new RegExp(
165 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg))/
167 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
169 export function isImage(url: string) {
170 return imageRegex.test(url);
173 export function isVideo(url: string) {
174 return videoRegex.test(url);
177 export function validURL(str: string) {
179 return !!new URL(str);
185 export function validEmail(email: string) {
186 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,}))$/;
187 return re.test(String(email).toLowerCase());
190 export function capitalizeFirstLetter(str: string): string {
191 return str.charAt(0).toUpperCase() + str.slice(1);
194 export function routeSortTypeToEnum(sort: string): SortType {
197 } else if (sort == 'hot') {
199 } else if (sort == 'topday') {
200 return SortType.TopDay;
201 } else if (sort == 'topweek') {
202 return SortType.TopWeek;
203 } else if (sort == 'topmonth') {
204 return SortType.TopMonth;
205 } else if (sort == 'topyear') {
206 return SortType.TopYear;
207 } else if (sort == 'topall') {
208 return SortType.TopAll;
212 export function routeListingTypeToEnum(type: string): ListingType {
213 return ListingType[capitalizeFirstLetter(type)];
216 export function routeDataTypeToEnum(type: string): DataType {
217 return DataType[capitalizeFirstLetter(type)];
220 export function routeSearchTypeToEnum(type: string): SearchType {
221 return SearchType[capitalizeFirstLetter(type)];
224 export async function getPageTitle(url: string) {
225 let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
226 let title = await res.title;
230 export function debounce(
233 immediate: boolean = false
235 // 'private' variable for instance
236 // The returned function will be able to reference this due to closure.
237 // Each call to the returned function will share this common timer.
240 // Calling debounce returns a new anonymous function
242 // reference the context and args for the setTimeout function
246 // Should the function be called now? If immediate is true
247 // and not already in a timeout then the answer is: Yes
248 var callNow = immediate && !timeout;
250 // This is the basic debounce behaviour where you can call this
251 // function several times, but it will only execute once
252 // [before or after imposing a delay].
253 // Each time the returned function is called, the timer starts over.
254 clearTimeout(timeout);
256 // Set the new timeout
257 timeout = setTimeout(function() {
258 // Inside the timeout function, clear the timeout variable
259 // which will let the next execution run when in 'immediate' mode
262 // Check if the function already ran with the immediate flag
264 // Call the original function with apply
265 // apply lets you define the 'this' object as well as the arguments
266 // (both captured before setTimeout)
267 func.apply(context, args);
271 // Immediate mode and no wait timer? Execute the function..
272 if (callNow) func.apply(context, args);
276 export const languages = [
277 { code: 'ca', name: 'Català' },
278 { code: 'en', name: 'English' },
279 { code: 'eo', name: 'Esperanto' },
280 { code: 'es', name: 'Español' },
281 { code: 'de', name: 'Deutsch' },
282 { code: 'fa', name: 'فارسی' },
283 { code: 'ja', name: '日本語' },
284 { code: 'pt_BR', name: 'Português Brasileiro' },
285 { code: 'zh', name: '中文' },
286 { code: 'fi', name: 'Suomi' },
287 { code: 'fr', name: 'Français' },
288 { code: 'sv', name: 'Svenska' },
289 { code: 'ru', name: 'Русский' },
290 { code: 'nl', name: 'Nederlands' },
291 { code: 'it', name: 'Italiano' },
294 export function getLanguage(): string {
295 let user = UserService.Instance.user;
296 let lang = user && user.lang ? user.lang : 'browser';
298 if (lang == 'browser') {
299 return getBrowserLanguage();
305 export function getBrowserLanguage(): string {
306 return navigator.language;
309 export function getMomentLanguage(): string {
310 let lang = getLanguage();
311 if (lang.startsWith('zh')) {
313 } else if (lang.startsWith('sv')) {
315 } else if (lang.startsWith('fr')) {
317 } else if (lang.startsWith('de')) {
319 } else if (lang.startsWith('ru')) {
321 } else if (lang.startsWith('es')) {
323 } else if (lang.startsWith('eo')) {
325 } else if (lang.startsWith('nl')) {
327 } else if (lang.startsWith('it')) {
329 } else if (lang.startsWith('fi')) {
331 } else if (lang.startsWith('ca')) {
333 } else if (lang.startsWith('fa')) {
335 } else if (lang.startsWith('pt')) {
337 } else if (lang.startsWith('ja')) {
345 export const themes = [
360 export function setTheme(theme: string = 'darkly') {
361 // unload all the other themes
362 for (var i = 0; i < themes.length; i++) {
363 let styleSheet = document.getElementById(themes[i]);
365 styleSheet.setAttribute('disabled', 'disabled');
369 // Load the theme dynamically
370 if (!document.getElementById(theme)) {
371 var head = document.getElementsByTagName('head')[0];
372 var link = document.createElement('link');
374 link.rel = 'stylesheet';
375 link.type = 'text/css';
376 link.href = `/static/assets/css/themes/${theme}.min.css`;
378 head.appendChild(link);
380 document.getElementById(theme).removeAttribute('disabled');
383 export function objectFlip(obj: any) {
385 Object.keys(obj).forEach(key => {
391 export function pictshareAvatarThumbnail(src: string): string {
392 // sample url: http://localhost:8535/pictshare/gs7xuu.jpg
393 let split = src.split('pictshare');
394 let out = `${split[0]}pictshare/96${split[1]}`;
398 export function showAvatars(): boolean {
400 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
401 !UserService.Instance.user
405 /// Converts to image thumbnail (only supports pictshare currently)
406 export function imageThumbnailer(url: string): string {
407 let split = url.split('pictshare');
408 if (split.length > 1) {
409 let out = `${split[0]}pictshare/192${split[1]}`;
416 export function isCommentType(item: Comment | PrivateMessage): item is Comment {
417 return (item as Comment).community_id !== undefined;
420 export function toast(text: string, background: string = 'success') {
421 let backgroundColor = `var(--${background})`;
424 backgroundColor: backgroundColor,
430 export function setupTribute(): Tribute {
436 menuItemTemplate: (item: any) => {
437 let emoji = `:${item.original.key}:`;
438 return `${item.original.val} ${emoji}`;
440 selectTemplate: (item: any) => {
441 return `:${item.original.key}:`;
443 values: Object.entries(emojiShortName).map(e => {
444 return { key: e[1], val: e[0] };
447 autocompleteMode: true,
448 menuItemLimit: mentionDropdownFetchLimit,
449 menuShowMinLength: 2,
454 selectTemplate: (item: any) => {
455 return `[/u/${item.original.key}](/u/${item.original.key})`;
457 values: (text: string, cb: any) => {
458 userSearch(text, (users: any) => cb(users));
461 autocompleteMode: true,
462 menuItemLimit: mentionDropdownFetchLimit,
463 menuShowMinLength: 2,
469 selectTemplate: (item: any) => {
470 return `[/c/${item.original.key}](/c/${item.original.key})`;
472 values: (text: string, cb: any) => {
473 communitySearch(text, (communities: any) => cb(communities));
476 autocompleteMode: true,
477 menuItemLimit: mentionDropdownFetchLimit,
478 menuShowMinLength: 2,
484 let tippyInstance = tippy('[data-tippy-content]');
486 export function setupTippy() {
487 tippyInstance.forEach(e => e.destroy());
488 tippyInstance = tippy('[data-tippy-content]', {
490 // Display on "long press"
491 touch: ['hold', 500],
495 function userSearch(text: string, cb: any) {
497 let form: SearchForm = {
499 type_: SearchType[SearchType.Users],
500 sort: SortType[SortType.TopAll],
502 limit: mentionDropdownFetchLimit,
505 WebSocketService.Instance.search(form);
507 this.userSub = WebSocketService.Instance.subject.subscribe(
509 let res = wsJsonToRes(msg);
510 if (res.op == UserOperation.Search) {
511 let data = res.data as SearchResponse;
512 let users = data.users.map(u => {
513 return { key: u.name };
516 this.userSub.unsubscribe();
519 err => console.error(err),
520 () => console.log('complete')
527 function communitySearch(text: string, cb: any) {
529 let form: SearchForm = {
531 type_: SearchType[SearchType.Communities],
532 sort: SortType[SortType.TopAll],
534 limit: mentionDropdownFetchLimit,
537 WebSocketService.Instance.search(form);
539 this.communitySub = WebSocketService.Instance.subject.subscribe(
541 let res = wsJsonToRes(msg);
542 if (res.op == UserOperation.Search) {
543 let data = res.data as SearchResponse;
544 let communities = data.communities.map(u => {
545 return { key: u.name };
548 this.communitySub.unsubscribe();
551 err => console.error(err),
552 () => console.log('complete')
559 export function getListingTypeFromProps(props: any): ListingType {
560 return props.match.params.listing_type
561 ? routeListingTypeToEnum(props.match.params.listing_type)
562 : UserService.Instance.user
563 ? UserService.Instance.user.default_listing_type
567 // TODO might need to add a user setting for this too
568 export function getDataTypeFromProps(props: any): DataType {
569 return props.match.params.data_type
570 ? routeDataTypeToEnum(props.match.params.data_type)
574 export function getSortTypeFromProps(props: any): SortType {
575 return props.match.params.sort
576 ? routeSortTypeToEnum(props.match.params.sort)
577 : UserService.Instance.user
578 ? UserService.Instance.user.default_sort_type
582 export function getPageFromProps(props: any): number {
583 return props.match.params.page ? Number(props.match.params.page) : 1;
586 export function editCommentRes(
587 data: CommentResponse,
588 comments: Array<Comment>
590 let found = comments.find(c => c.id == data.comment.id);
592 found.content = data.comment.content;
593 found.updated = data.comment.updated;
594 found.removed = data.comment.removed;
595 found.deleted = data.comment.deleted;
596 found.upvotes = data.comment.upvotes;
597 found.downvotes = data.comment.downvotes;
598 found.score = data.comment.score;
602 export function saveCommentRes(
603 data: CommentResponse,
604 comments: Array<Comment>
606 let found = comments.find(c => c.id == data.comment.id);
608 found.saved = data.comment.saved;
612 export function createCommentLikeRes(
613 data: CommentResponse,
614 comments: Array<Comment>
616 let found: Comment = comments.find(c => c.id === data.comment.id);
618 found.score = data.comment.score;
619 found.upvotes = data.comment.upvotes;
620 found.downvotes = data.comment.downvotes;
621 if (data.comment.my_vote !== null) {
622 found.my_vote = data.comment.my_vote;
627 export function createPostLikeFindRes(data: PostResponse, posts: Array<Post>) {
628 let found = posts.find(c => c.id == data.post.id);
630 createPostLikeRes(data, found);
634 export function createPostLikeRes(data: PostResponse, post: Post) {
636 post.score = data.post.score;
637 post.upvotes = data.post.upvotes;
638 post.downvotes = data.post.downvotes;
639 if (data.post.my_vote !== null) {
640 post.my_vote = data.post.my_vote;
645 export function editPostFindRes(data: PostResponse, posts: Array<Post>) {
646 let found = posts.find(c => c.id == data.post.id);
648 editPostRes(data, found);
652 export function editPostRes(data: PostResponse, post: Post) {
654 post.url = data.post.url;
655 post.name = data.post.name;
656 post.nsfw = data.post.nsfw;
660 export function commentsToFlatNodes(
661 comments: Array<Comment>
662 ): Array<CommentNode> {
663 let nodes: Array<CommentNode> = [];
664 for (let comment of comments) {
665 nodes.push({ comment: comment });
670 export function commentSort(tree: Array<CommentNode>, sort: CommentSortType) {
671 // First, put removed and deleted comments at the bottom, then do your other sorts
672 if (sort == CommentSortType.Top) {
675 +a.comment.removed - +b.comment.removed ||
676 +a.comment.deleted - +b.comment.deleted ||
677 b.comment.score - a.comment.score
679 } else if (sort == CommentSortType.New) {
682 +a.comment.removed - +b.comment.removed ||
683 +a.comment.deleted - +b.comment.deleted ||
684 b.comment.published.localeCompare(a.comment.published)
686 } else if (sort == CommentSortType.Old) {
689 +a.comment.removed - +b.comment.removed ||
690 +a.comment.deleted - +b.comment.deleted ||
691 a.comment.published.localeCompare(b.comment.published)
693 } else if (sort == CommentSortType.Hot) {
696 +a.comment.removed - +b.comment.removed ||
697 +a.comment.deleted - +b.comment.deleted ||
698 hotRankComment(b.comment) - hotRankComment(a.comment)
702 // Go through the children recursively
703 for (let node of tree) {
705 commentSort(node.children, sort);
710 export function commentSortSortType(tree: Array<CommentNode>, sort: SortType) {
711 commentSort(tree, convertCommentSortType(sort));
714 function convertCommentSortType(sort: SortType): CommentSortType {
716 sort == SortType.TopAll ||
717 sort == SortType.TopDay ||
718 sort == SortType.TopWeek ||
719 sort == SortType.TopMonth ||
720 sort == SortType.TopYear
722 return CommentSortType.Top;
723 } else if (sort == SortType.New) {
724 return CommentSortType.New;
725 } else if (sort == SortType.Hot) {
726 return CommentSortType.Hot;
728 return CommentSortType.Hot;
732 export function postSort(
735 communityType: boolean
737 // First, put removed and deleted comments at the bottom, then do your other sorts
739 sort == SortType.TopAll ||
740 sort == SortType.TopDay ||
741 sort == SortType.TopWeek ||
742 sort == SortType.TopMonth ||
743 sort == SortType.TopYear
747 +a.removed - +b.removed ||
748 +a.deleted - +b.deleted ||
749 (communityType && +b.stickied - +a.stickied) ||
752 } else if (sort == SortType.New) {
755 +a.removed - +b.removed ||
756 +a.deleted - +b.deleted ||
757 (communityType && +b.stickied - +a.stickied) ||
758 b.published.localeCompare(a.published)
760 } else if (sort == SortType.Hot) {
763 +a.removed - +b.removed ||
764 +a.deleted - +b.deleted ||
765 (communityType && +b.stickied - +a.stickied) ||
766 hotRankPost(b) - hotRankPost(a)
771 export const colorList: Array<string> = [...Array(10)].map(() => randomHsl());
773 export function randomHsl() {
774 return `hsla(${Math.random() * 360}, 100%, 50%, 1)`;