]> Untitled Git - lemmy.git/blob - ui/src/utils.ts
Translation additions.
[lemmy.git] / ui / src / utils.ts
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';
14 import 'moment/locale/ja';
15
16 import {
17   UserOperation,
18   Comment,
19   CommentNode,
20   Post,
21   PrivateMessage,
22   User,
23   SortType,
24   CommentSortType,
25   ListingType,
26   DataType,
27   SearchType,
28   WebSocketResponse,
29   WebSocketJsonResponse,
30   SearchForm,
31   SearchResponse,
32   CommentResponse,
33   PostResponse,
34 } from './interfaces';
35 import { UserService, WebSocketService } from './services';
36
37 import Tribute from 'tributejs/src/Tribute.js';
38 import markdown_it from 'markdown-it';
39 import markdownitEmoji from 'markdown-it-emoji/light';
40 import markdown_it_container from 'markdown-it-container';
41 import twemoji from 'twemoji';
42 import emojiShortName from 'emoji-short-name';
43 import Toastify from 'toastify-js';
44
45 export const repoUrl = 'https://github.com/dessalines/lemmy';
46 export const markdownHelpUrl = '/docs/about_guide.html';
47 export const archiveUrl = 'https://archive.is';
48
49 export const postRefetchSeconds: number = 60 * 1000;
50 export const fetchLimit: number = 20;
51 export const mentionDropdownFetchLimit = 10;
52
53 export function randomStr() {
54   return Math.random()
55     .toString(36)
56     .replace(/[^a-z]+/g, '')
57     .substr(2, 10);
58 }
59
60 export function wsJsonToRes(msg: WebSocketJsonResponse): WebSocketResponse {
61   let opStr: string = msg.op;
62   return {
63     op: UserOperation[opStr],
64     data: msg.data,
65   };
66 }
67
68 export const md = new markdown_it({
69   html: false,
70   linkify: true,
71   typographer: true,
72 })
73   .use(markdown_it_container, 'spoiler', {
74     validate: function(params: any) {
75       return params.trim().match(/^spoiler\s+(.*)$/);
76     },
77
78     render: function(tokens: any, idx: any) {
79       var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
80
81       if (tokens[idx].nesting === 1) {
82         // opening tag
83         return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
84       } else {
85         // closing tag
86         return '</details>\n';
87       }
88     },
89   })
90   .use(markdownitEmoji, {
91     defs: objectFlip(emojiShortName),
92   });
93
94 md.renderer.rules.emoji = function(token, idx) {
95   return twemoji.parse(token[idx].content);
96 };
97
98 export function hotRankComment(comment: Comment): number {
99   return hotRank(comment.score, comment.published);
100 }
101
102 export function hotRankPost(post: Post): number {
103   return hotRank(post.score, post.newest_activity_time);
104 }
105
106 export function hotRank(score: number, timeStr: string): number {
107   // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
108   let date: Date = new Date(timeStr + 'Z'); // Add Z to convert from UTC date
109   let now: Date = new Date();
110   let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
111
112   let rank =
113     (10000 * Math.log10(Math.max(1, 3 + score))) /
114     Math.pow(hoursElapsed + 2, 1.8);
115
116   // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
117
118   return rank;
119 }
120
121 export function mdToHtml(text: string) {
122   return { __html: md.render(text) };
123 }
124
125 export function getUnixTime(text: string): number {
126   return text ? new Date(text).getTime() / 1000 : undefined;
127 }
128
129 export function addTypeInfo<T>(
130   arr: Array<T>,
131   name: string
132 ): Array<{ type_: string; data: T }> {
133   return arr.map(e => {
134     return { type_: name, data: e };
135   });
136 }
137
138 export function canMod(
139   user: User,
140   modIds: Array<number>,
141   creator_id: number,
142   onSelf: boolean = false
143 ): boolean {
144   // You can do moderator actions only on the mods added after you.
145   if (user) {
146     let yourIndex = modIds.findIndex(id => id == user.id);
147     if (yourIndex == -1) {
148       return false;
149     } else {
150       // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
151       modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
152       return !modIds.includes(creator_id);
153     }
154   } else {
155     return false;
156   }
157 }
158
159 export function isMod(modIds: Array<number>, creator_id: number): boolean {
160   return modIds.includes(creator_id);
161 }
162
163 const imageRegex = new RegExp(
164   /(http)?s?:?(\/\/[^"']*\.(?:jpg|jpeg|gif|png|svg))/
165 );
166 const videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
167
168 export function isImage(url: string) {
169   return imageRegex.test(url);
170 }
171
172 export function isVideo(url: string) {
173   return videoRegex.test(url);
174 }
175
176 export function validURL(str: string) {
177   try {
178     return !!new URL(str);
179   } catch {
180     return false;
181   }
182 }
183
184 export function validEmail(email: string) {
185   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,}))$/;
186   return re.test(String(email).toLowerCase());
187 }
188
189 export function capitalizeFirstLetter(str: string): string {
190   return str.charAt(0).toUpperCase() + str.slice(1);
191 }
192
193 export function routeSortTypeToEnum(sort: string): SortType {
194   if (sort == 'new') {
195     return SortType.New;
196   } else if (sort == 'hot') {
197     return SortType.Hot;
198   } else if (sort == 'topday') {
199     return SortType.TopDay;
200   } else if (sort == 'topweek') {
201     return SortType.TopWeek;
202   } else if (sort == 'topmonth') {
203     return SortType.TopMonth;
204   } else if (sort == 'topyear') {
205     return SortType.TopYear;
206   } else if (sort == 'topall') {
207     return SortType.TopAll;
208   }
209 }
210
211 export function routeListingTypeToEnum(type: string): ListingType {
212   return ListingType[capitalizeFirstLetter(type)];
213 }
214
215 export function routeDataTypeToEnum(type: string): DataType {
216   return DataType[capitalizeFirstLetter(type)];
217 }
218
219 export function routeSearchTypeToEnum(type: string): SearchType {
220   return SearchType[capitalizeFirstLetter(type)];
221 }
222
223 export async function getPageTitle(url: string) {
224   let res = await fetch(`/iframely/oembed?url=${url}`).then(res => res.json());
225   let title = await res.title;
226   return title;
227 }
228
229 export function debounce(
230   func: any,
231   wait: number = 1000,
232   immediate: boolean = false
233 ) {
234   // 'private' variable for instance
235   // The returned function will be able to reference this due to closure.
236   // Each call to the returned function will share this common timer.
237   let timeout: any;
238
239   // Calling debounce returns a new anonymous function
240   return function() {
241     // reference the context and args for the setTimeout function
242     var context = this,
243       args = arguments;
244
245     // Should the function be called now? If immediate is true
246     //   and not already in a timeout then the answer is: Yes
247     var callNow = immediate && !timeout;
248
249     // This is the basic debounce behaviour where you can call this
250     //   function several times, but it will only execute once
251     //   [before or after imposing a delay].
252     //   Each time the returned function is called, the timer starts over.
253     clearTimeout(timeout);
254
255     // Set the new timeout
256     timeout = setTimeout(function() {
257       // Inside the timeout function, clear the timeout variable
258       // which will let the next execution run when in 'immediate' mode
259       timeout = null;
260
261       // Check if the function already ran with the immediate flag
262       if (!immediate) {
263         // Call the original function with apply
264         // apply lets you define the 'this' object as well as the arguments
265         //    (both captured before setTimeout)
266         func.apply(context, args);
267       }
268     }, wait);
269
270     // Immediate mode and no wait timer? Execute the function..
271     if (callNow) func.apply(context, args);
272   };
273 }
274
275 export const languages = [
276   { code: 'ca', name: 'Català' },
277   { code: 'en', name: 'English' },
278   { code: 'eo', name: 'Esperanto' },
279   { code: 'es', name: 'Español' },
280   { code: 'de', name: 'Deutsch' },
281   { code: 'fa', name: 'فارسی' },
282   { code: 'ja', name: '日本語' },
283   { code: 'pt_BR', name: 'Português Brasileiro' },
284   { code: 'zh', name: '中文' },
285   { code: 'fi', name: 'Suomi' },
286   { code: 'fr', name: 'Français' },
287   { code: 'sv', name: 'Svenska' },
288   { code: 'ru', name: 'Русский' },
289   { code: 'nl', name: 'Nederlands' },
290   { code: 'it', name: 'Italiano' },
291 ];
292
293 export function getLanguage(): string {
294   let user = UserService.Instance.user;
295   let lang = user && user.lang ? user.lang : 'browser';
296
297   if (lang == 'browser') {
298     return getBrowserLanguage();
299   } else {
300     return lang;
301   }
302 }
303
304 export function getBrowserLanguage(): string {
305   return navigator.language;
306 }
307
308 export function getMomentLanguage(): string {
309   let lang = getLanguage();
310   if (lang.startsWith('zh')) {
311     lang = 'zh-cn';
312   } else if (lang.startsWith('sv')) {
313     lang = 'sv';
314   } else if (lang.startsWith('fr')) {
315     lang = 'fr';
316   } else if (lang.startsWith('de')) {
317     lang = 'de';
318   } else if (lang.startsWith('ru')) {
319     lang = 'ru';
320   } else if (lang.startsWith('es')) {
321     lang = 'es';
322   } else if (lang.startsWith('eo')) {
323     lang = 'eo';
324   } else if (lang.startsWith('nl')) {
325     lang = 'nl';
326   } else if (lang.startsWith('it')) {
327     lang = 'it';
328   } else if (lang.startsWith('fi')) {
329     lang = 'fi';
330   } else if (lang.startsWith('ca')) {
331     lang = 'ca';
332   } else if (lang.startsWith('fa')) {
333     lang = 'fa';
334   } else if (lang.startsWith('pt')) {
335     lang = 'pt-br';
336   } else if (lang.startsWith('ja')) {
337     lang = 'ja';
338   } else {
339     lang = 'en';
340   }
341   return lang;
342 }
343
344 export const themes = [
345   'litera',
346   'materia',
347   'minty',
348   'solar',
349   'united',
350   'cyborg',
351   'darkly',
352   'journal',
353   'sketchy',
354   'vaporwave',
355   'vaporwave-dark',
356   'i386',
357 ];
358
359 export function setTheme(theme: string = 'darkly') {
360   // unload all the other themes
361   for (var i = 0; i < themes.length; i++) {
362     let styleSheet = document.getElementById(themes[i]);
363     if (styleSheet) {
364       styleSheet.setAttribute('disabled', 'disabled');
365     }
366   }
367
368   // Load the theme dynamically
369   if (!document.getElementById(theme)) {
370     var head = document.getElementsByTagName('head')[0];
371     var link = document.createElement('link');
372     link.id = theme;
373     link.rel = 'stylesheet';
374     link.type = 'text/css';
375     link.href = `/static/assets/css/themes/${theme}.min.css`;
376     link.media = 'all';
377     head.appendChild(link);
378   }
379   document.getElementById(theme).removeAttribute('disabled');
380 }
381
382 export function objectFlip(obj: any) {
383   const ret = {};
384   Object.keys(obj).forEach(key => {
385     ret[obj[key]] = key;
386   });
387   return ret;
388 }
389
390 export function pictshareAvatarThumbnail(src: string): string {
391   // sample url: http://localhost:8535/pictshare/gs7xuu.jpg
392   let split = src.split('pictshare');
393   let out = `${split[0]}pictshare/96${split[1]}`;
394   return out;
395 }
396
397 export function showAvatars(): boolean {
398   return (
399     (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
400     !UserService.Instance.user
401   );
402 }
403
404 /// Converts to image thumbnail (only supports pictshare currently)
405 export function imageThumbnailer(url: string): string {
406   let split = url.split('pictshare');
407   if (split.length > 1) {
408     let out = `${split[0]}pictshare/192${split[1]}`;
409     return out;
410   } else {
411     return url;
412   }
413 }
414
415 export function isCommentType(item: Comment | PrivateMessage): item is Comment {
416   return (item as Comment).community_id !== undefined;
417 }
418
419 export function toast(text: string, background: string = 'success') {
420   let backgroundColor = `var(--${background})`;
421   Toastify({
422     text: text,
423     backgroundColor: backgroundColor,
424     gravity: 'bottom',
425     position: 'left',
426   }).showToast();
427 }
428
429 export function setupTribute(): Tribute {
430   return new Tribute({
431     collection: [
432       // Emojis
433       {
434         trigger: ':',
435         menuItemTemplate: (item: any) => {
436           let emoji = `:${item.original.key}:`;
437           return `${item.original.val} ${emoji}`;
438         },
439         selectTemplate: (item: any) => {
440           return `:${item.original.key}:`;
441         },
442         values: Object.entries(emojiShortName).map(e => {
443           return { key: e[1], val: e[0] };
444         }),
445         allowSpaces: false,
446         autocompleteMode: true,
447         menuItemLimit: mentionDropdownFetchLimit,
448       },
449       // Users
450       {
451         trigger: '@',
452         selectTemplate: (item: any) => {
453           return `[/u/${item.original.key}](/u/${item.original.key})`;
454         },
455         values: (text: string, cb: any) => {
456           userSearch(text, (users: any) => cb(users));
457         },
458         allowSpaces: false,
459         autocompleteMode: true,
460         menuItemLimit: mentionDropdownFetchLimit,
461       },
462
463       // Communities
464       {
465         trigger: '#',
466         selectTemplate: (item: any) => {
467           return `[/c/${item.original.key}](/c/${item.original.key})`;
468         },
469         values: (text: string, cb: any) => {
470           communitySearch(text, (communities: any) => cb(communities));
471         },
472         allowSpaces: false,
473         autocompleteMode: true,
474         menuItemLimit: mentionDropdownFetchLimit,
475       },
476     ],
477   });
478 }
479
480 function userSearch(text: string, cb: any) {
481   if (text) {
482     let form: SearchForm = {
483       q: text,
484       type_: SearchType[SearchType.Users],
485       sort: SortType[SortType.TopAll],
486       page: 1,
487       limit: mentionDropdownFetchLimit,
488     };
489
490     WebSocketService.Instance.search(form);
491
492     this.userSub = WebSocketService.Instance.subject.subscribe(
493       msg => {
494         let res = wsJsonToRes(msg);
495         if (res.op == UserOperation.Search) {
496           let data = res.data as SearchResponse;
497           let users = data.users.map(u => {
498             return { key: u.name };
499           });
500           cb(users);
501           this.userSub.unsubscribe();
502         }
503       },
504       err => console.error(err),
505       () => console.log('complete')
506     );
507   } else {
508     cb([]);
509   }
510 }
511
512 function communitySearch(text: string, cb: any) {
513   if (text) {
514     let form: SearchForm = {
515       q: text,
516       type_: SearchType[SearchType.Communities],
517       sort: SortType[SortType.TopAll],
518       page: 1,
519       limit: mentionDropdownFetchLimit,
520     };
521
522     WebSocketService.Instance.search(form);
523
524     this.communitySub = WebSocketService.Instance.subject.subscribe(
525       msg => {
526         let res = wsJsonToRes(msg);
527         if (res.op == UserOperation.Search) {
528           let data = res.data as SearchResponse;
529           let communities = data.communities.map(u => {
530             return { key: u.name };
531           });
532           cb(communities);
533           this.communitySub.unsubscribe();
534         }
535       },
536       err => console.error(err),
537       () => console.log('complete')
538     );
539   } else {
540     cb([]);
541   }
542 }
543
544 export function getListingTypeFromProps(props: any): ListingType {
545   return props.match.params.listing_type
546     ? routeListingTypeToEnum(props.match.params.listing_type)
547     : UserService.Instance.user
548     ? UserService.Instance.user.default_listing_type
549     : ListingType.All;
550 }
551
552 // TODO might need to add a user setting for this too
553 export function getDataTypeFromProps(props: any): DataType {
554   return props.match.params.data_type
555     ? routeDataTypeToEnum(props.match.params.data_type)
556     : DataType.Post;
557 }
558
559 export function getSortTypeFromProps(props: any): SortType {
560   return props.match.params.sort
561     ? routeSortTypeToEnum(props.match.params.sort)
562     : UserService.Instance.user
563     ? UserService.Instance.user.default_sort_type
564     : SortType.Hot;
565 }
566
567 export function getPageFromProps(props: any): number {
568   return props.match.params.page ? Number(props.match.params.page) : 1;
569 }
570
571 export function editCommentRes(
572   data: CommentResponse,
573   comments: Array<Comment>
574 ) {
575   let found = comments.find(c => c.id == data.comment.id);
576   if (found) {
577     found.content = data.comment.content;
578     found.updated = data.comment.updated;
579     found.removed = data.comment.removed;
580     found.deleted = data.comment.deleted;
581     found.upvotes = data.comment.upvotes;
582     found.downvotes = data.comment.downvotes;
583     found.score = data.comment.score;
584   }
585 }
586
587 export function saveCommentRes(
588   data: CommentResponse,
589   comments: Array<Comment>
590 ) {
591   let found = comments.find(c => c.id == data.comment.id);
592   if (found) {
593     found.saved = data.comment.saved;
594   }
595 }
596
597 export function createCommentLikeRes(
598   data: CommentResponse,
599   comments: Array<Comment>
600 ) {
601   let found: Comment = comments.find(c => c.id === data.comment.id);
602   if (found) {
603     found.score = data.comment.score;
604     found.upvotes = data.comment.upvotes;
605     found.downvotes = data.comment.downvotes;
606     if (data.comment.my_vote !== null) {
607       found.my_vote = data.comment.my_vote;
608     }
609   }
610 }
611
612 export function createPostLikeFindRes(data: PostResponse, posts: Array<Post>) {
613   let found = posts.find(c => c.id == data.post.id);
614   if (found) {
615     createPostLikeRes(data, found);
616   }
617 }
618
619 export function createPostLikeRes(data: PostResponse, post: Post) {
620   if (post) {
621     post.score = data.post.score;
622     post.upvotes = data.post.upvotes;
623     post.downvotes = data.post.downvotes;
624     if (data.post.my_vote !== null) {
625       post.my_vote = data.post.my_vote;
626     }
627   }
628 }
629
630 export function editPostFindRes(data: PostResponse, posts: Array<Post>) {
631   let found = posts.find(c => c.id == data.post.id);
632   if (found) {
633     editPostRes(data, found);
634   }
635 }
636
637 export function editPostRes(data: PostResponse, post: Post) {
638   if (post) {
639     post.url = data.post.url;
640     post.name = data.post.name;
641     post.nsfw = data.post.nsfw;
642   }
643 }
644
645 export function commentsToFlatNodes(
646   comments: Array<Comment>
647 ): Array<CommentNode> {
648   let nodes: Array<CommentNode> = [];
649   for (let comment of comments) {
650     nodes.push({ comment: comment });
651   }
652   return nodes;
653 }
654
655 export function commentSort(tree: Array<CommentNode>, sort: CommentSortType) {
656   // First, put removed and deleted comments at the bottom, then do your other sorts
657   if (sort == CommentSortType.Top) {
658     tree.sort(
659       (a, b) =>
660         +a.comment.removed - +b.comment.removed ||
661         +a.comment.deleted - +b.comment.deleted ||
662         b.comment.score - a.comment.score
663     );
664   } else if (sort == CommentSortType.New) {
665     tree.sort(
666       (a, b) =>
667         +a.comment.removed - +b.comment.removed ||
668         +a.comment.deleted - +b.comment.deleted ||
669         b.comment.published.localeCompare(a.comment.published)
670     );
671   } else if (sort == CommentSortType.Old) {
672     tree.sort(
673       (a, b) =>
674         +a.comment.removed - +b.comment.removed ||
675         +a.comment.deleted - +b.comment.deleted ||
676         a.comment.published.localeCompare(b.comment.published)
677     );
678   } else if (sort == CommentSortType.Hot) {
679     tree.sort(
680       (a, b) =>
681         +a.comment.removed - +b.comment.removed ||
682         +a.comment.deleted - +b.comment.deleted ||
683         hotRankComment(b.comment) - hotRankComment(a.comment)
684     );
685   }
686
687   // Go through the children recursively
688   for (let node of tree) {
689     if (node.children) {
690       commentSort(node.children, sort);
691     }
692   }
693 }
694
695 export function commentSortSortType(tree: Array<CommentNode>, sort: SortType) {
696   commentSort(tree, convertCommentSortType(sort));
697 }
698
699 function convertCommentSortType(sort: SortType): CommentSortType {
700   if (
701     sort == SortType.TopAll ||
702     sort == SortType.TopDay ||
703     sort == SortType.TopWeek ||
704     sort == SortType.TopMonth ||
705     sort == SortType.TopYear
706   ) {
707     return CommentSortType.Top;
708   } else if (sort == SortType.New) {
709     return CommentSortType.New;
710   } else if (sort == SortType.Hot) {
711     return CommentSortType.Hot;
712   } else {
713     return CommentSortType.Hot;
714   }
715 }
716
717 export function postSort(posts: Array<Post>, sort: SortType) {
718   // First, put removed and deleted comments at the bottom, then do your other sorts
719   if (
720     sort == SortType.TopAll ||
721     sort == SortType.TopDay ||
722     sort == SortType.TopWeek ||
723     sort == SortType.TopMonth ||
724     sort == SortType.TopYear
725   ) {
726     posts.sort(
727       (a, b) =>
728         +a.removed - +b.removed || +a.deleted - +b.deleted || b.score - a.score
729     );
730   } else if (sort == SortType.New) {
731     posts.sort(
732       (a, b) =>
733         +a.removed - +b.removed ||
734         +a.deleted - +b.deleted ||
735         b.published.localeCompare(a.published)
736     );
737   } else if (sort == SortType.Hot) {
738     posts.sort(
739       (a, b) =>
740         +a.removed - +b.removed ||
741         +a.deleted - +b.deleted ||
742         hotRankPost(b) - hotRankPost(a)
743     );
744   }
745 }