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';
28 CommentNode as CommentNodeI,
38 WebSocketJsonResponse,
43 } from './interfaces';
44 import { UserService, WebSocketService } from './services';
46 import Tribute from 'tributejs/src/Tribute.js';
47 import markdown_it from 'markdown-it';
48 import markdownitEmoji from 'markdown-it-emoji/light';
49 import markdown_it_container from 'markdown-it-container';
50 import twemoji from 'twemoji';
51 import emojiShortName from 'emoji-short-name';
52 import Toastify from 'toastify-js';
53 import tippy from 'tippy.js';
54 import EmojiButton from '@joeattardi/emoji-button';
56 export const repoUrl = 'https://github.com/LemmyNet/lemmy';
57 export const helpGuideUrl = '/docs/about_guide.html';
58 export const markdownHelpUrl = `${helpGuideUrl}#markdown-guide`;
59 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
60 export const archiveUrl = 'https://archive.is';
62 export const postRefetchSeconds: number = 60 * 1000;
63 export const fetchLimit: number = 20;
64 export const mentionDropdownFetchLimit = 10;
66 export const languages = [
67 { code: 'ca', name: 'Català' },
68 { code: 'en', name: 'English' },
69 { code: 'el', name: 'Ελληνικά' },
70 { code: 'eu', name: 'Euskara' },
71 { code: 'eo', name: 'Esperanto' },
72 { code: 'es', name: 'Español' },
73 { code: 'de', name: 'Deutsch' },
74 { code: 'gl', name: 'Galego' },
75 { code: 'hu', name: 'Magyar Nyelv' },
76 { code: 'ka', name: 'ქართული ენა' },
77 { code: 'hi', name: 'मानक हिन्दी' },
78 { code: 'fa', name: 'فارسی' },
79 { code: 'ja', name: '日本語' },
80 { code: 'pl', name: 'Polski' },
81 { code: 'pt_BR', name: 'Português Brasileiro' },
82 { code: 'zh', name: '中文' },
83 { code: 'fi', name: 'Suomi' },
84 { code: 'fr', name: 'Français' },
85 { code: 'sv', name: 'Svenska' },
86 { code: 'tr', name: 'Türkçe' },
87 { code: 'uk', name: 'українська мова' },
88 { code: 'ru', name: 'Русский' },
89 { code: 'nl', name: 'Nederlands' },
90 { code: 'it', name: 'Italiano' },
93 export const themes = [
109 export const emojiPicker = new EmojiButton({
110 // Use the emojiShortName from native
113 position: 'auto-start',
117 export function randomStr() {
120 .replace(/[^a-z]+/g, '')
124 export function wsJsonToRes(msg: WebSocketJsonResponse): WebSocketResponse {
125 let opStr: string = msg.op;
127 op: UserOperation[opStr],
132 export const md = new markdown_it({
137 .use(markdown_it_container, 'spoiler', {
138 validate: function (params: any) {
139 return params.trim().match(/^spoiler\s+(.*)$/);
142 render: function (tokens: any, idx: any) {
143 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
145 if (tokens[idx].nesting === 1) {
147 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
150 return '</details>\n';
154 .use(markdownitEmoji, {
155 defs: objectFlip(emojiShortName),
158 md.renderer.rules.emoji = function (token, idx) {
159 return twemoji.parse(token[idx].content);
162 export function hotRankComment(comment: Comment): number {
163 return hotRank(comment.score, comment.published);
166 export function hotRankPost(post: Post): number {
167 return hotRank(post.score, post.newest_activity_time);
170 export function hotRank(score: number, timeStr: string): number {
171 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
172 let date: Date = new Date(timeStr + 'Z'); // Add Z to convert from UTC date
173 let now: Date = new Date();
174 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
177 (10000 * Math.log10(Math.max(1, 3 + score))) /
178 Math.pow(hoursElapsed + 2, 1.8);
180 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
185 export function mdToHtml(text: string) {
186 return { __html: md.render(text) };
189 export function getUnixTime(text: string): number {
190 return text ? new Date(text).getTime() / 1000 : undefined;
193 export function addTypeInfo<T>(
196 ): Array<{ type_: string; data: T }> {
197 return arr.map(e => {
198 return { type_: name, data: e };
202 export function canMod(
204 modIds: Array<number>,
206 onSelf: boolean = false
208 // You can do moderator actions only on the mods added after you.
210 let yourIndex = modIds.findIndex(id => id == user.id);
211 if (yourIndex == -1) {
214 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
215 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
216 return !modIds.includes(creator_id);
223 export function isMod(modIds: Array<number>, creator_id: number): boolean {
224 return modIds.includes(creator_id);
227 const imageRegex = new RegExp(
228 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
230 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
232 export function isImage(url: string) {
233 return imageRegex.test(url);
236 export function isVideo(url: string) {
237 return videoRegex.test(url);
240 export function validURL(str: string) {
242 return !!new URL(str);
248 export function validEmail(email: string) {
249 let re = /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
250 return re.test(String(email).toLowerCase());
253 export function capitalizeFirstLetter(str: string): string {
254 return str.charAt(0).toUpperCase() + str.slice(1);
257 export function routeSortTypeToEnum(sort: string): SortType {
260 } else if (sort == 'hot') {
262 } else if (sort == 'topday') {
263 return SortType.TopDay;
264 } else if (sort == 'topweek') {
265 return SortType.TopWeek;
266 } else if (sort == 'topmonth') {
267 return SortType.TopMonth;
268 } else if (sort == 'topyear') {
269 return SortType.TopYear;
270 } else if (sort == 'topall') {
271 return SortType.TopAll;
275 export function routeListingTypeToEnum(type: string): ListingType {
276 return ListingType[capitalizeFirstLetter(type)];
279 export function routeDataTypeToEnum(type: string): DataType {
280 return DataType[capitalizeFirstLetter(type)];
283 export function routeSearchTypeToEnum(type: string): SearchType {
284 return SearchType[capitalizeFirstLetter(type)];
287 export async function getPageTitle(url: string) {
288 let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
289 let title = await res.title;
293 export function debounce(
296 immediate: boolean = false
298 // 'private' variable for instance
299 // The returned function will be able to reference this due to closure.
300 // Each call to the returned function will share this common timer.
303 // Calling debounce returns a new anonymous function
305 // reference the context and args for the setTimeout function
309 // Should the function be called now? If immediate is true
310 // and not already in a timeout then the answer is: Yes
311 var callNow = immediate && !timeout;
313 // This is the basic debounce behaviour where you can call this
314 // function several times, but it will only execute once
315 // [before or after imposing a delay].
316 // Each time the returned function is called, the timer starts over.
317 clearTimeout(timeout);
319 // Set the new timeout
320 timeout = setTimeout(function () {
321 // Inside the timeout function, clear the timeout variable
322 // which will let the next execution run when in 'immediate' mode
325 // Check if the function already ran with the immediate flag
327 // Call the original function with apply
328 // apply lets you define the 'this' object as well as the arguments
329 // (both captured before setTimeout)
330 func.apply(context, args);
334 // Immediate mode and no wait timer? Execute the function..
335 if (callNow) func.apply(context, args);
339 export function getLanguage(): string {
340 let user = UserService.Instance.user;
341 let lang = user && user.lang ? user.lang : 'browser';
343 if (lang == 'browser') {
344 return getBrowserLanguage();
350 export function getBrowserLanguage(): string {
351 return navigator.language;
354 export function getMomentLanguage(): string {
355 let lang = getLanguage();
356 if (lang.startsWith('zh')) {
358 } else if (lang.startsWith('sv')) {
360 } else if (lang.startsWith('fr')) {
362 } else if (lang.startsWith('de')) {
364 } else if (lang.startsWith('ru')) {
366 } else if (lang.startsWith('es')) {
368 } else if (lang.startsWith('eo')) {
370 } else if (lang.startsWith('nl')) {
372 } else if (lang.startsWith('it')) {
374 } else if (lang.startsWith('fi')) {
376 } else if (lang.startsWith('ca')) {
378 } else if (lang.startsWith('fa')) {
380 } else if (lang.startsWith('pl')) {
382 } else if (lang.startsWith('pt')) {
384 } else if (lang.startsWith('ja')) {
386 } else if (lang.startsWith('ka')) {
388 } else if (lang.startsWith('hi')) {
390 } else if (lang.startsWith('el')) {
392 } else if (lang.startsWith('eu')) {
394 } else if (lang.startsWith('gl')) {
396 } else if (lang.startsWith('tr')) {
398 } else if (lang.startsWith('hu')) {
400 } else if (lang.startsWith('uk')) {
408 export function setTheme(theme: string = 'darkly', loggedIn: boolean = false) {
409 // unload all the other themes
410 for (var i = 0; i < themes.length; i++) {
411 let styleSheet = document.getElementById(themes[i]);
413 styleSheet.setAttribute('disabled', 'disabled');
417 // if the user is not logged in, we load the default themes and let the browser decide
419 document.getElementById('default-light').removeAttribute('disabled');
420 document.getElementById('default-dark').removeAttribute('disabled');
423 .getElementById('default-light')
424 .setAttribute('disabled', 'disabled');
426 .getElementById('default-dark')
427 .setAttribute('disabled', 'disabled');
429 // Load the theme dynamically
430 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
431 loadCss(theme, cssLoc);
432 document.getElementById(theme).removeAttribute('disabled');
436 export function loadCss(id: string, loc: string) {
437 if (!document.getElementById(id)) {
438 var head = document.getElementsByTagName('head')[0];
439 var link = document.createElement('link');
441 link.rel = 'stylesheet';
442 link.type = 'text/css';
445 head.appendChild(link);
449 export function objectFlip(obj: any) {
451 Object.keys(obj).forEach(key => {
457 export function pictrsAvatarThumbnail(src: string): string {
458 // sample url: http://localhost:8535/pictrs/image/thumbnail256/gs7xuu.jpg
459 let split = src.split('/pictrs/image');
460 let out = `${split[0]}/pictrs/image/${
461 canUseWebP() ? 'webp/' : ''
462 }thumbnail96${split[1]}`;
466 export function showAvatars(): boolean {
468 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
469 !UserService.Instance.user
473 // Converts to image thumbnail
474 export function pictrsImage(hash: string, thumbnail: boolean = false): string {
475 let root = `/pictrs/image`;
477 // Necessary for other servers / domains
478 if (hash.includes('pictrs')) {
479 let split = hash.split('/pictrs/image/');
480 root = `${split[0]}/pictrs/image`;
484 let out = `${root}/${canUseWebP() ? 'webp/' : ''}${
485 thumbnail ? 'thumbnail256/' : ''
490 export function isCommentType(item: Comment | PrivateMessage): item is Comment {
491 return (item as Comment).community_id !== undefined;
494 export function toast(text: string, background: string = 'success') {
495 let backgroundColor = `var(--${background})`;
498 backgroundColor: backgroundColor,
504 export function pictrsDeleteToast(
505 clickToDeleteText: string,
506 deletePictureText: string,
509 let backgroundColor = `var(--light)`;
510 let toast = Toastify({
511 text: clickToDeleteText,
512 backgroundColor: backgroundColor,
518 window.location.replace(deleteUrl);
519 alert(deletePictureText);
527 export function messageToastify(
534 let backgroundColor = `var(--light)`;
536 let toast = Toastify({
537 text: `${body}<br />${creator}`,
539 backgroundColor: backgroundColor,
540 className: 'text-dark',
548 router.history.push(link);
554 export function setupTribute(): Tribute {
560 menuItemTemplate: (item: any) => {
561 let shortName = `:${item.original.key}:`;
562 let twemojiIcon = twemoji.parse(item.original.val);
563 return `${twemojiIcon} ${shortName}`;
565 selectTemplate: (item: any) => {
566 return `:${item.original.key}:`;
568 values: Object.entries(emojiShortName).map(e => {
569 return { key: e[1], val: e[0] };
572 autocompleteMode: true,
573 menuItemLimit: mentionDropdownFetchLimit,
574 menuShowMinLength: 2,
579 selectTemplate: (item: any) => {
580 return `[/u/${item.original.key}](/u/${item.original.key})`;
582 values: (text: string, cb: any) => {
583 userSearch(text, (users: any) => cb(users));
586 autocompleteMode: true,
587 menuItemLimit: mentionDropdownFetchLimit,
588 menuShowMinLength: 2,
594 selectTemplate: (item: any) => {
595 return `[/c/${item.original.key}](/c/${item.original.key})`;
597 values: (text: string, cb: any) => {
598 communitySearch(text, (communities: any) => cb(communities));
601 autocompleteMode: true,
602 menuItemLimit: mentionDropdownFetchLimit,
603 menuShowMinLength: 2,
609 let tippyInstance = tippy('[data-tippy-content]');
611 export function setupTippy() {
612 tippyInstance.forEach(e => e.destroy());
613 tippyInstance = tippy('[data-tippy-content]', {
615 // Display on "long press"
616 touch: ['hold', 500],
620 function userSearch(text: string, cb: any) {
622 let form: SearchForm = {
624 type_: SearchType[SearchType.Users],
625 sort: SortType[SortType.TopAll],
627 limit: mentionDropdownFetchLimit,
630 WebSocketService.Instance.search(form);
632 this.userSub = WebSocketService.Instance.subject.subscribe(
634 let res = wsJsonToRes(msg);
635 if (res.op == UserOperation.Search) {
636 let data = res.data as SearchResponse;
637 let users = data.users.map(u => {
638 return { key: u.name };
641 this.userSub.unsubscribe();
644 err => console.error(err),
645 () => console.log('complete')
652 function communitySearch(text: string, cb: any) {
654 let form: SearchForm = {
656 type_: SearchType[SearchType.Communities],
657 sort: SortType[SortType.TopAll],
659 limit: mentionDropdownFetchLimit,
662 WebSocketService.Instance.search(form);
664 this.communitySub = WebSocketService.Instance.subject.subscribe(
666 let res = wsJsonToRes(msg);
667 if (res.op == UserOperation.Search) {
668 let data = res.data as SearchResponse;
669 let communities = data.communities.map(u => {
670 return { key: u.name };
673 this.communitySub.unsubscribe();
676 err => console.error(err),
677 () => console.log('complete')
684 export function getListingTypeFromProps(props: any): ListingType {
685 return props.match.params.listing_type
686 ? routeListingTypeToEnum(props.match.params.listing_type)
687 : UserService.Instance.user
688 ? UserService.Instance.user.default_listing_type
692 // TODO might need to add a user setting for this too
693 export function getDataTypeFromProps(props: any): DataType {
694 return props.match.params.data_type
695 ? routeDataTypeToEnum(props.match.params.data_type)
699 export function getSortTypeFromProps(props: any): SortType {
700 return props.match.params.sort
701 ? routeSortTypeToEnum(props.match.params.sort)
702 : UserService.Instance.user
703 ? UserService.Instance.user.default_sort_type
707 export function getPageFromProps(props: any): number {
708 return props.match.params.page ? Number(props.match.params.page) : 1;
711 export function editCommentRes(
712 data: CommentResponse,
713 comments: Array<Comment>
715 let found = comments.find(c => c.id == data.comment.id);
717 found.content = data.comment.content;
718 found.updated = data.comment.updated;
719 found.removed = data.comment.removed;
720 found.deleted = data.comment.deleted;
721 found.upvotes = data.comment.upvotes;
722 found.downvotes = data.comment.downvotes;
723 found.score = data.comment.score;
727 export function saveCommentRes(
728 data: CommentResponse,
729 comments: Array<Comment>
731 let found = comments.find(c => c.id == data.comment.id);
733 found.saved = data.comment.saved;
737 export function createCommentLikeRes(
738 data: CommentResponse,
739 comments: Array<Comment>
741 let found: Comment = comments.find(c => c.id === data.comment.id);
743 found.score = data.comment.score;
744 found.upvotes = data.comment.upvotes;
745 found.downvotes = data.comment.downvotes;
746 if (data.comment.my_vote !== null) {
747 found.my_vote = data.comment.my_vote;
752 export function createPostLikeFindRes(data: PostResponse, posts: Array<Post>) {
753 let found = posts.find(c => c.id == data.post.id);
755 createPostLikeRes(data, found);
759 export function createPostLikeRes(data: PostResponse, post: Post) {
761 post.score = data.post.score;
762 post.upvotes = data.post.upvotes;
763 post.downvotes = data.post.downvotes;
764 if (data.post.my_vote !== null) {
765 post.my_vote = data.post.my_vote;
770 export function editPostFindRes(data: PostResponse, posts: Array<Post>) {
771 let found = posts.find(c => c.id == data.post.id);
773 editPostRes(data, found);
777 export function editPostRes(data: PostResponse, post: Post) {
779 post.url = data.post.url;
780 post.name = data.post.name;
781 post.nsfw = data.post.nsfw;
785 export function commentsToFlatNodes(
786 comments: Array<Comment>
787 ): Array<CommentNodeI> {
788 let nodes: Array<CommentNodeI> = [];
789 for (let comment of comments) {
790 nodes.push({ comment: comment });
795 export function commentSort(tree: Array<CommentNodeI>, sort: CommentSortType) {
796 // First, put removed and deleted comments at the bottom, then do your other sorts
797 if (sort == CommentSortType.Top) {
800 +a.comment.removed - +b.comment.removed ||
801 +a.comment.deleted - +b.comment.deleted ||
802 b.comment.score - a.comment.score
804 } else if (sort == CommentSortType.New) {
807 +a.comment.removed - +b.comment.removed ||
808 +a.comment.deleted - +b.comment.deleted ||
809 b.comment.published.localeCompare(a.comment.published)
811 } else if (sort == CommentSortType.Old) {
814 +a.comment.removed - +b.comment.removed ||
815 +a.comment.deleted - +b.comment.deleted ||
816 a.comment.published.localeCompare(b.comment.published)
818 } else if (sort == CommentSortType.Hot) {
821 +a.comment.removed - +b.comment.removed ||
822 +a.comment.deleted - +b.comment.deleted ||
823 hotRankComment(b.comment) - hotRankComment(a.comment)
827 // Go through the children recursively
828 for (let node of tree) {
830 commentSort(node.children, sort);
835 export function commentSortSortType(tree: Array<CommentNodeI>, sort: SortType) {
836 commentSort(tree, convertCommentSortType(sort));
839 function convertCommentSortType(sort: SortType): CommentSortType {
841 sort == SortType.TopAll ||
842 sort == SortType.TopDay ||
843 sort == SortType.TopWeek ||
844 sort == SortType.TopMonth ||
845 sort == SortType.TopYear
847 return CommentSortType.Top;
848 } else if (sort == SortType.New) {
849 return CommentSortType.New;
850 } else if (sort == SortType.Hot) {
851 return CommentSortType.Hot;
853 return CommentSortType.Hot;
857 export function postSort(
860 communityType: boolean
862 // First, put removed and deleted comments at the bottom, then do your other sorts
864 sort == SortType.TopAll ||
865 sort == SortType.TopDay ||
866 sort == SortType.TopWeek ||
867 sort == SortType.TopMonth ||
868 sort == SortType.TopYear
872 +a.removed - +b.removed ||
873 +a.deleted - +b.deleted ||
874 (communityType && +b.stickied - +a.stickied) ||
877 } else if (sort == SortType.New) {
880 +a.removed - +b.removed ||
881 +a.deleted - +b.deleted ||
882 (communityType && +b.stickied - +a.stickied) ||
883 b.published.localeCompare(a.published)
885 } else if (sort == SortType.Hot) {
888 +a.removed - +b.removed ||
889 +a.deleted - +b.deleted ||
890 (communityType && +b.stickied - +a.stickied) ||
891 hotRankPost(b) - hotRankPost(a)
896 export const colorList: Array<string> = [
905 function hsl(num: number) {
906 return `hsla(${num}, 35%, 50%, 1)`;
909 function randomHsl() {
910 return `hsla(${Math.random() * 360}, 100%, 50%, 1)`;
913 export function previewLines(text: string, lines: number = 3): string {
914 // Use lines * 2 because markdown requires 2 lines
921 function canUseWebP() {
922 // TODO pictshare might have a webp conversion bug, try disabling this
925 // var elem = document.createElement('canvas');
926 // if (!!(elem.getContext && elem.getContext('2d'))) {
927 // var testString = !(window.mozInnerScreenX == null) ? 'png' : 'webp';
928 // // was able or not to get WebP representation
930 // elem.toDataURL('image/webp').startsWith('data:image/' + testString)
934 // // very old browser like IE 8, canvas not supported