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';
15 import 'moment/locale/ka';
20 CommentNode as CommentNodeI,
30 WebSocketJsonResponse,
35 } from './interfaces';
36 import { UserService, WebSocketService } from './services';
38 import Tribute from 'tributejs/src/Tribute.js';
39 import markdown_it from 'markdown-it';
40 import markdownitEmoji from 'markdown-it-emoji/light';
41 import markdown_it_container from 'markdown-it-container';
42 import twemoji from 'twemoji';
43 import emojiShortName from 'emoji-short-name';
44 import Toastify from 'toastify-js';
45 import tippy from 'tippy.js';
46 import EmojiButton from '@joeattardi/emoji-button';
48 export const repoUrl = 'https://github.com/LemmyNet/lemmy';
49 export const helpGuideUrl = '/docs/about_guide.html';
50 export const markdownHelpUrl = `${helpGuideUrl}#markdown-guide`;
51 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
52 export const archiveUrl = 'https://archive.is';
54 export const postRefetchSeconds: number = 60 * 1000;
55 export const fetchLimit: number = 20;
56 export const mentionDropdownFetchLimit = 10;
58 export const languages = [
59 { code: 'ca', name: 'Català' },
60 { code: 'en', name: 'English' },
61 { code: 'eo', name: 'Esperanto' },
62 { code: 'es', name: 'Español' },
63 { code: 'de', name: 'Deutsch' },
64 { code: 'ka', name: 'ქართული ენა' },
65 { code: 'fa', name: 'فارسی' },
66 { code: 'ja', name: '日本語' },
67 { code: 'pt_BR', name: 'Português Brasileiro' },
68 { code: 'zh', name: '中文' },
69 { code: 'fi', name: 'Suomi' },
70 { code: 'fr', name: 'Français' },
71 { code: 'sv', name: 'Svenska' },
72 { code: 'ru', name: 'Русский' },
73 { code: 'nl', name: 'Nederlands' },
74 { code: 'it', name: 'Italiano' },
77 export const themes = [
92 export const emojiPicker = new EmojiButton({
93 // Use the emojiShortName from native
96 position: 'auto-start',
100 export function randomStr() {
103 .replace(/[^a-z]+/g, '')
107 export function wsJsonToRes(msg: WebSocketJsonResponse): WebSocketResponse {
108 let opStr: string = msg.op;
110 op: UserOperation[opStr],
115 export const md = new markdown_it({
120 .use(markdown_it_container, 'spoiler', {
121 validate: function(params: any) {
122 return params.trim().match(/^spoiler\s+(.*)$/);
125 render: function(tokens: any, idx: any) {
126 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
128 if (tokens[idx].nesting === 1) {
130 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
133 return '</details>\n';
137 .use(markdownitEmoji, {
138 defs: objectFlip(emojiShortName),
141 md.renderer.rules.emoji = function(token, idx) {
142 return twemoji.parse(token[idx].content);
145 export function hotRankComment(comment: Comment): number {
146 return hotRank(comment.score, comment.published);
149 export function hotRankPost(post: Post): number {
150 return hotRank(post.score, post.newest_activity_time);
153 export function hotRank(score: number, timeStr: string): number {
154 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
155 let date: Date = new Date(timeStr + 'Z'); // Add Z to convert from UTC date
156 let now: Date = new Date();
157 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
160 (10000 * Math.log10(Math.max(1, 3 + score))) /
161 Math.pow(hoursElapsed + 2, 1.8);
163 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
168 export function mdToHtml(text: string) {
169 return { __html: md.render(text) };
172 export function getUnixTime(text: string): number {
173 return text ? new Date(text).getTime() / 1000 : undefined;
176 export function addTypeInfo<T>(
179 ): Array<{ type_: string; data: T }> {
180 return arr.map(e => {
181 return { type_: name, data: e };
185 export function canMod(
187 modIds: Array<number>,
189 onSelf: boolean = false
191 // You can do moderator actions only on the mods added after you.
193 let yourIndex = modIds.findIndex(id => id == user.id);
194 if (yourIndex == -1) {
197 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
198 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
199 return !modIds.includes(creator_id);
206 export function isMod(modIds: Array<number>, creator_id: number): boolean {
207 return modIds.includes(creator_id);
210 const imageRegex = new RegExp(
211 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg))/
213 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
215 export function isImage(url: string) {
216 return imageRegex.test(url);
219 export function isVideo(url: string) {
220 return videoRegex.test(url);
223 export function validURL(str: string) {
225 return !!new URL(str);
231 export function validEmail(email: string) {
232 let re = /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
233 return re.test(String(email).toLowerCase());
236 export function capitalizeFirstLetter(str: string): string {
237 return str.charAt(0).toUpperCase() + str.slice(1);
240 export function routeSortTypeToEnum(sort: string): SortType {
243 } else if (sort == 'hot') {
245 } else if (sort == 'topday') {
246 return SortType.TopDay;
247 } else if (sort == 'topweek') {
248 return SortType.TopWeek;
249 } else if (sort == 'topmonth') {
250 return SortType.TopMonth;
251 } else if (sort == 'topyear') {
252 return SortType.TopYear;
253 } else if (sort == 'topall') {
254 return SortType.TopAll;
258 export function routeListingTypeToEnum(type: string): ListingType {
259 return ListingType[capitalizeFirstLetter(type)];
262 export function routeDataTypeToEnum(type: string): DataType {
263 return DataType[capitalizeFirstLetter(type)];
266 export function routeSearchTypeToEnum(type: string): SearchType {
267 return SearchType[capitalizeFirstLetter(type)];
270 export async function getPageTitle(url: string) {
271 let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
272 let title = await res.title;
276 export function debounce(
279 immediate: boolean = false
281 // 'private' variable for instance
282 // The returned function will be able to reference this due to closure.
283 // Each call to the returned function will share this common timer.
286 // Calling debounce returns a new anonymous function
288 // reference the context and args for the setTimeout function
292 // Should the function be called now? If immediate is true
293 // and not already in a timeout then the answer is: Yes
294 var callNow = immediate && !timeout;
296 // This is the basic debounce behaviour where you can call this
297 // function several times, but it will only execute once
298 // [before or after imposing a delay].
299 // Each time the returned function is called, the timer starts over.
300 clearTimeout(timeout);
302 // Set the new timeout
303 timeout = setTimeout(function() {
304 // Inside the timeout function, clear the timeout variable
305 // which will let the next execution run when in 'immediate' mode
308 // Check if the function already ran with the immediate flag
310 // Call the original function with apply
311 // apply lets you define the 'this' object as well as the arguments
312 // (both captured before setTimeout)
313 func.apply(context, args);
317 // Immediate mode and no wait timer? Execute the function..
318 if (callNow) func.apply(context, args);
322 export function getLanguage(): string {
323 let user = UserService.Instance.user;
324 let lang = user && user.lang ? user.lang : 'browser';
326 if (lang == 'browser') {
327 return getBrowserLanguage();
333 export function getBrowserLanguage(): string {
334 return navigator.language;
337 export function getMomentLanguage(): string {
338 let lang = getLanguage();
339 if (lang.startsWith('zh')) {
341 } else if (lang.startsWith('sv')) {
343 } else if (lang.startsWith('fr')) {
345 } else if (lang.startsWith('de')) {
347 } else if (lang.startsWith('ru')) {
349 } else if (lang.startsWith('es')) {
351 } else if (lang.startsWith('eo')) {
353 } else if (lang.startsWith('nl')) {
355 } else if (lang.startsWith('it')) {
357 } else if (lang.startsWith('fi')) {
359 } else if (lang.startsWith('ca')) {
361 } else if (lang.startsWith('fa')) {
363 } else if (lang.startsWith('pt')) {
365 } else if (lang.startsWith('ja')) {
367 } else if (lang.startsWith('ka')) {
375 export function setTheme(theme: string = 'darkly') {
376 // unload all the other themes
377 for (var i = 0; i < themes.length; i++) {
378 let styleSheet = document.getElementById(themes[i]);
380 styleSheet.setAttribute('disabled', 'disabled');
384 // Load the theme dynamically
385 if (!document.getElementById(theme)) {
386 var head = document.getElementsByTagName('head')[0];
387 var link = document.createElement('link');
389 link.rel = 'stylesheet';
390 link.type = 'text/css';
391 link.href = `/static/assets/css/themes/${theme}.min.css`;
393 head.appendChild(link);
395 document.getElementById(theme).removeAttribute('disabled');
398 export function objectFlip(obj: any) {
400 Object.keys(obj).forEach(key => {
406 export function pictshareAvatarThumbnail(src: string): string {
407 // sample url: http://localhost:8535/pictshare/gs7xuu.jpg
408 let split = src.split('pictshare');
409 let out = `${split[0]}pictshare/96${split[1]}`;
413 export function showAvatars(): boolean {
415 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
416 !UserService.Instance.user
420 // Converts to image thumbnail
421 export function pictshareImage(
423 thumbnail: boolean = false
425 let root = `/pictshare`;
427 // Necessary for other servers / domains
428 if (hash.includes('pictshare')) {
429 let split = hash.split('/pictshare/');
430 root = `${split[0]}/pictshare`;
434 let out = `${root}/${thumbnail ? '192/' : ''}${hash}`;
438 export function isCommentType(item: Comment | PrivateMessage): item is Comment {
439 return (item as Comment).community_id !== undefined;
442 export function toast(text: string, background: string = 'success') {
443 let backgroundColor = `var(--${background})`;
446 backgroundColor: backgroundColor,
452 export function messageToastify(
459 let backgroundColor = `var(--light)`;
461 let toast = Toastify({
462 text: `${body}<br />${creator}`,
464 backgroundColor: backgroundColor,
472 router.history.push(link);
478 export function setupTribute(): Tribute {
484 menuItemTemplate: (item: any) => {
485 let shortName = `:${item.original.key}:`;
486 let twemojiIcon = twemoji.parse(item.original.val);
487 return `${twemojiIcon} ${shortName}`;
489 selectTemplate: (item: any) => {
490 return `:${item.original.key}:`;
492 values: Object.entries(emojiShortName).map(e => {
493 return { key: e[1], val: e[0] };
496 autocompleteMode: true,
497 menuItemLimit: mentionDropdownFetchLimit,
498 menuShowMinLength: 2,
503 selectTemplate: (item: any) => {
504 return `[/u/${item.original.key}](/u/${item.original.key})`;
506 values: (text: string, cb: any) => {
507 userSearch(text, (users: any) => cb(users));
510 autocompleteMode: true,
511 menuItemLimit: mentionDropdownFetchLimit,
512 menuShowMinLength: 2,
518 selectTemplate: (item: any) => {
519 return `[/c/${item.original.key}](/c/${item.original.key})`;
521 values: (text: string, cb: any) => {
522 communitySearch(text, (communities: any) => cb(communities));
525 autocompleteMode: true,
526 menuItemLimit: mentionDropdownFetchLimit,
527 menuShowMinLength: 2,
533 let tippyInstance = tippy('[data-tippy-content]');
535 export function setupTippy() {
536 tippyInstance.forEach(e => e.destroy());
537 tippyInstance = tippy('[data-tippy-content]', {
539 // Display on "long press"
540 touch: ['hold', 500],
544 function userSearch(text: string, cb: any) {
546 let form: SearchForm = {
548 type_: SearchType[SearchType.Users],
549 sort: SortType[SortType.TopAll],
551 limit: mentionDropdownFetchLimit,
554 WebSocketService.Instance.search(form);
556 this.userSub = WebSocketService.Instance.subject.subscribe(
558 let res = wsJsonToRes(msg);
559 if (res.op == UserOperation.Search) {
560 let data = res.data as SearchResponse;
561 let users = data.users.map(u => {
562 return { key: u.name };
565 this.userSub.unsubscribe();
568 err => console.error(err),
569 () => console.log('complete')
576 function communitySearch(text: string, cb: any) {
578 let form: SearchForm = {
580 type_: SearchType[SearchType.Communities],
581 sort: SortType[SortType.TopAll],
583 limit: mentionDropdownFetchLimit,
586 WebSocketService.Instance.search(form);
588 this.communitySub = WebSocketService.Instance.subject.subscribe(
590 let res = wsJsonToRes(msg);
591 if (res.op == UserOperation.Search) {
592 let data = res.data as SearchResponse;
593 let communities = data.communities.map(u => {
594 return { key: u.name };
597 this.communitySub.unsubscribe();
600 err => console.error(err),
601 () => console.log('complete')
608 export function getListingTypeFromProps(props: any): ListingType {
609 return props.match.params.listing_type
610 ? routeListingTypeToEnum(props.match.params.listing_type)
611 : UserService.Instance.user
612 ? UserService.Instance.user.default_listing_type
616 // TODO might need to add a user setting for this too
617 export function getDataTypeFromProps(props: any): DataType {
618 return props.match.params.data_type
619 ? routeDataTypeToEnum(props.match.params.data_type)
623 export function getSortTypeFromProps(props: any): SortType {
624 return props.match.params.sort
625 ? routeSortTypeToEnum(props.match.params.sort)
626 : UserService.Instance.user
627 ? UserService.Instance.user.default_sort_type
631 export function getPageFromProps(props: any): number {
632 return props.match.params.page ? Number(props.match.params.page) : 1;
635 export function editCommentRes(
636 data: CommentResponse,
637 comments: Array<Comment>
639 let found = comments.find(c => c.id == data.comment.id);
641 found.content = data.comment.content;
642 found.updated = data.comment.updated;
643 found.removed = data.comment.removed;
644 found.deleted = data.comment.deleted;
645 found.upvotes = data.comment.upvotes;
646 found.downvotes = data.comment.downvotes;
647 found.score = data.comment.score;
651 export function saveCommentRes(
652 data: CommentResponse,
653 comments: Array<Comment>
655 let found = comments.find(c => c.id == data.comment.id);
657 found.saved = data.comment.saved;
661 export function createCommentLikeRes(
662 data: CommentResponse,
663 comments: Array<Comment>
665 let found: Comment = comments.find(c => c.id === data.comment.id);
667 found.score = data.comment.score;
668 found.upvotes = data.comment.upvotes;
669 found.downvotes = data.comment.downvotes;
670 if (data.comment.my_vote !== null) {
671 found.my_vote = data.comment.my_vote;
676 export function createPostLikeFindRes(data: PostResponse, posts: Array<Post>) {
677 let found = posts.find(c => c.id == data.post.id);
679 createPostLikeRes(data, found);
683 export function createPostLikeRes(data: PostResponse, post: Post) {
685 post.score = data.post.score;
686 post.upvotes = data.post.upvotes;
687 post.downvotes = data.post.downvotes;
688 if (data.post.my_vote !== null) {
689 post.my_vote = data.post.my_vote;
694 export function editPostFindRes(data: PostResponse, posts: Array<Post>) {
695 let found = posts.find(c => c.id == data.post.id);
697 editPostRes(data, found);
701 export function editPostRes(data: PostResponse, post: Post) {
703 post.url = data.post.url;
704 post.name = data.post.name;
705 post.nsfw = data.post.nsfw;
709 export function commentsToFlatNodes(
710 comments: Array<Comment>
711 ): Array<CommentNodeI> {
712 let nodes: Array<CommentNodeI> = [];
713 for (let comment of comments) {
714 nodes.push({ comment: comment });
719 export function commentSort(tree: Array<CommentNodeI>, sort: CommentSortType) {
720 // First, put removed and deleted comments at the bottom, then do your other sorts
721 if (sort == CommentSortType.Top) {
724 +a.comment.removed - +b.comment.removed ||
725 +a.comment.deleted - +b.comment.deleted ||
726 b.comment.score - a.comment.score
728 } else if (sort == CommentSortType.New) {
731 +a.comment.removed - +b.comment.removed ||
732 +a.comment.deleted - +b.comment.deleted ||
733 b.comment.published.localeCompare(a.comment.published)
735 } else if (sort == CommentSortType.Old) {
738 +a.comment.removed - +b.comment.removed ||
739 +a.comment.deleted - +b.comment.deleted ||
740 a.comment.published.localeCompare(b.comment.published)
742 } else if (sort == CommentSortType.Hot) {
745 +a.comment.removed - +b.comment.removed ||
746 +a.comment.deleted - +b.comment.deleted ||
747 hotRankComment(b.comment) - hotRankComment(a.comment)
751 // Go through the children recursively
752 for (let node of tree) {
754 commentSort(node.children, sort);
759 export function commentSortSortType(tree: Array<CommentNodeI>, sort: SortType) {
760 commentSort(tree, convertCommentSortType(sort));
763 function convertCommentSortType(sort: SortType): CommentSortType {
765 sort == SortType.TopAll ||
766 sort == SortType.TopDay ||
767 sort == SortType.TopWeek ||
768 sort == SortType.TopMonth ||
769 sort == SortType.TopYear
771 return CommentSortType.Top;
772 } else if (sort == SortType.New) {
773 return CommentSortType.New;
774 } else if (sort == SortType.Hot) {
775 return CommentSortType.Hot;
777 return CommentSortType.Hot;
781 export function postSort(
784 communityType: boolean
786 // First, put removed and deleted comments at the bottom, then do your other sorts
788 sort == SortType.TopAll ||
789 sort == SortType.TopDay ||
790 sort == SortType.TopWeek ||
791 sort == SortType.TopMonth ||
792 sort == SortType.TopYear
796 +a.removed - +b.removed ||
797 +a.deleted - +b.deleted ||
798 (communityType && +b.stickied - +a.stickied) ||
801 } else if (sort == SortType.New) {
804 +a.removed - +b.removed ||
805 +a.deleted - +b.deleted ||
806 (communityType && +b.stickied - +a.stickied) ||
807 b.published.localeCompare(a.published)
809 } else if (sort == SortType.Hot) {
812 +a.removed - +b.removed ||
813 +a.deleted - +b.deleted ||
814 (communityType && +b.stickied - +a.stickied) ||
815 hotRankPost(b) - hotRankPost(a)
820 export const colorList: Array<string> = [
829 function hsl(num: number) {
830 return `hsla(${num}, 35%, 50%, 1)`;
833 function randomHsl() {
834 return `hsla(${Math.random() * 360}, 100%, 50%, 1)`;
837 export function previewLines(text: string, lines: number = 3): string {
838 // Use lines * 2 because markdown requires 2 lines