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 emojiShortName from 'emoji-short-name';
55 import Toastify from 'toastify-js';
56 import tippy from 'tippy.js';
57 import moment from 'moment';
59 export const repoUrl = 'https://github.com/LemmyNet/lemmy';
60 export const helpGuideUrl = '/docs/about_guide.html';
61 export const markdownHelpUrl = `${helpGuideUrl}#markdown-guide`;
62 export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
63 export const archiveUrl = 'https://archive.is';
65 export const postRefetchSeconds: number = 60 * 1000;
66 export const fetchLimit: number = 20;
67 export const mentionDropdownFetchLimit = 10;
69 export const languages = [
70 { code: 'ca', name: 'Català' },
71 { code: 'en', name: 'English' },
72 { code: 'el', name: 'Ελληνικά' },
73 { code: 'eu', name: 'Euskara' },
74 { code: 'eo', name: 'Esperanto' },
75 { code: 'es', name: 'Español' },
76 { code: 'de', name: 'Deutsch' },
77 { code: 'ga', name: 'Gaeilge' },
78 { code: 'gl', name: 'Galego' },
79 { code: 'hu', name: 'Magyar Nyelv' },
80 { code: 'ka', name: 'ქართული ენა' },
81 { code: 'km', name: 'ភាសាខ្មែរ' },
82 { code: 'hi', name: 'मानक हिन्दी' },
83 { code: 'fa', name: 'فارسی' },
84 { code: 'ja', name: '日本語' },
85 { code: 'pl', name: 'Polski' },
86 { code: 'pt_BR', name: 'Português Brasileiro' },
87 { code: 'zh', name: '中文' },
88 { code: 'fi', name: 'Suomi' },
89 { code: 'fr', name: 'Français' },
90 { code: 'sv', name: 'Svenska' },
91 { code: 'sq', name: 'Shqip' },
92 { code: 'sr_Latn', name: 'srpski' },
93 { code: 'tr', name: 'Türkçe' },
94 { code: 'uk', name: 'Українська Mова' },
95 { code: 'ru', name: 'Русский' },
96 { code: 'nl', name: 'Nederlands' },
97 { code: 'it', name: 'Italiano' },
100 export const themes = [
116 const DEFAULT_ALPHABET =
117 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
119 function getRandomCharFromAlphabet(alphabet: string): string {
120 return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
123 export function randomStr(
124 idDesiredLength: number = 20,
125 alphabet = DEFAULT_ALPHABET
128 * Create n-long array and map it to random chars from given alphabet.
129 * Then join individual chars as string
131 return Array.from({ length: idDesiredLength })
133 return getRandomCharFromAlphabet(alphabet);
138 export function wsJsonToRes(msg: WebSocketJsonResponse): WebSocketResponse {
139 let opStr: string = msg.op;
141 op: UserOperation[opStr],
146 export const md = new markdown_it({
151 .use(markdown_it_container, 'spoiler', {
152 validate: function (params: any) {
153 return params.trim().match(/^spoiler\s+(.*)$/);
156 render: function (tokens: any, idx: any) {
157 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
159 if (tokens[idx].nesting === 1) {
161 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
164 return '</details>\n';
168 .use(markdownitEmoji, {
169 defs: objectFlip(emojiShortName),
172 export function hotRankComment(comment: Comment): number {
173 return hotRank(comment.score, comment.published);
176 export function hotRankPost(post: Post): number {
177 return hotRank(post.score, post.newest_activity_time);
180 export function hotRank(score: number, timeStr: string): number {
181 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
182 let date: Date = new Date(timeStr + 'Z'); // Add Z to convert from UTC date
183 let now: Date = new Date();
184 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
187 (10000 * Math.log10(Math.max(1, 3 + score))) /
188 Math.pow(hoursElapsed + 2, 1.8);
190 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
195 export function mdToHtml(text: string) {
196 return { __html: md.render(text) };
199 export function getUnixTime(text: string): number {
200 return text ? new Date(text).getTime() / 1000 : undefined;
203 export function addTypeInfo<T>(
206 ): Array<{ type_: string; data: T }> {
207 return arr.map(e => {
208 return { type_: name, data: e };
212 export function canMod(
214 modIds: Array<number>,
216 onSelf: boolean = false
218 // You can do moderator actions only on the mods added after you.
220 let yourIndex = modIds.findIndex(id => id == user.id);
221 if (yourIndex == -1) {
224 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
225 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
226 return !modIds.includes(creator_id);
233 export function isMod(modIds: Array<number>, creator_id: number): boolean {
234 return modIds.includes(creator_id);
237 const imageRegex = new RegExp(
238 /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg|webp))/
240 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
242 export function isImage(url: string) {
243 return imageRegex.test(url);
246 export function isVideo(url: string) {
247 return videoRegex.test(url);
250 export function validURL(str: string) {
252 return !!new URL(str);
258 export function validEmail(email: string) {
259 let re = /^(([^\s"(),.:;<>@[\\\]]+(\.[^\s"(),.:;<>@[\\\]]+)*)|(".+"))@((\[(?:\d{1,3}\.){3}\d{1,3}])|(([\dA-Za-z\-]+\.)+[A-Za-z]{2,}))$/;
260 return re.test(String(email).toLowerCase());
263 export function capitalizeFirstLetter(str: string): string {
264 return str.charAt(0).toUpperCase() + str.slice(1);
267 export function routeSortTypeToEnum(sort: string): SortType {
270 } else if (sort == 'hot') {
272 } else if (sort == 'topday') {
273 return SortType.TopDay;
274 } else if (sort == 'topweek') {
275 return SortType.TopWeek;
276 } else if (sort == 'topmonth') {
277 return SortType.TopMonth;
278 } else if (sort == 'topyear') {
279 return SortType.TopYear;
280 } else if (sort == 'topall') {
281 return SortType.TopAll;
285 export function routeListingTypeToEnum(type: string): ListingType {
286 return ListingType[capitalizeFirstLetter(type)];
289 export function routeDataTypeToEnum(type: string): DataType {
290 return DataType[capitalizeFirstLetter(type)];
293 export function routeSearchTypeToEnum(type: string): SearchType {
294 return SearchType[capitalizeFirstLetter(type)];
297 export async function getPageTitle(url: string) {
298 let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
299 let title = await res.title;
303 export function debounce(
306 immediate: boolean = false
308 // 'private' variable for instance
309 // The returned function will be able to reference this due to closure.
310 // Each call to the returned function will share this common timer.
313 // Calling debounce returns a new anonymous function
315 // reference the context and args for the setTimeout function
319 // Should the function be called now? If immediate is true
320 // and not already in a timeout then the answer is: Yes
321 var callNow = immediate && !timeout;
323 // This is the basic debounce behaviour where you can call this
324 // function several times, but it will only execute once
325 // [before or after imposing a delay].
326 // Each time the returned function is called, the timer starts over.
327 clearTimeout(timeout);
329 // Set the new timeout
330 timeout = setTimeout(function () {
331 // Inside the timeout function, clear the timeout variable
332 // which will let the next execution run when in 'immediate' mode
335 // Check if the function already ran with the immediate flag
337 // Call the original function with apply
338 // apply lets you define the 'this' object as well as the arguments
339 // (both captured before setTimeout)
340 func.apply(context, args);
344 // Immediate mode and no wait timer? Execute the function..
345 if (callNow) func.apply(context, args);
349 export function getLanguage(): string {
350 let user = UserService.Instance.user;
351 let lang = user && user.lang ? user.lang : 'browser';
353 if (lang == 'browser') {
354 return getBrowserLanguage();
360 export function getBrowserLanguage(): string {
361 return navigator.language;
364 export function getMomentLanguage(): string {
365 let lang = getLanguage();
366 if (lang.startsWith('zh')) {
368 } else if (lang.startsWith('sv')) {
370 } else if (lang.startsWith('fr')) {
372 } else if (lang.startsWith('de')) {
374 } else if (lang.startsWith('ru')) {
376 } else if (lang.startsWith('es')) {
378 } else if (lang.startsWith('eo')) {
380 } else if (lang.startsWith('nl')) {
382 } else if (lang.startsWith('it')) {
384 } else if (lang.startsWith('fi')) {
386 } else if (lang.startsWith('ca')) {
388 } else if (lang.startsWith('fa')) {
390 } else if (lang.startsWith('pl')) {
392 } else if (lang.startsWith('pt')) {
394 } else if (lang.startsWith('ja')) {
396 } else if (lang.startsWith('ka')) {
398 } else if (lang.startsWith('hi')) {
400 } else if (lang.startsWith('el')) {
402 } else if (lang.startsWith('eu')) {
404 } else if (lang.startsWith('gl')) {
406 } else if (lang.startsWith('tr')) {
408 } else if (lang.startsWith('hu')) {
410 } else if (lang.startsWith('uk')) {
412 } else if (lang.startsWith('sq')) {
414 } else if (lang.startsWith('km')) {
416 } else if (lang.startsWith('ga')) {
418 } else if (lang.startsWith('sr')) {
426 export function setTheme(theme: string = 'darkly', loggedIn: boolean = false) {
427 // unload all the other themes
428 for (var i = 0; i < themes.length; i++) {
429 let styleSheet = document.getElementById(themes[i]);
431 styleSheet.setAttribute('disabled', 'disabled');
435 // if the user is not logged in, we load the default themes and let the browser decide
437 document.getElementById('default-light').removeAttribute('disabled');
438 document.getElementById('default-dark').removeAttribute('disabled');
441 .getElementById('default-light')
442 .setAttribute('disabled', 'disabled');
444 .getElementById('default-dark')
445 .setAttribute('disabled', 'disabled');
447 // Load the theme dynamically
448 let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
449 loadCss(theme, cssLoc);
450 document.getElementById(theme).removeAttribute('disabled');
454 export function loadCss(id: string, loc: string) {
455 if (!document.getElementById(id)) {
456 var head = document.getElementsByTagName('head')[0];
457 var link = document.createElement('link');
459 link.rel = 'stylesheet';
460 link.type = 'text/css';
463 head.appendChild(link);
467 export function objectFlip(obj: any) {
469 Object.keys(obj).forEach(key => {
475 export function pictrsAvatarThumbnail(src: string): string {
476 // sample url: http://localhost:8535/pictrs/image/thumbnail256/gs7xuu.jpg
477 let split = src.split('/pictrs/image');
478 let out = `${split[0]}/pictrs/image/${
479 canUseWebP() ? 'webp/' : ''
480 }thumbnail96${split[1]}`;
484 export function showAvatars(): boolean {
486 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
487 !UserService.Instance.user
491 export function isCakeDay(published: string): boolean {
492 // moment(undefined) or moment.utc(undefined) returns the current date/time
493 // moment(null) or moment.utc(null) returns null
494 const userCreationDate = moment.utc(published || null).local();
495 const currentDate = moment(new Date());
498 userCreationDate.date() === currentDate.date() &&
499 userCreationDate.month() === currentDate.month()
503 // Converts to image thumbnail
504 export function pictrsImage(hash: string, thumbnail: boolean = false): string {
505 let root = `/pictrs/image`;
507 // Necessary for other servers / domains
508 if (hash.includes('pictrs')) {
509 let split = hash.split('/pictrs/image/');
510 root = `${split[0]}/pictrs/image`;
514 let out = `${root}/${canUseWebP() ? 'webp/' : ''}${
515 thumbnail ? 'thumbnail256/' : ''
520 export function isCommentType(item: Comment | PrivateMessage): item is Comment {
521 return (item as Comment).community_id !== undefined;
524 export function toast(text: string, background: string = 'success') {
525 let backgroundColor = `var(--${background})`;
528 backgroundColor: backgroundColor,
534 export function pictrsDeleteToast(
535 clickToDeleteText: string,
536 deletePictureText: string,
539 let backgroundColor = `var(--light)`;
540 let toast = Toastify({
541 text: clickToDeleteText,
542 backgroundColor: backgroundColor,
548 window.location.replace(deleteUrl);
549 alert(deletePictureText);
557 export function messageToastify(
564 let backgroundColor = `var(--light)`;
566 let toast = Toastify({
567 text: `${body}<br />${creator}`,
569 backgroundColor: backgroundColor,
570 className: 'text-dark',
578 router.history.push(link);
584 export function setupTribute(): Tribute {
590 menuItemTemplate: (item: any) => {
591 let shortName = `:${item.original.key}:`;
592 return `${item.original.val} ${shortName}`;
594 selectTemplate: (item: any) => {
595 return `:${item.original.key}:`;
597 values: Object.entries(emojiShortName).map(e => {
598 return { key: e[1], val: e[0] };
601 autocompleteMode: true,
602 menuItemLimit: mentionDropdownFetchLimit,
603 menuShowMinLength: 2,
608 selectTemplate: (item: any) => {
609 let link = item.original.local
610 ? `[${item.original.key}](/u/${item.original.name})`
611 : `[${item.original.key}](/user/${item.original.id})`;
614 values: (text: string, cb: any) => {
615 userSearch(text, (users: any) => cb(users));
618 autocompleteMode: true,
619 menuItemLimit: mentionDropdownFetchLimit,
620 menuShowMinLength: 2,
626 selectTemplate: (item: any) => {
627 let link = item.original.local
628 ? `[${item.original.key}](/c/${item.original.name})`
629 : `[${item.original.key}](/community/${item.original.id})`;
632 values: (text: string, cb: any) => {
633 communitySearch(text, (communities: any) => cb(communities));
636 autocompleteMode: true,
637 menuItemLimit: mentionDropdownFetchLimit,
638 menuShowMinLength: 2,
644 let tippyInstance = tippy('[data-tippy-content]');
646 export function setupTippy() {
647 tippyInstance.forEach(e => e.destroy());
648 tippyInstance = tippy('[data-tippy-content]', {
650 // Display on "long press"
651 touch: ['hold', 500],
655 function userSearch(text: string, cb: any) {
657 let form: SearchForm = {
659 type_: SearchType[SearchType.Users],
660 sort: SortType[SortType.TopAll],
662 limit: mentionDropdownFetchLimit,
665 WebSocketService.Instance.search(form);
667 this.userSub = WebSocketService.Instance.subject.subscribe(
669 let res = wsJsonToRes(msg);
670 if (res.op == UserOperation.Search) {
671 let data = res.data as SearchResponse;
672 let users = data.users.map(u => {
674 key: `@${u.name}@${hostname(u.actor_id)}`,
681 this.userSub.unsubscribe();
684 err => console.error(err),
685 () => console.log('complete')
692 function communitySearch(text: string, cb: any) {
694 let form: SearchForm = {
696 type_: SearchType[SearchType.Communities],
697 sort: SortType[SortType.TopAll],
699 limit: mentionDropdownFetchLimit,
702 WebSocketService.Instance.search(form);
704 this.communitySub = WebSocketService.Instance.subject.subscribe(
706 let res = wsJsonToRes(msg);
707 if (res.op == UserOperation.Search) {
708 let data = res.data as SearchResponse;
709 let communities = data.communities.map(c => {
711 key: `!${c.name}@${hostname(c.actor_id)}`,
718 this.communitySub.unsubscribe();
721 err => console.error(err),
722 () => console.log('complete')
729 export function getListingTypeFromProps(props: any): ListingType {
730 return props.match.params.listing_type
731 ? routeListingTypeToEnum(props.match.params.listing_type)
732 : UserService.Instance.user
733 ? UserService.Instance.user.default_listing_type
737 // TODO might need to add a user setting for this too
738 export function getDataTypeFromProps(props: any): DataType {
739 return props.match.params.data_type
740 ? routeDataTypeToEnum(props.match.params.data_type)
744 export function getSortTypeFromProps(props: any): SortType {
745 return props.match.params.sort
746 ? routeSortTypeToEnum(props.match.params.sort)
747 : UserService.Instance.user
748 ? UserService.Instance.user.default_sort_type
752 export function getPageFromProps(props: any): number {
753 return props.match.params.page ? Number(props.match.params.page) : 1;
756 export function editCommentRes(
757 data: CommentResponse,
758 comments: Array<Comment>
760 let found = comments.find(c => c.id == data.comment.id);
762 found.content = data.comment.content;
763 found.updated = data.comment.updated;
764 found.removed = data.comment.removed;
765 found.deleted = data.comment.deleted;
766 found.upvotes = data.comment.upvotes;
767 found.downvotes = data.comment.downvotes;
768 found.score = data.comment.score;
772 export function saveCommentRes(
773 data: CommentResponse,
774 comments: Array<Comment>
776 let found = comments.find(c => c.id == data.comment.id);
778 found.saved = data.comment.saved;
782 export function createCommentLikeRes(
783 data: CommentResponse,
784 comments: Array<Comment>
786 let found: Comment = comments.find(c => c.id === data.comment.id);
788 found.score = data.comment.score;
789 found.upvotes = data.comment.upvotes;
790 found.downvotes = data.comment.downvotes;
791 if (data.comment.my_vote !== null) {
792 found.my_vote = data.comment.my_vote;
797 export function createPostLikeFindRes(data: PostResponse, posts: Array<Post>) {
798 let found = posts.find(c => c.id == data.post.id);
800 createPostLikeRes(data, found);
804 export function createPostLikeRes(data: PostResponse, post: Post) {
806 post.score = data.post.score;
807 post.upvotes = data.post.upvotes;
808 post.downvotes = data.post.downvotes;
809 if (data.post.my_vote !== null) {
810 post.my_vote = data.post.my_vote;
815 export function editPostFindRes(data: PostResponse, posts: Array<Post>) {
816 let found = posts.find(c => c.id == data.post.id);
818 editPostRes(data, found);
822 export function editPostRes(data: PostResponse, post: Post) {
824 post.url = data.post.url;
825 post.name = data.post.name;
826 post.nsfw = data.post.nsfw;
830 export function commentsToFlatNodes(
831 comments: Array<Comment>
832 ): Array<CommentNodeI> {
833 let nodes: Array<CommentNodeI> = [];
834 for (let comment of comments) {
835 nodes.push({ comment: comment });
840 export function commentSort(tree: Array<CommentNodeI>, sort: CommentSortType) {
841 // First, put removed and deleted comments at the bottom, then do your other sorts
842 if (sort == CommentSortType.Top) {
845 +a.comment.removed - +b.comment.removed ||
846 +a.comment.deleted - +b.comment.deleted ||
847 b.comment.score - a.comment.score
849 } else if (sort == CommentSortType.New) {
852 +a.comment.removed - +b.comment.removed ||
853 +a.comment.deleted - +b.comment.deleted ||
854 b.comment.published.localeCompare(a.comment.published)
856 } else if (sort == CommentSortType.Old) {
859 +a.comment.removed - +b.comment.removed ||
860 +a.comment.deleted - +b.comment.deleted ||
861 a.comment.published.localeCompare(b.comment.published)
863 } else if (sort == CommentSortType.Hot) {
866 +a.comment.removed - +b.comment.removed ||
867 +a.comment.deleted - +b.comment.deleted ||
868 hotRankComment(b.comment) - hotRankComment(a.comment)
872 // Go through the children recursively
873 for (let node of tree) {
875 commentSort(node.children, sort);
880 export function commentSortSortType(tree: Array<CommentNodeI>, sort: SortType) {
881 commentSort(tree, convertCommentSortType(sort));
884 function convertCommentSortType(sort: SortType): CommentSortType {
886 sort == SortType.TopAll ||
887 sort == SortType.TopDay ||
888 sort == SortType.TopWeek ||
889 sort == SortType.TopMonth ||
890 sort == SortType.TopYear
892 return CommentSortType.Top;
893 } else if (sort == SortType.New) {
894 return CommentSortType.New;
895 } else if (sort == SortType.Hot) {
896 return CommentSortType.Hot;
898 return CommentSortType.Hot;
902 export function postSort(
905 communityType: boolean
907 // First, put removed and deleted comments at the bottom, then do your other sorts
909 sort == SortType.TopAll ||
910 sort == SortType.TopDay ||
911 sort == SortType.TopWeek ||
912 sort == SortType.TopMonth ||
913 sort == SortType.TopYear
917 +a.removed - +b.removed ||
918 +a.deleted - +b.deleted ||
919 (communityType && +b.stickied - +a.stickied) ||
922 } else if (sort == SortType.New) {
925 +a.removed - +b.removed ||
926 +a.deleted - +b.deleted ||
927 (communityType && +b.stickied - +a.stickied) ||
928 b.published.localeCompare(a.published)
930 } else if (sort == SortType.Hot) {
933 +a.removed - +b.removed ||
934 +a.deleted - +b.deleted ||
935 (communityType && +b.stickied - +a.stickied) ||
936 b.hot_rank - a.hot_rank
941 export const colorList: Array<string> = [
950 function hsl(num: number) {
951 return `hsla(${num}, 35%, 50%, 1)`;
954 function randomHsl() {
955 return `hsla(${Math.random() * 360}, 100%, 50%, 1)`;
958 export function previewLines(text: string, lines: number = 3): string {
959 // Use lines * 2 because markdown requires 2 lines
966 export function hostname(url: string): string {
967 let cUrl = new URL(url);
968 return window.location.port
969 ? `${cUrl.hostname}:${cUrl.port}`
970 : `${cUrl.hostname}`;
973 function canUseWebP() {
974 // TODO pictshare might have a webp conversion bug, try disabling this
977 // var elem = document.createElement('canvas');
978 // if (!!(elem.getContext && elem.getContext('2d'))) {
979 // var testString = !(window.mozInnerScreenX == null) ? 'png' : 'webp';
980 // // was able or not to get WebP representation
982 // elem.toDataURL('image/webp').startsWith('data:image/' + testString)
986 // // very old browser like IE 8, canvas not supported