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 markdownitEmoji from 'markdown-it-emoji/light';
53 import markdown_it_container from 'markdown-it-container';
54 import twemoji from 'twemoji';
55 import emojiShortName from 'emoji-short-name';
56 import Toastify from 'toastify-js';
57 import tippy from 'tippy.js';
58 import EmojiButton from '@joeattardi/emoji-button';
60 export const repoUrl = 'https://github.com/LemmyNet/lemmy';
61 export const helpGuideUrl = '/docs/about_guide.html';
62 export const markdownHelpUrl = `${helpGuideUrl}#markdown-guide`;
63 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
64 export const archiveUrl = 'https://archive.is';
66 export const postRefetchSeconds: number = 60 * 1000;
67 export const fetchLimit: number = 20;
68 export const mentionDropdownFetchLimit = 10;
70 export const languages = [
71 { code: 'ca', name: 'Català' },
72 { code: 'en', name: 'English' },
73 { code: 'el', name: 'Ελληνικά' },
74 { code: 'eu', name: 'Euskara' },
75 { code: 'eo', name: 'Esperanto' },
76 { code: 'es', name: 'Español' },
77 { code: 'de', name: 'Deutsch' },
78 { code: 'ga', name: 'Gaeilge' },
79 { code: 'gl', name: 'Galego' },
80 { code: 'hu', name: 'Magyar Nyelv' },
81 { code: 'ka', name: 'ქართული ენა' },
82 { code: 'km', name: 'ភាសាខ្មែរ' },
83 { code: 'hi', name: 'मानक हिन्दी' },
84 { code: 'fa', name: 'فارسی' },
85 { code: 'ja', name: '日本語' },
86 { code: 'pl', name: 'Polski' },
87 { code: 'pt_BR', name: 'Português Brasileiro' },
88 { code: 'zh', name: '中文' },
89 { code: 'fi', name: 'Suomi' },
90 { code: 'fr', name: 'Français' },
91 { code: 'sv', name: 'Svenska' },
92 { code: 'sq', name: 'Shqip' },
93 { code: 'sr_Latn', name: 'srpski' },
94 { code: 'tr', name: 'Türkçe' },
95 { code: 'uk', name: 'Українська Mова' },
96 { code: 'ru', name: 'Русский' },
97 { code: 'nl', name: 'Nederlands' },
98 { code: 'it', name: 'Italiano' },
101 export const themes = [
117 export const emojiPicker = new EmojiButton({
118 // Use the emojiShortName from native
121 position: 'auto-start',
125 const DEFAULT_ALPHABET =
126 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
128 function getRandomCharFromAlphabet(alphabet: string): string {
129 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
132 export function randomStr(
133 idDesiredLength: number = 20,
134 alphabet = DEFAULT_ALPHABET
137 * Create n-long array and map it to random chars from given alphabet.
138 * Then join individual chars as string
140 return Array.from({ length: idDesiredLength })
142 return getRandomCharFromAlphabet(alphabet);
147 export function wsJsonToRes(msg: WebSocketJsonResponse): WebSocketResponse {
148 let opStr: string = msg.op;
150 op: UserOperation[opStr],
155 export const md = new markdown_it({
160 .use(markdown_it_container, 'spoiler', {
161 validate: function (params: any) {
162 return params.trim().match(/^spoiler\s+(.*)$/);
165 render: function (tokens: any, idx: any) {
166 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
168 if (tokens[idx].nesting === 1) {
170 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
173 return '</details>\n';
177 .use(markdownitEmoji, {
178 defs: objectFlip(emojiShortName),
181 md.renderer.rules.emoji = function (token, idx) {
182 return twemoji.parse(token[idx].content);
185 export function hotRankComment(comment: Comment): number {
186 return hotRank(comment.score, comment.published);
189 export function hotRankPost(post: Post): number {
190 return hotRank(post.score, post.newest_activity_time);
193 export function hotRank(score: number, timeStr: string): number {
194 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
195 let date: Date = new Date(timeStr + 'Z'); // Add Z to convert from UTC date
196 let now: Date = new Date();
197 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
200 (10000 * Math.log10(Math.max(1, 3 + score))) /
201 Math.pow(hoursElapsed + 2, 1.8);
203 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
208 export function mdToHtml(text: string) {
209 return { __html: md.render(text) };
212 export function getUnixTime(text: string): number {
213 return text ? new Date(text).getTime() / 1000 : undefined;
216 export function addTypeInfo<T>(
219 ): Array<{ type_: string; data: T }> {
220 return arr.map(e => {
221 return { type_: name, data: e };
225 export function canMod(
227 modIds: Array<number>,
229 onSelf: boolean = false
231 // You can do moderator actions only on the mods added after you.
233 let yourIndex = modIds.findIndex(id => id == user.id);
234 if (yourIndex == -1) {
237 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
238 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
239 return !modIds.includes(creator_id);
246 export function isMod(modIds: Array<number>, creator_id: number): boolean {
247 return modIds.includes(creator_id);
250 const imageRegex = new RegExp(
251 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
253 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
255 export function isImage(url: string) {
256 return imageRegex.test(url);
259 export function isVideo(url: string) {
260 return videoRegex.test(url);
263 export function validURL(str: string) {
265 return !!new URL(str);
271 export function validEmail(email: string) {
272 let re = /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
273 return re.test(String(email).toLowerCase());
276 export function capitalizeFirstLetter(str: string): string {
277 return str.charAt(0).toUpperCase() + str.slice(1);
280 export function routeSortTypeToEnum(sort: string): SortType {
283 } else if (sort == 'hot') {
285 } else if (sort == 'topday') {
286 return SortType.TopDay;
287 } else if (sort == 'topweek') {
288 return SortType.TopWeek;
289 } else if (sort == 'topmonth') {
290 return SortType.TopMonth;
291 } else if (sort == 'topyear') {
292 return SortType.TopYear;
293 } else if (sort == 'topall') {
294 return SortType.TopAll;
298 export function routeListingTypeToEnum(type: string): ListingType {
299 return ListingType[capitalizeFirstLetter(type)];
302 export function routeDataTypeToEnum(type: string): DataType {
303 return DataType[capitalizeFirstLetter(type)];
306 export function routeSearchTypeToEnum(type: string): SearchType {
307 return SearchType[capitalizeFirstLetter(type)];
310 export async function getPageTitle(url: string) {
311 let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
312 let title = await res.title;
316 export function debounce(
319 immediate: boolean = false
321 // 'private' variable for instance
322 // The returned function will be able to reference this due to closure.
323 // Each call to the returned function will share this common timer.
326 // Calling debounce returns a new anonymous function
328 // reference the context and args for the setTimeout function
332 // Should the function be called now? If immediate is true
333 // and not already in a timeout then the answer is: Yes
334 var callNow = immediate && !timeout;
336 // This is the basic debounce behaviour where you can call this
337 // function several times, but it will only execute once
338 // [before or after imposing a delay].
339 // Each time the returned function is called, the timer starts over.
340 clearTimeout(timeout);
342 // Set the new timeout
343 timeout = setTimeout(function () {
344 // Inside the timeout function, clear the timeout variable
345 // which will let the next execution run when in 'immediate' mode
348 // Check if the function already ran with the immediate flag
350 // Call the original function with apply
351 // apply lets you define the 'this' object as well as the arguments
352 // (both captured before setTimeout)
353 func.apply(context, args);
357 // Immediate mode and no wait timer? Execute the function..
358 if (callNow) func.apply(context, args);
362 export function getLanguage(): string {
363 let user = UserService.Instance.user;
364 let lang = user && user.lang ? user.lang : 'browser';
366 if (lang == 'browser') {
367 return getBrowserLanguage();
373 export function getBrowserLanguage(): string {
374 return navigator.language;
377 export function getMomentLanguage(): string {
378 let lang = getLanguage();
379 if (lang.startsWith('zh')) {
381 } else if (lang.startsWith('sv')) {
383 } else if (lang.startsWith('fr')) {
385 } else if (lang.startsWith('de')) {
387 } else if (lang.startsWith('ru')) {
389 } else if (lang.startsWith('es')) {
391 } else if (lang.startsWith('eo')) {
393 } else if (lang.startsWith('nl')) {
395 } else if (lang.startsWith('it')) {
397 } else if (lang.startsWith('fi')) {
399 } else if (lang.startsWith('ca')) {
401 } else if (lang.startsWith('fa')) {
403 } else if (lang.startsWith('pl')) {
405 } else if (lang.startsWith('pt')) {
407 } else if (lang.startsWith('ja')) {
409 } else if (lang.startsWith('ka')) {
411 } else if (lang.startsWith('hi')) {
413 } else if (lang.startsWith('el')) {
415 } else if (lang.startsWith('eu')) {
417 } else if (lang.startsWith('gl')) {
419 } else if (lang.startsWith('tr')) {
421 } else if (lang.startsWith('hu')) {
423 } else if (lang.startsWith('uk')) {
425 } else if (lang.startsWith('sq')) {
427 } else if (lang.startsWith('km')) {
429 } else if (lang.startsWith('ga')) {
431 } else if (lang.startsWith('sr')) {
439 export function setTheme(theme: string = 'darkly', loggedIn: boolean = false) {
440 // unload all the other themes
441 for (var i = 0; i < themes.length; i++) {
442 let styleSheet = document.getElementById(themes[i]);
444 styleSheet.setAttribute('disabled', 'disabled');
448 // if the user is not logged in, we load the default themes and let the browser decide
450 document.getElementById('default-light').removeAttribute('disabled');
451 document.getElementById('default-dark').removeAttribute('disabled');
454 .getElementById('default-light')
455 .setAttribute('disabled', 'disabled');
457 .getElementById('default-dark')
458 .setAttribute('disabled', 'disabled');
460 // Load the theme dynamically
461 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
462 loadCss(theme, cssLoc);
463 document.getElementById(theme).removeAttribute('disabled');
467 export function loadCss(id: string, loc: string) {
468 if (!document.getElementById(id)) {
469 var head = document.getElementsByTagName('head')[0];
470 var link = document.createElement('link');
472 link.rel = 'stylesheet';
473 link.type = 'text/css';
476 head.appendChild(link);
480 export function objectFlip(obj: any) {
482 Object.keys(obj).forEach(key => {
488 export function pictrsAvatarThumbnail(src: string): string {
489 // sample url: http://localhost:8535/pictrs/image/thumbnail256/gs7xuu.jpg
490 let split = src.split('/pictrs/image');
491 let out = `${split[0]}/pictrs/image/${
492 canUseWebP() ? 'webp/' : ''
493 }thumbnail96${split[1]}`;
497 export function showAvatars(): boolean {
499 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
500 !UserService.Instance.user
504 // Converts to image thumbnail
505 export function pictrsImage(hash: string, thumbnail: boolean = false): string {
506 let root = `/pictrs/image`;
508 // Necessary for other servers / domains
509 if (hash.includes('pictrs')) {
510 let split = hash.split('/pictrs/image/');
511 root = `${split[0]}/pictrs/image`;
515 let out = `${root}/${canUseWebP() ? 'webp/' : ''}${
516 thumbnail ? 'thumbnail256/' : ''
521 export function isCommentType(item: Comment | PrivateMessage): item is Comment {
522 return (item as Comment).community_id !== undefined;
525 export function toast(text: string, background: string = 'success') {
526 let backgroundColor = `var(--${background})`;
529 backgroundColor: backgroundColor,
535 export function pictrsDeleteToast(
536 clickToDeleteText: string,
537 deletePictureText: string,
540 let backgroundColor = `var(--light)`;
541 let toast = Toastify({
542 text: clickToDeleteText,
543 backgroundColor: backgroundColor,
549 window.location.replace(deleteUrl);
550 alert(deletePictureText);
558 export function messageToastify(
565 let backgroundColor = `var(--light)`;
567 let toast = Toastify({
568 text: `${body}<br />${creator}`,
570 backgroundColor: backgroundColor,
571 className: 'text-dark',
579 router.history.push(link);
585 export function setupTribute(): Tribute {
591 menuItemTemplate: (item: any) => {
592 let shortName = `:${item.original.key}:`;
593 let twemojiIcon = twemoji.parse(item.original.val);
594 return `${twemojiIcon} ${shortName}`;
596 selectTemplate: (item: any) => {
597 return `:${item.original.key}:`;
599 values: Object.entries(emojiShortName).map(e => {
600 return { key: e[1], val: e[0] };
603 autocompleteMode: true,
604 menuItemLimit: mentionDropdownFetchLimit,
605 menuShowMinLength: 2,
610 selectTemplate: (item: any) => {
611 let link = item.original.local
612 ? `[${item.original.key}](/u/${item.original.name})`
613 : `[${item.original.key}](/user/${item.original.id})`;
616 values: (text: string, cb: any) => {
617 userSearch(text, (users: any) => cb(users));
620 autocompleteMode: true,
621 menuItemLimit: mentionDropdownFetchLimit,
622 menuShowMinLength: 2,
628 selectTemplate: (item: any) => {
629 let link = item.original.local
630 ? `[${item.original.key}](/c/${item.original.name})`
631 : `[${item.original.key}](/community/${item.original.id})`;
634 values: (text: string, cb: any) => {
635 communitySearch(text, (communities: any) => cb(communities));
638 autocompleteMode: true,
639 menuItemLimit: mentionDropdownFetchLimit,
640 menuShowMinLength: 2,
646 let tippyInstance = tippy('[data-tippy-content]');
648 export function setupTippy() {
649 tippyInstance.forEach(e => e.destroy());
650 tippyInstance = tippy('[data-tippy-content]', {
652 // Display on "long press"
653 touch: ['hold', 500],
657 function userSearch(text: string, cb: any) {
659 let form: SearchForm = {
661 type_: SearchType[SearchType.Users],
662 sort: SortType[SortType.TopAll],
664 limit: mentionDropdownFetchLimit,
667 WebSocketService.Instance.search(form);
669 this.userSub = WebSocketService.Instance.subject.subscribe(
671 let res = wsJsonToRes(msg);
672 if (res.op == UserOperation.Search) {
673 let data = res.data as SearchResponse;
674 let users = data.users.map(u => {
676 key: `@${u.name}@${hostname(u.actor_id)}`,
683 this.userSub.unsubscribe();
686 err => console.error(err),
687 () => console.log('complete')
694 function communitySearch(text: string, cb: any) {
696 let form: SearchForm = {
698 type_: SearchType[SearchType.Communities],
699 sort: SortType[SortType.TopAll],
701 limit: mentionDropdownFetchLimit,
704 WebSocketService.Instance.search(form);
706 this.communitySub = WebSocketService.Instance.subject.subscribe(
708 let res = wsJsonToRes(msg);
709 if (res.op == UserOperation.Search) {
710 let data = res.data as SearchResponse;
711 let communities = data.communities.map(c => {
713 key: `!${c.name}@${hostname(c.actor_id)}`,
720 this.communitySub.unsubscribe();
723 err => console.error(err),
724 () => console.log('complete')
731 export function getListingTypeFromProps(props: any): ListingType {
732 return props.match.params.listing_type
733 ? routeListingTypeToEnum(props.match.params.listing_type)
734 : UserService.Instance.user
735 ? UserService.Instance.user.default_listing_type
739 // TODO might need to add a user setting for this too
740 export function getDataTypeFromProps(props: any): DataType {
741 return props.match.params.data_type
742 ? routeDataTypeToEnum(props.match.params.data_type)
746 export function getSortTypeFromProps(props: any): SortType {
747 return props.match.params.sort
748 ? routeSortTypeToEnum(props.match.params.sort)
749 : UserService.Instance.user
750 ? UserService.Instance.user.default_sort_type
754 export function getPageFromProps(props: any): number {
755 return props.match.params.page ? Number(props.match.params.page) : 1;
758 export function editCommentRes(
759 data: CommentResponse,
760 comments: Array<Comment>
762 let found = comments.find(c => c.id == data.comment.id);
764 found.content = data.comment.content;
765 found.updated = data.comment.updated;
766 found.removed = data.comment.removed;
767 found.deleted = data.comment.deleted;
768 found.upvotes = data.comment.upvotes;
769 found.downvotes = data.comment.downvotes;
770 found.score = data.comment.score;
774 export function saveCommentRes(
775 data: CommentResponse,
776 comments: Array<Comment>
778 let found = comments.find(c => c.id == data.comment.id);
780 found.saved = data.comment.saved;
784 export function createCommentLikeRes(
785 data: CommentResponse,
786 comments: Array<Comment>
788 let found: Comment = comments.find(c => c.id === data.comment.id);
790 found.score = data.comment.score;
791 found.upvotes = data.comment.upvotes;
792 found.downvotes = data.comment.downvotes;
793 if (data.comment.my_vote !== null) {
794 found.my_vote = data.comment.my_vote;
799 export function createPostLikeFindRes(data: PostResponse, posts: Array<Post>) {
800 let found = posts.find(c => c.id == data.post.id);
802 createPostLikeRes(data, found);
806 export function createPostLikeRes(data: PostResponse, post: Post) {
808 post.score = data.post.score;
809 post.upvotes = data.post.upvotes;
810 post.downvotes = data.post.downvotes;
811 if (data.post.my_vote !== null) {
812 post.my_vote = data.post.my_vote;
817 export function editPostFindRes(data: PostResponse, posts: Array<Post>) {
818 let found = posts.find(c => c.id == data.post.id);
820 editPostRes(data, found);
824 export function editPostRes(data: PostResponse, post: Post) {
826 post.url = data.post.url;
827 post.name = data.post.name;
828 post.nsfw = data.post.nsfw;
832 export function commentsToFlatNodes(
833 comments: Array<Comment>
834 ): Array<CommentNodeI> {
835 let nodes: Array<CommentNodeI> = [];
836 for (let comment of comments) {
837 nodes.push({ comment: comment });
842 export function commentSort(tree: Array<CommentNodeI>, sort: CommentSortType) {
843 // First, put removed and deleted comments at the bottom, then do your other sorts
844 if (sort == CommentSortType.Top) {
847 +a.comment.removed - +b.comment.removed ||
848 +a.comment.deleted - +b.comment.deleted ||
849 b.comment.score - a.comment.score
851 } else if (sort == CommentSortType.New) {
854 +a.comment.removed - +b.comment.removed ||
855 +a.comment.deleted - +b.comment.deleted ||
856 b.comment.published.localeCompare(a.comment.published)
858 } else if (sort == CommentSortType.Old) {
861 +a.comment.removed - +b.comment.removed ||
862 +a.comment.deleted - +b.comment.deleted ||
863 a.comment.published.localeCompare(b.comment.published)
865 } else if (sort == CommentSortType.Hot) {
868 +a.comment.removed - +b.comment.removed ||
869 +a.comment.deleted - +b.comment.deleted ||
870 hotRankComment(b.comment) - hotRankComment(a.comment)
874 // Go through the children recursively
875 for (let node of tree) {
877 commentSort(node.children, sort);
882 export function commentSortSortType(tree: Array<CommentNodeI>, sort: SortType) {
883 commentSort(tree, convertCommentSortType(sort));
886 function convertCommentSortType(sort: SortType): CommentSortType {
888 sort == SortType.TopAll ||
889 sort == SortType.TopDay ||
890 sort == SortType.TopWeek ||
891 sort == SortType.TopMonth ||
892 sort == SortType.TopYear
894 return CommentSortType.Top;
895 } else if (sort == SortType.New) {
896 return CommentSortType.New;
897 } else if (sort == SortType.Hot) {
898 return CommentSortType.Hot;
900 return CommentSortType.Hot;
904 export function postSort(
907 communityType: boolean
909 // First, put removed and deleted comments at the bottom, then do your other sorts
911 sort == SortType.TopAll ||
912 sort == SortType.TopDay ||
913 sort == SortType.TopWeek ||
914 sort == SortType.TopMonth ||
915 sort == SortType.TopYear
919 +a.removed - +b.removed ||
920 +a.deleted - +b.deleted ||
921 (communityType && +b.stickied - +a.stickied) ||
924 } else if (sort == SortType.New) {
927 +a.removed - +b.removed ||
928 +a.deleted - +b.deleted ||
929 (communityType && +b.stickied - +a.stickied) ||
930 b.published.localeCompare(a.published)
932 } else if (sort == SortType.Hot) {
935 +a.removed - +b.removed ||
936 +a.deleted - +b.deleted ||
937 (communityType && +b.stickied - +a.stickied) ||
938 b.hot_rank - a.hot_rank
943 export const colorList: Array<string> = [
952 function hsl(num: number) {
953 return `hsla(${num}, 35%, 50%, 1)`;
956 function randomHsl() {
957 return `hsla(${Math.random() * 360}, 100%, 50%, 1)`;
960 export function previewLines(text: string, lines: number = 3): string {
961 // Use lines * 2 because markdown requires 2 lines
968 export function hostname(url: string): string {
969 let cUrl = new URL(url);
970 return window.location.port
971 ? `${cUrl.hostname}:${cUrl.port}`
972 : `${cUrl.hostname}`;
975 function canUseWebP() {
976 // TODO pictshare might have a webp conversion bug, try disabling this
979 // var elem = document.createElement('canvas');
980 // if (!!(elem.getContext && elem.getContext('2d'))) {
981 // var testString = !(window.mozInnerScreenX == null) ? 'png' : 'webp';
982 // // was able or not to get WebP representation
984 // elem.toDataURL('image/webp').startsWith('data:image/' + testString)
988 // // very old browser like IE 8, canvas not supported