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