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 const DEFAULT_ALPHABET =
118 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
120 function getRandomCharFromAlphabet(alphabet: string): string {
121 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
124 export function randomStr(
125 idDesiredLength: number = 20,
126 alphabet = DEFAULT_ALPHABET
129 * Create n-long array and map it to random chars from given alphabet.
130 * Then join individual chars as string
132 return Array.from({ length: idDesiredLength })
134 return getRandomCharFromAlphabet(alphabet);
139 export function wsJsonToRes(msg: WebSocketJsonResponse): WebSocketResponse {
140 let opStr: string = msg.op;
142 op: UserOperation[opStr],
147 export const md = new markdown_it({
152 .use(markdown_it_container, 'spoiler', {
153 validate: function (params: any) {
154 return params.trim().match(/^spoiler\s+(.*)$/);
157 render: function (tokens: any, idx: any) {
158 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
160 if (tokens[idx].nesting === 1) {
162 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
165 return '</details>\n';
169 .use(markdownitEmoji, {
170 defs: objectFlip(emojiShortName),
173 md.renderer.rules.emoji = function (token, idx) {
174 return twemoji.parse(token[idx].content);
177 export function hotRankComment(comment: Comment): number {
178 return hotRank(comment.score, comment.published);
181 export function hotRankPost(post: Post): number {
182 return hotRank(post.score, post.newest_activity_time);
185 export function hotRank(score: number, timeStr: string): number {
186 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
187 let date: Date = new Date(timeStr + 'Z'); // Add Z to convert from UTC date
188 let now: Date = new Date();
189 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
192 (10000 * Math.log10(Math.max(1, 3 + score))) /
193 Math.pow(hoursElapsed + 2, 1.8);
195 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
200 export function mdToHtml(text: string) {
201 return { __html: md.render(text) };
204 export function getUnixTime(text: string): number {
205 return text ? new Date(text).getTime() / 1000 : undefined;
208 export function addTypeInfo<T>(
211 ): Array<{ type_: string; data: T }> {
212 return arr.map(e => {
213 return { type_: name, data: e };
217 export function canMod(
219 modIds: Array<number>,
221 onSelf: boolean = false
223 // You can do moderator actions only on the mods added after you.
225 let yourIndex = modIds.findIndex(id => id == user.id);
226 if (yourIndex == -1) {
229 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
230 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
231 return !modIds.includes(creator_id);
238 export function isMod(modIds: Array<number>, creator_id: number): boolean {
239 return modIds.includes(creator_id);
242 const imageRegex = new RegExp(
243 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
245 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
247 export function isImage(url: string) {
248 return imageRegex.test(url);
251 export function isVideo(url: string) {
252 return videoRegex.test(url);
255 export function validURL(str: string) {
257 return !!new URL(str);
263 export function validEmail(email: string) {
264 let re = /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
265 return re.test(String(email).toLowerCase());
268 export function capitalizeFirstLetter(str: string): string {
269 return str.charAt(0).toUpperCase() + str.slice(1);
272 export function routeSortTypeToEnum(sort: string): SortType {
275 } else if (sort == 'hot') {
277 } else if (sort == 'topday') {
278 return SortType.TopDay;
279 } else if (sort == 'topweek') {
280 return SortType.TopWeek;
281 } else if (sort == 'topmonth') {
282 return SortType.TopMonth;
283 } else if (sort == 'topyear') {
284 return SortType.TopYear;
285 } else if (sort == 'topall') {
286 return SortType.TopAll;
290 export function routeListingTypeToEnum(type: string): ListingType {
291 return ListingType[capitalizeFirstLetter(type)];
294 export function routeDataTypeToEnum(type: string): DataType {
295 return DataType[capitalizeFirstLetter(type)];
298 export function routeSearchTypeToEnum(type: string): SearchType {
299 return SearchType[capitalizeFirstLetter(type)];
302 export async function getPageTitle(url: string) {
303 let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
304 let title = await res.title;
308 export function debounce(
311 immediate: boolean = false
313 // 'private' variable for instance
314 // The returned function will be able to reference this due to closure.
315 // Each call to the returned function will share this common timer.
318 // Calling debounce returns a new anonymous function
320 // reference the context and args for the setTimeout function
324 // Should the function be called now? If immediate is true
325 // and not already in a timeout then the answer is: Yes
326 var callNow = immediate && !timeout;
328 // This is the basic debounce behaviour where you can call this
329 // function several times, but it will only execute once
330 // [before or after imposing a delay].
331 // Each time the returned function is called, the timer starts over.
332 clearTimeout(timeout);
334 // Set the new timeout
335 timeout = setTimeout(function () {
336 // Inside the timeout function, clear the timeout variable
337 // which will let the next execution run when in 'immediate' mode
340 // Check if the function already ran with the immediate flag
342 // Call the original function with apply
343 // apply lets you define the 'this' object as well as the arguments
344 // (both captured before setTimeout)
345 func.apply(context, args);
349 // Immediate mode and no wait timer? Execute the function..
350 if (callNow) func.apply(context, args);
354 export function getLanguage(): string {
355 let user = UserService.Instance.user;
356 let lang = user && user.lang ? user.lang : 'browser';
358 if (lang == 'browser') {
359 return getBrowserLanguage();
365 export function getBrowserLanguage(): string {
366 return navigator.language;
369 export function getMomentLanguage(): string {
370 let lang = getLanguage();
371 if (lang.startsWith('zh')) {
373 } else if (lang.startsWith('sv')) {
375 } else if (lang.startsWith('fr')) {
377 } else if (lang.startsWith('de')) {
379 } else if (lang.startsWith('ru')) {
381 } else if (lang.startsWith('es')) {
383 } else if (lang.startsWith('eo')) {
385 } else if (lang.startsWith('nl')) {
387 } else if (lang.startsWith('it')) {
389 } else if (lang.startsWith('fi')) {
391 } else if (lang.startsWith('ca')) {
393 } else if (lang.startsWith('fa')) {
395 } else if (lang.startsWith('pl')) {
397 } else if (lang.startsWith('pt')) {
399 } else if (lang.startsWith('ja')) {
401 } else if (lang.startsWith('ka')) {
403 } else if (lang.startsWith('hi')) {
405 } else if (lang.startsWith('el')) {
407 } else if (lang.startsWith('eu')) {
409 } else if (lang.startsWith('gl')) {
411 } else if (lang.startsWith('tr')) {
413 } else if (lang.startsWith('hu')) {
415 } else if (lang.startsWith('uk')) {
423 export function setTheme(theme: string = 'darkly', loggedIn: boolean = false) {
424 // unload all the other themes
425 for (var i = 0; i < themes.length; i++) {
426 let styleSheet = document.getElementById(themes[i]);
428 styleSheet.setAttribute('disabled', 'disabled');
432 // if the user is not logged in, we load the default themes and let the browser decide
434 document.getElementById('default-light').removeAttribute('disabled');
435 document.getElementById('default-dark').removeAttribute('disabled');
438 .getElementById('default-light')
439 .setAttribute('disabled', 'disabled');
441 .getElementById('default-dark')
442 .setAttribute('disabled', 'disabled');
444 // Load the theme dynamically
445 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
446 loadCss(theme, cssLoc);
447 document.getElementById(theme).removeAttribute('disabled');
451 export function loadCss(id: string, loc: string) {
452 if (!document.getElementById(id)) {
453 var head = document.getElementsByTagName('head')[0];
454 var link = document.createElement('link');
456 link.rel = 'stylesheet';
457 link.type = 'text/css';
460 head.appendChild(link);
464 export function objectFlip(obj: any) {
466 Object.keys(obj).forEach(key => {
472 export function pictrsAvatarThumbnail(src: string): string {
473 // sample url: http://localhost:8535/pictrs/image/thumbnail256/gs7xuu.jpg
474 let split = src.split('/pictrs/image');
475 let out = `${split[0]}/pictrs/image/${
476 canUseWebP() ? 'webp/' : ''
477 }thumbnail96${split[1]}`;
481 export function showAvatars(): boolean {
483 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
484 !UserService.Instance.user
488 // Converts to image thumbnail
489 export function pictrsImage(hash: string, thumbnail: boolean = false): string {
490 let root = `/pictrs/image`;
492 // Necessary for other servers / domains
493 if (hash.includes('pictrs')) {
494 let split = hash.split('/pictrs/image/');
495 root = `${split[0]}/pictrs/image`;
499 let out = `${root}/${canUseWebP() ? 'webp/' : ''}${
500 thumbnail ? 'thumbnail256/' : ''
505 export function isCommentType(item: Comment | PrivateMessage): item is Comment {
506 return (item as Comment).community_id !== undefined;
509 export function toast(text: string, background: string = 'success') {
510 let backgroundColor = `var(--${background})`;
513 backgroundColor: backgroundColor,
519 export function pictrsDeleteToast(
520 clickToDeleteText: string,
521 deletePictureText: string,
524 let backgroundColor = `var(--light)`;
525 let toast = Toastify({
526 text: clickToDeleteText,
527 backgroundColor: backgroundColor,
533 window.location.replace(deleteUrl);
534 alert(deletePictureText);
542 export function messageToastify(
549 let backgroundColor = `var(--light)`;
551 let toast = Toastify({
552 text: `${body}<br />${creator}`,
554 backgroundColor: backgroundColor,
555 className: 'text-dark',
563 router.history.push(link);
569 export function setupTribute(): Tribute {
575 menuItemTemplate: (item: any) => {
576 let shortName = `:${item.original.key}:`;
577 let twemojiIcon = twemoji.parse(item.original.val);
578 return `${twemojiIcon} ${shortName}`;
580 selectTemplate: (item: any) => {
581 return `:${item.original.key}:`;
583 values: Object.entries(emojiShortName).map(e => {
584 return { key: e[1], val: e[0] };
587 autocompleteMode: true,
588 menuItemLimit: mentionDropdownFetchLimit,
589 menuShowMinLength: 2,
594 selectTemplate: (item: any) => {
595 let link = item.original.local
596 ? `[${item.original.key}](/u/${item.original.name})`
597 : `[${item.original.key}](/user/${item.original.id})`;
600 values: (text: string, cb: any) => {
601 userSearch(text, (users: any) => cb(users));
604 autocompleteMode: true,
605 menuItemLimit: mentionDropdownFetchLimit,
606 menuShowMinLength: 2,
612 selectTemplate: (item: any) => {
613 let link = item.original.local
614 ? `[${item.original.key}](/c/${item.original.name})`
615 : `[${item.original.key}](/community/${item.original.id})`;
618 values: (text: string, cb: any) => {
619 communitySearch(text, (communities: any) => cb(communities));
622 autocompleteMode: true,
623 menuItemLimit: mentionDropdownFetchLimit,
624 menuShowMinLength: 2,
630 let tippyInstance = tippy('[data-tippy-content]');
632 export function setupTippy() {
633 tippyInstance.forEach(e => e.destroy());
634 tippyInstance = tippy('[data-tippy-content]', {
636 // Display on "long press"
637 touch: ['hold', 500],
641 function userSearch(text: string, cb: any) {
643 let form: SearchForm = {
645 type_: SearchType[SearchType.Users],
646 sort: SortType[SortType.TopAll],
648 limit: mentionDropdownFetchLimit,
651 WebSocketService.Instance.search(form);
653 this.userSub = WebSocketService.Instance.subject.subscribe(
655 let res = wsJsonToRes(msg);
656 if (res.op == UserOperation.Search) {
657 let data = res.data as SearchResponse;
658 let users = data.users.map(u => {
660 key: `@${u.name}@${hostname(u.actor_id)}`,
667 this.userSub.unsubscribe();
670 err => console.error(err),
671 () => console.log('complete')
678 function communitySearch(text: string, cb: any) {
680 let form: SearchForm = {
682 type_: SearchType[SearchType.Communities],
683 sort: SortType[SortType.TopAll],
685 limit: mentionDropdownFetchLimit,
688 WebSocketService.Instance.search(form);
690 this.communitySub = WebSocketService.Instance.subject.subscribe(
692 let res = wsJsonToRes(msg);
693 if (res.op == UserOperation.Search) {
694 let data = res.data as SearchResponse;
695 let communities = data.communities.map(c => {
697 key: `!${c.name}@${hostname(c.actor_id)}`,
704 this.communitySub.unsubscribe();
707 err => console.error(err),
708 () => console.log('complete')
715 export function getListingTypeFromProps(props: any): ListingType {
716 return props.match.params.listing_type
717 ? routeListingTypeToEnum(props.match.params.listing_type)
718 : UserService.Instance.user
719 ? UserService.Instance.user.default_listing_type
723 // TODO might need to add a user setting for this too
724 export function getDataTypeFromProps(props: any): DataType {
725 return props.match.params.data_type
726 ? routeDataTypeToEnum(props.match.params.data_type)
730 export function getSortTypeFromProps(props: any): SortType {
731 return props.match.params.sort
732 ? routeSortTypeToEnum(props.match.params.sort)
733 : UserService.Instance.user
734 ? UserService.Instance.user.default_sort_type
738 export function getPageFromProps(props: any): number {
739 return props.match.params.page ? Number(props.match.params.page) : 1;
742 export function editCommentRes(
743 data: CommentResponse,
744 comments: Array<Comment>
746 let found = comments.find(c => c.id == data.comment.id);
748 found.content = data.comment.content;
749 found.updated = data.comment.updated;
750 found.removed = data.comment.removed;
751 found.deleted = data.comment.deleted;
752 found.upvotes = data.comment.upvotes;
753 found.downvotes = data.comment.downvotes;
754 found.score = data.comment.score;
758 export function saveCommentRes(
759 data: CommentResponse,
760 comments: Array<Comment>
762 let found = comments.find(c => c.id == data.comment.id);
764 found.saved = data.comment.saved;
768 export function createCommentLikeRes(
769 data: CommentResponse,
770 comments: Array<Comment>
772 let found: Comment = comments.find(c => c.id === data.comment.id);
774 found.score = data.comment.score;
775 found.upvotes = data.comment.upvotes;
776 found.downvotes = data.comment.downvotes;
777 if (data.comment.my_vote !== null) {
778 found.my_vote = data.comment.my_vote;
783 export function createPostLikeFindRes(data: PostResponse, posts: Array<Post>) {
784 let found = posts.find(c => c.id == data.post.id);
786 createPostLikeRes(data, found);
790 export function createPostLikeRes(data: PostResponse, post: Post) {
792 post.score = data.post.score;
793 post.upvotes = data.post.upvotes;
794 post.downvotes = data.post.downvotes;
795 if (data.post.my_vote !== null) {
796 post.my_vote = data.post.my_vote;
801 export function editPostFindRes(data: PostResponse, posts: Array<Post>) {
802 let found = posts.find(c => c.id == data.post.id);
804 editPostRes(data, found);
808 export function editPostRes(data: PostResponse, post: Post) {
810 post.url = data.post.url;
811 post.name = data.post.name;
812 post.nsfw = data.post.nsfw;
816 export function commentsToFlatNodes(
817 comments: Array<Comment>
818 ): Array<CommentNodeI> {
819 let nodes: Array<CommentNodeI> = [];
820 for (let comment of comments) {
821 nodes.push({ comment: comment });
826 export function commentSort(tree: Array<CommentNodeI>, sort: CommentSortType) {
827 // First, put removed and deleted comments at the bottom, then do your other sorts
828 if (sort == CommentSortType.Top) {
831 +a.comment.removed - +b.comment.removed ||
832 +a.comment.deleted - +b.comment.deleted ||
833 b.comment.score - a.comment.score
835 } else if (sort == CommentSortType.New) {
838 +a.comment.removed - +b.comment.removed ||
839 +a.comment.deleted - +b.comment.deleted ||
840 b.comment.published.localeCompare(a.comment.published)
842 } else if (sort == CommentSortType.Old) {
845 +a.comment.removed - +b.comment.removed ||
846 +a.comment.deleted - +b.comment.deleted ||
847 a.comment.published.localeCompare(b.comment.published)
849 } else if (sort == CommentSortType.Hot) {
852 +a.comment.removed - +b.comment.removed ||
853 +a.comment.deleted - +b.comment.deleted ||
854 hotRankComment(b.comment) - hotRankComment(a.comment)
858 // Go through the children recursively
859 for (let node of tree) {
861 commentSort(node.children, sort);
866 export function commentSortSortType(tree: Array<CommentNodeI>, sort: SortType) {
867 commentSort(tree, convertCommentSortType(sort));
870 function convertCommentSortType(sort: SortType): CommentSortType {
872 sort == SortType.TopAll ||
873 sort == SortType.TopDay ||
874 sort == SortType.TopWeek ||
875 sort == SortType.TopMonth ||
876 sort == SortType.TopYear
878 return CommentSortType.Top;
879 } else if (sort == SortType.New) {
880 return CommentSortType.New;
881 } else if (sort == SortType.Hot) {
882 return CommentSortType.Hot;
884 return CommentSortType.Hot;
888 export function postSort(
891 communityType: boolean
893 // First, put removed and deleted comments at the bottom, then do your other sorts
895 sort == SortType.TopAll ||
896 sort == SortType.TopDay ||
897 sort == SortType.TopWeek ||
898 sort == SortType.TopMonth ||
899 sort == SortType.TopYear
903 +a.removed - +b.removed ||
904 +a.deleted - +b.deleted ||
905 (communityType && +b.stickied - +a.stickied) ||
908 } else if (sort == SortType.New) {
911 +a.removed - +b.removed ||
912 +a.deleted - +b.deleted ||
913 (communityType && +b.stickied - +a.stickied) ||
914 b.published.localeCompare(a.published)
916 } else if (sort == SortType.Hot) {
919 +a.removed - +b.removed ||
920 +a.deleted - +b.deleted ||
921 (communityType && +b.stickied - +a.stickied) ||
922 hotRankPost(b) - hotRankPost(a)
927 export const colorList: Array<string> = [
936 function hsl(num: number) {
937 return `hsla(${num}, 35%, 50%, 1)`;
940 function randomHsl() {
941 return `hsla(${Math.random() * 360}, 100%, 50%, 1)`;
944 export function previewLines(text: string, lines: number = 3): string {
945 // Use lines * 2 because markdown requires 2 lines
952 export function hostname(url: string): string {
953 let cUrl = new URL(url);
954 return window.location.port
955 ? `${cUrl.hostname}:${cUrl.port}`
956 : `${cUrl.hostname}`;
959 function canUseWebP() {
960 // TODO pictshare might have a webp conversion bug, try disabling this
963 // var elem = document.createElement('canvas');
964 // if (!!(elem.getContext && elem.getContext('2d'))) {
965 // var testString = !(window.mozInnerScreenX == null) ? 'png' : 'webp';
966 // // was able or not to get WebP representation
968 // elem.toDataURL('image/webp').startsWith('data:image/' + testString)
972 // // very old browser like IE 8, canvas not supported