1 import 'moment/locale/es';
2 import 'moment/locale/eo';
3 import 'moment/locale/de';
4 import 'moment/locale/zh-cn';
5 import 'moment/locale/fr';
6 import 'moment/locale/sv';
7 import 'moment/locale/ru';
8 import 'moment/locale/nl';
9 import 'moment/locale/it';
10 import 'moment/locale/fi';
11 import 'moment/locale/ca';
12 import 'moment/locale/fa';
13 import 'moment/locale/pt-br';
27 WebSocketJsonResponse,
32 } from './interfaces';
33 import { UserService, WebSocketService } from './services';
35 import Tribute from 'tributejs/src/Tribute.js';
36 import markdown_it from 'markdown-it';
37 import markdownitEmoji from 'markdown-it-emoji/light';
38 import markdown_it_container from 'markdown-it-container';
39 import twemoji from 'twemoji';
40 import emojiShortName from 'emoji-short-name';
41 import Toastify from 'toastify-js';
43 export const repoUrl = 'https://github.com/dessalines/lemmy';
44 export const markdownHelpUrl = 'https://commonmark.org/help/';
45 export const archiveUrl = 'https://archive.is';
47 export const postRefetchSeconds: number = 60 * 1000;
48 export const fetchLimit: number = 20;
49 export const mentionDropdownFetchLimit = 10;
51 export function randomStr() {
54 .replace(/[^a-z]+/g, '')
58 export function wsJsonToRes(msg: WebSocketJsonResponse): WebSocketResponse {
59 let opStr: string = msg.op;
61 op: UserOperation[opStr],
66 export const md = new markdown_it({
71 .use(markdown_it_container, 'spoiler', {
72 validate: function(params: any) {
73 return params.trim().match(/^spoiler\s+(.*)$/);
76 render: function(tokens: any, idx: any) {
77 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
79 if (tokens[idx].nesting === 1) {
81 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
84 return '</details>\n';
88 .use(markdownitEmoji, {
89 defs: objectFlip(emojiShortName),
92 md.renderer.rules.emoji = function(token, idx) {
93 return twemoji.parse(token[idx].content);
96 export function hotRank(comment: Comment): number {
97 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
99 let date: Date = new Date(comment.published + 'Z'); // Add Z to convert from UTC date
100 let now: Date = new Date();
101 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
104 (10000 * Math.log10(Math.max(1, 3 + comment.score))) /
105 Math.pow(hoursElapsed + 2, 1.8);
107 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
112 export function mdToHtml(text: string) {
113 return { __html: md.render(text) };
116 export function getUnixTime(text: string): number {
117 return text ? new Date(text).getTime() / 1000 : undefined;
120 export function addTypeInfo<T>(
123 ): Array<{ type_: string; data: T }> {
124 return arr.map(e => {
125 return { type_: name, data: e };
129 export function canMod(
131 modIds: Array<number>,
133 onSelf: boolean = false
135 // You can do moderator actions only on the mods added after you.
137 let yourIndex = modIds.findIndex(id => id == user.id);
138 if (yourIndex == -1) {
141 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
142 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
143 return !modIds.includes(creator_id);
150 export function isMod(modIds: Array<number>, creator_id: number): boolean {
151 return modIds.includes(creator_id);
154 var imageRegex = new RegExp(
155 `(http)?s?:?(\/\/[^"']*\.(?:png|jpg|jpeg|gif|png|svg))`
157 var videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
159 export function isImage(url: string) {
160 return imageRegex.test(url);
163 export function isVideo(url: string) {
164 return videoRegex.test(url);
167 export function validURL(str: string) {
169 return !!new URL(str);
175 export function validEmail(email: string) {
176 let re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
177 return re.test(String(email).toLowerCase());
180 export function capitalizeFirstLetter(str: string): string {
181 return str.charAt(0).toUpperCase() + str.slice(1);
184 export function routeSortTypeToEnum(sort: string): SortType {
187 } else if (sort == 'hot') {
189 } else if (sort == 'topday') {
190 return SortType.TopDay;
191 } else if (sort == 'topweek') {
192 return SortType.TopWeek;
193 } else if (sort == 'topmonth') {
194 return SortType.TopMonth;
195 } else if (sort == 'topyear') {
196 return SortType.TopYear;
197 } else if (sort == 'topall') {
198 return SortType.TopAll;
202 export function routeListingTypeToEnum(type: string): ListingType {
203 return ListingType[capitalizeFirstLetter(type)];
206 export function routeDataTypeToEnum(type: string): DataType {
207 return DataType[capitalizeFirstLetter(type)];
210 export function routeSearchTypeToEnum(type: string): SearchType {
211 return SearchType[capitalizeFirstLetter(type)];
214 export async function getPageTitle(url: string) {
215 let res = await fetch(`https://textance.herokuapp.com/title/${url}`);
216 let data = await res.text();
220 export function debounce(
223 immediate: boolean = false
225 // 'private' variable for instance
226 // The returned function will be able to reference this due to closure.
227 // Each call to the returned function will share this common timer.
230 // Calling debounce returns a new anonymous function
232 // reference the context and args for the setTimeout function
236 // Should the function be called now? If immediate is true
237 // and not already in a timeout then the answer is: Yes
238 var callNow = immediate && !timeout;
240 // This is the basic debounce behaviour where you can call this
241 // function several times, but it will only execute once
242 // [before or after imposing a delay].
243 // Each time the returned function is called, the timer starts over.
244 clearTimeout(timeout);
246 // Set the new timeout
247 timeout = setTimeout(function() {
248 // Inside the timeout function, clear the timeout variable
249 // which will let the next execution run when in 'immediate' mode
252 // Check if the function already ran with the immediate flag
254 // Call the original function with apply
255 // apply lets you define the 'this' object as well as the arguments
256 // (both captured before setTimeout)
257 func.apply(context, args);
261 // Immediate mode and no wait timer? Execute the function..
262 if (callNow) func.apply(context, args);
266 export const languages = [
267 { code: 'ca', name: 'Català' },
268 { code: 'en', name: 'English' },
269 { code: 'eo', name: 'Esperanto' },
270 { code: 'es', name: 'Español' },
271 { code: 'de', name: 'Deutsch' },
272 { code: 'fa', name: 'فارسی' },
273 { code: 'pt_BR', name: 'Português Brasileiro' },
274 { code: 'zh', name: '中文' },
275 { code: 'fi', name: 'Suomi' },
276 { code: 'fr', name: 'Français' },
277 { code: 'sv', name: 'Svenska' },
278 { code: 'ru', name: 'Русский' },
279 { code: 'nl', name: 'Nederlands' },
280 { code: 'it', name: 'Italiano' },
283 export function getLanguage(): string {
284 let user = UserService.Instance.user;
285 let lang = user && user.lang ? user.lang : 'browser';
287 if (lang == 'browser') {
288 return getBrowserLanguage();
294 export function getBrowserLanguage(): string {
295 return navigator.language;
298 export function getMomentLanguage(): string {
299 let lang = getLanguage();
300 if (lang.startsWith('zh')) {
302 } else if (lang.startsWith('sv')) {
304 } else if (lang.startsWith('fr')) {
306 } else if (lang.startsWith('de')) {
308 } else if (lang.startsWith('ru')) {
310 } else if (lang.startsWith('es')) {
312 } else if (lang.startsWith('eo')) {
314 } else if (lang.startsWith('nl')) {
316 } else if (lang.startsWith('it')) {
318 } else if (lang.startsWith('fi')) {
320 } else if (lang.startsWith('ca')) {
322 } else if (lang.startsWith('fa')) {
324 } else if (lang.startsWith('pt')) {
332 export const themes = [
347 export function setTheme(theme: string = 'darkly') {
348 // unload all the other themes
349 for (var i = 0; i < themes.length; i++) {
350 let styleSheet = document.getElementById(themes[i]);
352 styleSheet.setAttribute('disabled', 'disabled');
356 // Load the theme dynamically
357 if (!document.getElementById(theme)) {
358 var head = document.getElementsByTagName('head')[0];
359 var link = document.createElement('link');
361 link.rel = 'stylesheet';
362 link.type = 'text/css';
363 link.href = `/static/assets/css/themes/${theme}.min.css`;
365 head.appendChild(link);
367 document.getElementById(theme).removeAttribute('disabled');
370 export function objectFlip(obj: any) {
372 Object.keys(obj).forEach(key => {
378 export function pictshareAvatarThumbnail(src: string): string {
379 // sample url: http://localhost:8535/pictshare/gs7xuu.jpg
380 let split = src.split('pictshare');
381 let out = `${split[0]}pictshare/96x96${split[1]}`;
385 export function showAvatars(): boolean {
387 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
388 !UserService.Instance.user
392 /// Converts to image thumbnail (only supports pictshare currently)
393 export function imageThumbnailer(url: string): string {
394 let split = url.split('pictshare');
395 if (split.length > 1) {
396 let out = `${split[0]}pictshare/192x192${split[1]}`;
403 export function isCommentType(item: Comment | PrivateMessage): item is Comment {
404 return (item as Comment).community_id !== undefined;
407 export function toast(text: string, background: string = 'success') {
408 let backgroundColor = `var(--${background})`;
411 backgroundColor: backgroundColor,
417 export function setupTribute(): Tribute {
423 menuItemTemplate: (item: any) => {
424 let emoji = `:${item.original.key}:`;
425 return `${item.original.val} ${emoji}`;
427 selectTemplate: (item: any) => {
428 return `:${item.original.key}:`;
430 values: Object.entries(emojiShortName).map(e => {
431 return { key: e[1], val: e[0] };
434 autocompleteMode: true,
435 menuItemLimit: mentionDropdownFetchLimit,
440 selectTemplate: (item: any) => {
441 return `[/u/${item.original.key}](/u/${item.original.key})`;
443 values: (text: string, cb: any) => {
444 userSearch(text, (users: any) => cb(users));
447 autocompleteMode: true,
448 menuItemLimit: mentionDropdownFetchLimit,
454 selectTemplate: (item: any) => {
455 return `[/c/${item.original.key}](/c/${item.original.key})`;
457 values: (text: string, cb: any) => {
458 communitySearch(text, (communities: any) => cb(communities));
461 autocompleteMode: true,
462 menuItemLimit: mentionDropdownFetchLimit,
468 function userSearch(text: string, cb: any) {
470 let form: SearchForm = {
472 type_: SearchType[SearchType.Users],
473 sort: SortType[SortType.TopAll],
475 limit: mentionDropdownFetchLimit,
478 WebSocketService.Instance.search(form);
480 this.userSub = WebSocketService.Instance.subject.subscribe(
482 let res = wsJsonToRes(msg);
483 if (res.op == UserOperation.Search) {
484 let data = res.data as SearchResponse;
485 let users = data.users.map(u => {
486 return { key: u.name };
489 this.userSub.unsubscribe();
492 err => console.error(err),
493 () => console.log('complete')
500 function communitySearch(text: string, cb: any) {
502 let form: SearchForm = {
504 type_: SearchType[SearchType.Communities],
505 sort: SortType[SortType.TopAll],
507 limit: mentionDropdownFetchLimit,
510 WebSocketService.Instance.search(form);
512 this.communitySub = WebSocketService.Instance.subject.subscribe(
514 let res = wsJsonToRes(msg);
515 if (res.op == UserOperation.Search) {
516 let data = res.data as SearchResponse;
517 let communities = data.communities.map(u => {
518 return { key: u.name };
521 this.communitySub.unsubscribe();
524 err => console.error(err),
525 () => console.log('complete')
532 export function getListingTypeFromProps(props: any): ListingType {
533 return props.match.params.listing_type
534 ? routeListingTypeToEnum(props.match.params.listing_type)
535 : UserService.Instance.user
536 ? UserService.Instance.user.default_listing_type
540 // TODO might need to add a user setting for this too
541 export function getDataTypeFromProps(props: any): DataType {
542 return props.match.params.data_type
543 ? routeDataTypeToEnum(props.match.params.data_type)
547 export function getSortTypeFromProps(props: any): SortType {
548 return props.match.params.sort
549 ? routeSortTypeToEnum(props.match.params.sort)
550 : UserService.Instance.user
551 ? UserService.Instance.user.default_sort_type
555 export function getPageFromProps(props: any): number {
556 return props.match.params.page ? Number(props.match.params.page) : 1;
559 export function editCommentRes(
560 data: CommentResponse,
561 comments: Array<Comment>
563 let found = comments.find(c => c.id == data.comment.id);
565 found.content = data.comment.content;
566 found.updated = data.comment.updated;
567 found.removed = data.comment.removed;
568 found.deleted = data.comment.deleted;
569 found.upvotes = data.comment.upvotes;
570 found.downvotes = data.comment.downvotes;
571 found.score = data.comment.score;
575 export function saveCommentRes(
576 data: CommentResponse,
577 comments: Array<Comment>
579 let found = comments.find(c => c.id == data.comment.id);
581 found.saved = data.comment.saved;
585 export function createCommentLikeRes(
586 data: CommentResponse,
587 comments: Array<Comment>
589 let found: Comment = comments.find(c => c.id === data.comment.id);
591 found.score = data.comment.score;
592 found.upvotes = data.comment.upvotes;
593 found.downvotes = data.comment.downvotes;
594 if (data.comment.my_vote !== null) {
595 found.my_vote = data.comment.my_vote;
596 found.upvoteLoading = false;
597 found.downvoteLoading = false;
602 export function createPostLikeFindRes(data: PostResponse, posts: Array<Post>) {
603 let found = posts.find(c => c.id == data.post.id);
605 createPostLikeRes(data, found);
609 export function createPostLikeRes(data: PostResponse, post: Post) {
610 post.score = data.post.score;
611 post.upvotes = data.post.upvotes;
612 post.downvotes = data.post.downvotes;
613 if (data.post.my_vote !== null) {
614 post.my_vote = data.post.my_vote;
615 post.upvoteLoading = false;
616 post.downvoteLoading = false;
620 export function editPostFindRes(data: PostResponse, posts: Array<Post>) {
621 let found = posts.find(c => c.id == data.post.id);
623 editPostRes(data, found);
627 export function editPostRes(data: PostResponse, post: Post) {
628 post.url = data.post.url;
629 post.name = data.post.name;
630 post.nsfw = data.post.nsfw;
633 export function commentsToFlatNodes(
634 comments: Array<Comment>
635 ): Array<CommentNode> {
636 let nodes: Array<CommentNode> = [];
637 for (let comment of comments) {
638 nodes.push({ comment: comment });