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';
24 import 'moment/locale/sq';
25 import 'moment/locale/km';
26 import 'moment/locale/ga';
27 import 'moment/locale/sr';
32 CommentNode as CommentNodeI,
42 WebSocketJsonResponse,
47 } from './interfaces';
48 import { UserService, WebSocketService } from './services';
50 import Tribute from 'tributejs/src/Tribute.js';
51 import markdown_it from 'markdown-it';
52 import markdown_it_sub from 'markdown-it-sub';
53 import markdown_it_sup from 'markdown-it-sup';
54 import markdownitEmoji from 'markdown-it-emoji/light';
55 import markdown_it_container from 'markdown-it-container';
56 import emojiShortName from 'emoji-short-name';
57 import Toastify from 'toastify-js';
58 import tippy from 'tippy.js';
59 import moment from 'moment';
61 export const repoUrl = 'https://github.com/LemmyNet/lemmy';
62 export const helpGuideUrl = '/docs/about_guide.html';
63 export const markdownHelpUrl = `${helpGuideUrl}#markdown-guide`;
64 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
65 export const archiveUrl = 'https://archive.is';
67 export const postRefetchSeconds: number = 60 * 1000;
68 export const fetchLimit: number = 20;
69 export const mentionDropdownFetchLimit = 10;
71 export const languages = [
72 { code: 'ca', name: 'Català' },
73 { code: 'en', name: 'English' },
74 { code: 'el', name: 'Ελληνικά' },
75 { code: 'eu', name: 'Euskara' },
76 { code: 'eo', name: 'Esperanto' },
77 { code: 'es', name: 'Español' },
78 { code: 'de', name: 'Deutsch' },
79 { code: 'ga', name: 'Gaeilge' },
80 { code: 'gl', name: 'Galego' },
81 { code: 'hu', name: 'Magyar Nyelv' },
82 { code: 'ka', name: 'ქართული ენა' },
83 { code: 'km', name: 'ភាសាខ្មែរ' },
84 { code: 'hi', name: 'मानक हिन्दी' },
85 { code: 'fa', name: 'فارسی' },
86 { code: 'ja', name: '日本語' },
87 { code: 'pl', name: 'Polski' },
88 { code: 'pt_BR', name: 'Português Brasileiro' },
89 { code: 'zh', name: '中文' },
90 { code: 'fi', name: 'Suomi' },
91 { code: 'fr', name: 'Français' },
92 { code: 'sv', name: 'Svenska' },
93 { code: 'sq', name: 'Shqip' },
94 { code: 'sr_Latn', name: 'srpski' },
95 { code: 'tr', name: 'Türkçe' },
96 { code: 'uk', name: 'Українська Mова' },
97 { code: 'ru', name: 'Русский' },
98 { code: 'nl', name: 'Nederlands' },
99 { code: 'it', name: 'Italiano' },
102 export const themes = [
118 const DEFAULT_ALPHABET =
119 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
121 function getRandomCharFromAlphabet(alphabet: string): string {
122 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
125 export function randomStr(
126 idDesiredLength: number = 20,
127 alphabet = DEFAULT_ALPHABET
130 * Create n-long array and map it to random chars from given alphabet.
131 * Then join individual chars as string
133 return Array.from({ length: idDesiredLength })
135 return getRandomCharFromAlphabet(alphabet);
140 export function wsJsonToRes(msg: WebSocketJsonResponse): WebSocketResponse {
141 let opStr: string = msg.op;
143 op: UserOperation[opStr],
148 export const md = new markdown_it({
153 .use(markdown_it_sub)
154 .use(markdown_it_sup)
155 .use(markdown_it_container, 'spoiler', {
156 validate: function (params: any) {
157 return params.trim().match(/^spoiler\s+(.*)$/);
160 render: function (tokens: any, idx: any) {
161 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
163 if (tokens[idx].nesting === 1) {
165 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
168 return '</details>\n';
172 .use(markdownitEmoji, {
173 defs: objectFlip(emojiShortName),
176 export function hotRankComment(comment: Comment): number {
177 return hotRank(comment.score, comment.published);
180 export function hotRankPost(post: Post): number {
181 return hotRank(post.score, post.newest_activity_time);
184 export function hotRank(score: number, timeStr: string): number {
185 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
186 let date: Date = new Date(timeStr + 'Z'); // Add Z to convert from UTC date
187 let now: Date = new Date();
188 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
191 (10000 * Math.log10(Math.max(1, 3 + score))) /
192 Math.pow(hoursElapsed + 2, 1.8);
194 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
199 export function mdToHtml(text: string) {
200 return { __html: md.render(text) };
203 export function getUnixTime(text: string): number {
204 return text ? new Date(text).getTime() / 1000 : undefined;
207 export function addTypeInfo<T>(
210 ): Array<{ type_: string; data: T }> {
211 return arr.map(e => {
212 return { type_: name, data: e };
216 export function canMod(
218 modIds: Array<number>,
220 onSelf: boolean = false
222 // You can do moderator actions only on the mods added after you.
224 let yourIndex = modIds.findIndex(id => id == user.id);
225 if (yourIndex == -1) {
228 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
229 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
230 return !modIds.includes(creator_id);
237 export function isMod(modIds: Array<number>, creator_id: number): boolean {
238 return modIds.includes(creator_id);
241 const imageRegex = new RegExp(
242 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
244 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
246 export function isImage(url: string) {
247 return imageRegex.test(url);
250 export function isVideo(url: string) {
251 return videoRegex.test(url);
254 export function validURL(str: string) {
256 return !!new URL(str);
262 export function validEmail(email: string) {
263 let re = /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
264 return re.test(String(email).toLowerCase());
267 export function capitalizeFirstLetter(str: string): string {
268 return str.charAt(0).toUpperCase() + str.slice(1);
271 export function routeSortTypeToEnum(sort: string): SortType {
274 } else if (sort == 'hot') {
276 } else if (sort == 'topday') {
277 return SortType.TopDay;
278 } else if (sort == 'topweek') {
279 return SortType.TopWeek;
280 } else if (sort == 'topmonth') {
281 return SortType.TopMonth;
282 } else if (sort == 'topyear') {
283 return SortType.TopYear;
284 } else if (sort == 'topall') {
285 return SortType.TopAll;
289 export function routeListingTypeToEnum(type: string): ListingType {
290 return ListingType[capitalizeFirstLetter(type)];
293 export function routeDataTypeToEnum(type: string): DataType {
294 return DataType[capitalizeFirstLetter(type)];
297 export function routeSearchTypeToEnum(type: string): SearchType {
298 return SearchType[capitalizeFirstLetter(type)];
301 export async function getPageTitle(url: string) {
302 let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
303 let title = await res.title;
307 export function debounce(
310 immediate: boolean = false
312 // 'private' variable for instance
313 // The returned function will be able to reference this due to closure.
314 // Each call to the returned function will share this common timer.
317 // Calling debounce returns a new anonymous function
319 // reference the context and args for the setTimeout function
323 // Should the function be called now? If immediate is true
324 // and not already in a timeout then the answer is: Yes
325 var callNow = immediate && !timeout;
327 // This is the basic debounce behaviour where you can call this
328 // function several times, but it will only execute once
329 // [before or after imposing a delay].
330 // Each time the returned function is called, the timer starts over.
331 clearTimeout(timeout);
333 // Set the new timeout
334 timeout = setTimeout(function () {
335 // Inside the timeout function, clear the timeout variable
336 // which will let the next execution run when in 'immediate' mode
339 // Check if the function already ran with the immediate flag
341 // Call the original function with apply
342 // apply lets you define the 'this' object as well as the arguments
343 // (both captured before setTimeout)
344 func.apply(context, args);
348 // Immediate mode and no wait timer? Execute the function..
349 if (callNow) func.apply(context, args);
353 export function getLanguage(override?: string): string {
354 let user = UserService.Instance.user;
355 let lang = override || (user && user.lang ? user.lang : 'browser');
357 if (lang == 'browser') {
358 return getBrowserLanguage();
364 export function getBrowserLanguage(): string {
365 return navigator.language;
368 export function getMomentLanguage(): string {
369 let lang = getLanguage();
370 if (lang.startsWith('zh')) {
372 } else if (lang.startsWith('sv')) {
374 } else if (lang.startsWith('fr')) {
376 } else if (lang.startsWith('de')) {
378 } else if (lang.startsWith('ru')) {
380 } else if (lang.startsWith('es')) {
382 } else if (lang.startsWith('eo')) {
384 } else if (lang.startsWith('nl')) {
386 } else if (lang.startsWith('it')) {
388 } else if (lang.startsWith('fi')) {
390 } else if (lang.startsWith('ca')) {
392 } else if (lang.startsWith('fa')) {
394 } else if (lang.startsWith('pl')) {
396 } else if (lang.startsWith('pt')) {
398 } else if (lang.startsWith('ja')) {
400 } else if (lang.startsWith('ka')) {
402 } else if (lang.startsWith('hi')) {
404 } else if (lang.startsWith('el')) {
406 } else if (lang.startsWith('eu')) {
408 } else if (lang.startsWith('gl')) {
410 } else if (lang.startsWith('tr')) {
412 } else if (lang.startsWith('hu')) {
414 } else if (lang.startsWith('uk')) {
416 } else if (lang.startsWith('sq')) {
418 } else if (lang.startsWith('km')) {
420 } else if (lang.startsWith('ga')) {
422 } else if (lang.startsWith('sr')) {
430 export function setTheme(theme: string = 'darkly', loggedIn: boolean = false) {
431 // unload all the other themes
432 for (var i = 0; i < themes.length; i++) {
433 let styleSheet = document.getElementById(themes[i]);
435 styleSheet.setAttribute('disabled', 'disabled');
439 // if the user is not logged in, we load the default themes and let the browser decide
441 document.getElementById('default-light').removeAttribute('disabled');
442 document.getElementById('default-dark').removeAttribute('disabled');
445 .getElementById('default-light')
446 .setAttribute('disabled', 'disabled');
448 .getElementById('default-dark')
449 .setAttribute('disabled', 'disabled');
451 // Load the theme dynamically
452 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
453 loadCss(theme, cssLoc);
454 document.getElementById(theme).removeAttribute('disabled');
458 export function loadCss(id: string, loc: string) {
459 if (!document.getElementById(id)) {
460 var head = document.getElementsByTagName('head')[0];
461 var link = document.createElement('link');
463 link.rel = 'stylesheet';
464 link.type = 'text/css';
467 head.appendChild(link);
471 export function objectFlip(obj: any) {
473 Object.keys(obj).forEach(key => {
479 export function pictrsAvatarThumbnail(src: string): string {
480 // sample url: http://localhost:8535/pictrs/image/thumbnail256/gs7xuu.jpg
481 let split = src.split('/pictrs/image');
482 let out = `${split[0]}/pictrs/image/${
483 canUseWebP() ? 'webp/' : ''
484 }thumbnail96${split[1]}`;
488 export function showAvatars(): boolean {
490 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
491 !UserService.Instance.user
495 export function isCakeDay(published: string): boolean {
496 // moment(undefined) or moment.utc(undefined) returns the current date/time
497 // moment(null) or moment.utc(null) returns null
498 const userCreationDate = moment.utc(published || null).local();
499 const currentDate = moment(new Date());
502 userCreationDate.date() === currentDate.date() &&
503 userCreationDate.month() === currentDate.month() &&
504 userCreationDate.year() !== currentDate.year()
508 // Converts to image thumbnail
509 export function pictrsImage(hash: string, thumbnail: boolean = false): string {
510 let root = `/pictrs/image`;
512 // Necessary for other servers / domains
513 if (hash.includes('pictrs')) {
514 let split = hash.split('/pictrs/image/');
515 root = `${split[0]}/pictrs/image`;
519 let out = `${root}/${canUseWebP() ? 'webp/' : ''}${
520 thumbnail ? 'thumbnail256/' : ''
525 export function isCommentType(item: Comment | PrivateMessage): item is Comment {
526 return (item as Comment).community_id !== undefined;
529 export function toast(text: string, background: string = 'success') {
530 let backgroundColor = `var(--${background})`;
533 backgroundColor: backgroundColor,
539 export function pictrsDeleteToast(
540 clickToDeleteText: string,
541 deletePictureText: string,
544 let backgroundColor = `var(--light)`;
545 let toast = Toastify({
546 text: clickToDeleteText,
547 backgroundColor: backgroundColor,
553 window.location.replace(deleteUrl);
554 alert(deletePictureText);
562 export function messageToastify(
569 let backgroundColor = `var(--light)`;
571 let toast = Toastify({
572 text: `${body}<br />${creator}`,
574 backgroundColor: backgroundColor,
575 className: 'text-dark',
583 router.history.push(link);
589 export function setupTribute(): Tribute {
591 noMatchTemplate: function () {
598 menuItemTemplate: (item: any) => {
599 let shortName = `:${item.original.key}:`;
600 return `${item.original.val} ${shortName}`;
602 selectTemplate: (item: any) => {
603 return `:${item.original.key}:`;
605 values: Object.entries(emojiShortName).map(e => {
606 return { key: e[1], val: e[0] };
609 autocompleteMode: true,
610 menuItemLimit: mentionDropdownFetchLimit,
611 menuShowMinLength: 2,
616 selectTemplate: (item: any) => {
617 let link = item.original.local
618 ? `[${item.original.key}](/u/${item.original.name})`
619 : `[${item.original.key}](/user/${item.original.id})`;
622 values: (text: string, cb: any) => {
623 userSearch(text, (users: any) => cb(users));
626 autocompleteMode: true,
627 menuItemLimit: mentionDropdownFetchLimit,
628 menuShowMinLength: 2,
634 selectTemplate: (item: any) => {
635 let link = item.original.local
636 ? `[${item.original.key}](/c/${item.original.name})`
637 : `[${item.original.key}](/community/${item.original.id})`;
640 values: (text: string, cb: any) => {
641 communitySearch(text, (communities: any) => cb(communities));
644 autocompleteMode: true,
645 menuItemLimit: mentionDropdownFetchLimit,
646 menuShowMinLength: 2,
652 let tippyInstance = tippy('[data-tippy-content]');
654 export function setupTippy() {
655 tippyInstance.forEach(e => e.destroy());
656 tippyInstance = tippy('[data-tippy-content]', {
658 // Display on "long press"
659 touch: ['hold', 500],
663 function userSearch(text: string, cb: any) {
665 let form: SearchForm = {
667 type_: SearchType[SearchType.Users],
668 sort: SortType[SortType.TopAll],
670 limit: mentionDropdownFetchLimit,
673 WebSocketService.Instance.search(form);
675 let userSub = WebSocketService.Instance.subject.subscribe(
677 let res = wsJsonToRes(msg);
678 if (res.op == UserOperation.Search) {
679 let data = res.data as SearchResponse;
680 let users = data.users.map(u => {
682 key: `@${u.name}@${hostname(u.actor_id)}`,
689 userSub.unsubscribe();
692 err => console.error(err),
693 () => console.log('complete')
700 function communitySearch(text: string, cb: any) {
702 let form: SearchForm = {
704 type_: SearchType[SearchType.Communities],
705 sort: SortType[SortType.TopAll],
707 limit: mentionDropdownFetchLimit,
710 WebSocketService.Instance.search(form);
712 let communitySub = WebSocketService.Instance.subject.subscribe(
714 let res = wsJsonToRes(msg);
715 if (res.op == UserOperation.Search) {
716 let data = res.data as SearchResponse;
717 let communities = data.communities.map(c => {
719 key: `!${c.name}@${hostname(c.actor_id)}`,
726 communitySub.unsubscribe();
729 err => console.error(err),
730 () => console.log('complete')
737 export function getListingTypeFromProps(props: any): ListingType {
738 return props.match.params.listing_type
739 ? routeListingTypeToEnum(props.match.params.listing_type)
740 : UserService.Instance.user
741 ? UserService.Instance.user.default_listing_type
745 // TODO might need to add a user setting for this too
746 export function getDataTypeFromProps(props: any): DataType {
747 return props.match.params.data_type
748 ? routeDataTypeToEnum(props.match.params.data_type)
752 export function getSortTypeFromProps(props: any): SortType {
753 return props.match.params.sort
754 ? routeSortTypeToEnum(props.match.params.sort)
755 : UserService.Instance.user
756 ? UserService.Instance.user.default_sort_type
760 export function getPageFromProps(props: any): number {
761 return props.match.params.page ? Number(props.match.params.page) : 1;
764 export function editCommentRes(
765 data: CommentResponse,
766 comments: Array<Comment>
768 let found = comments.find(c => c.id == data.comment.id);
770 found.content = data.comment.content;
771 found.updated = data.comment.updated;
772 found.removed = data.comment.removed;
773 found.deleted = data.comment.deleted;
774 found.upvotes = data.comment.upvotes;
775 found.downvotes = data.comment.downvotes;
776 found.score = data.comment.score;
780 export function saveCommentRes(
781 data: CommentResponse,
782 comments: Array<Comment>
784 let found = comments.find(c => c.id == data.comment.id);
786 found.saved = data.comment.saved;
790 export function createCommentLikeRes(
791 data: CommentResponse,
792 comments: Array<Comment>
794 let found: Comment = comments.find(c => c.id === data.comment.id);
796 found.score = data.comment.score;
797 found.upvotes = data.comment.upvotes;
798 found.downvotes = data.comment.downvotes;
799 if (data.comment.my_vote !== null) {
800 found.my_vote = data.comment.my_vote;
805 export function createPostLikeFindRes(data: PostResponse, posts: Array<Post>) {
806 let found = posts.find(c => c.id == data.post.id);
808 createPostLikeRes(data, found);
812 export function createPostLikeRes(data: PostResponse, post: Post) {
814 post.score = data.post.score;
815 post.upvotes = data.post.upvotes;
816 post.downvotes = data.post.downvotes;
817 if (data.post.my_vote !== null) {
818 post.my_vote = data.post.my_vote;
823 export function editPostFindRes(data: PostResponse, posts: Array<Post>) {
824 let found = posts.find(c => c.id == data.post.id);
826 editPostRes(data, found);
830 export function editPostRes(data: PostResponse, post: Post) {
832 post.url = data.post.url;
833 post.name = data.post.name;
834 post.nsfw = data.post.nsfw;
835 post.deleted = data.post.deleted;
836 post.removed = data.post.removed;
837 post.stickied = data.post.stickied;
838 post.body = data.post.body;
839 post.locked = data.post.locked;
843 export function commentsToFlatNodes(
844 comments: Array<Comment>
845 ): Array<CommentNodeI> {
846 let nodes: Array<CommentNodeI> = [];
847 for (let comment of comments) {
848 nodes.push({ comment: comment });
853 export function commentSort(tree: Array<CommentNodeI>, sort: CommentSortType) {
854 // First, put removed and deleted comments at the bottom, then do your other sorts
855 if (sort == CommentSortType.Top) {
858 +a.comment.removed - +b.comment.removed ||
859 +a.comment.deleted - +b.comment.deleted ||
860 b.comment.score - a.comment.score
862 } else if (sort == CommentSortType.New) {
865 +a.comment.removed - +b.comment.removed ||
866 +a.comment.deleted - +b.comment.deleted ||
867 b.comment.published.localeCompare(a.comment.published)
869 } else if (sort == CommentSortType.Old) {
872 +a.comment.removed - +b.comment.removed ||
873 +a.comment.deleted - +b.comment.deleted ||
874 a.comment.published.localeCompare(b.comment.published)
876 } else if (sort == CommentSortType.Hot) {
879 +a.comment.removed - +b.comment.removed ||
880 +a.comment.deleted - +b.comment.deleted ||
881 hotRankComment(b.comment) - hotRankComment(a.comment)
885 // Go through the children recursively
886 for (let node of tree) {
888 commentSort(node.children, sort);
893 export function commentSortSortType(tree: Array<CommentNodeI>, sort: SortType) {
894 commentSort(tree, convertCommentSortType(sort));
897 function convertCommentSortType(sort: SortType): CommentSortType {
899 sort == SortType.TopAll ||
900 sort == SortType.TopDay ||
901 sort == SortType.TopWeek ||
902 sort == SortType.TopMonth ||
903 sort == SortType.TopYear
905 return CommentSortType.Top;
906 } else if (sort == SortType.New) {
907 return CommentSortType.New;
908 } else if (sort == SortType.Hot) {
909 return CommentSortType.Hot;
911 return CommentSortType.Hot;
915 export function postSort(
918 communityType: boolean
920 // First, put removed and deleted comments at the bottom, then do your other sorts
922 sort == SortType.TopAll ||
923 sort == SortType.TopDay ||
924 sort == SortType.TopWeek ||
925 sort == SortType.TopMonth ||
926 sort == SortType.TopYear
930 +a.removed - +b.removed ||
931 +a.deleted - +b.deleted ||
932 (communityType && +b.stickied - +a.stickied) ||
935 } else if (sort == SortType.New) {
938 +a.removed - +b.removed ||
939 +a.deleted - +b.deleted ||
940 (communityType && +b.stickied - +a.stickied) ||
941 b.published.localeCompare(a.published)
943 } else if (sort == SortType.Hot) {
946 +a.removed - +b.removed ||
947 +a.deleted - +b.deleted ||
948 (communityType && +b.stickied - +a.stickied) ||
949 b.hot_rank - a.hot_rank
954 export const colorList: Array<string> = [
963 function hsl(num: number) {
964 return `hsla(${num}, 35%, 50%, 1)`;
967 function randomHsl() {
968 return `hsla(${Math.random() * 360}, 100%, 50%, 1)`;
971 export function previewLines(text: string, lines: number = 3): string {
972 // Use lines * 2 because markdown requires 2 lines
979 export function hostname(url: string): string {
980 let cUrl = new URL(url);
981 return window.location.port
982 ? `${cUrl.hostname}:${cUrl.port}`
983 : `${cUrl.hostname}`;
986 function canUseWebP() {
987 // TODO pictshare might have a webp conversion bug, try disabling this
990 // var elem = document.createElement('canvas');
991 // if (!!(elem.getContext && elem.getContext('2d'))) {
992 // var testString = !(window.mozInnerScreenX == null) ? 'png' : 'webp';
993 // // was able or not to get WebP representation
995 // elem.toDataURL('image/webp').startsWith('data:image/' + testString)
999 // // very old browser like IE 8, canvas not supported
1003 export function validTitle(title?: string): boolean {
1004 // Initial title is null, minimum length is taken care of by textarea's minLength={3}
1005 if (title === null || title.length < 3) return true;
1007 const regex = new RegExp(/.*\S.*/, 'g');
1009 return regex.test(title);