]> Untitled Git - lemmy.git/blob - ui/src/utils.ts
Proper comment-node depth coloring.
[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         menuShowMinLength: 2,
450       },
451       // Users
452       {
453         trigger: '@',
454         selectTemplate: (item: any) => {
455           return `[/u/${item.original.key}](/u/${item.original.key})`;
456         },
457         values: (text: string, cb: any) => {
458           userSearch(text, (users: any) => cb(users));
459         },
460         allowSpaces: false,
461         autocompleteMode: true,
462         menuItemLimit: mentionDropdownFetchLimit,
463         menuShowMinLength: 2,
464       },
465
466       // Communities
467       {
468         trigger: '#',
469         selectTemplate: (item: any) => {
470           return `[/c/${item.original.key}](/c/${item.original.key})`;
471         },
472         values: (text: string, cb: any) => {
473           communitySearch(text, (communities: any) => cb(communities));
474         },
475         allowSpaces: false,
476         autocompleteMode: true,
477         menuItemLimit: mentionDropdownFetchLimit,
478         menuShowMinLength: 2,
479       },
480     ],
481   });
482 }
483
484 let tippyInstance = tippy('[data-tippy-content]');
485
486 export function setupTippy() {
487   tippyInstance.forEach(e => e.destroy());
488   tippyInstance = tippy('[data-tippy-content]', {
489     delay: [500, 0],
490     // Display on "long press"
491     touch: ['hold', 500],
492   });
493 }
494
495 function userSearch(text: string, cb: any) {
496   if (text) {
497     let form: SearchForm = {
498       q: text,
499       type_: SearchType[SearchType.Users],
500       sort: SortType[SortType.TopAll],
501       page: 1,
502       limit: mentionDropdownFetchLimit,
503     };
504
505     WebSocketService.Instance.search(form);
506
507     this.userSub = WebSocketService.Instance.subject.subscribe(
508       msg => {
509         let res = wsJsonToRes(msg);
510         if (res.op == UserOperation.Search) {
511           let data = res.data as SearchResponse;
512           let users = data.users.map(u => {
513             return { key: u.name };
514           });
515           cb(users);
516           this.userSub.unsubscribe();
517         }
518       },
519       err => console.error(err),
520       () => console.log('complete')
521     );
522   } else {
523     cb([]);
524   }
525 }
526
527 function communitySearch(text: string, cb: any) {
528   if (text) {
529     let form: SearchForm = {
530       q: text,
531       type_: SearchType[SearchType.Communities],
532       sort: SortType[SortType.TopAll],
533       page: 1,
534       limit: mentionDropdownFetchLimit,
535     };
536
537     WebSocketService.Instance.search(form);
538
539     this.communitySub = WebSocketService.Instance.subject.subscribe(
540       msg => {
541         let res = wsJsonToRes(msg);
542         if (res.op == UserOperation.Search) {
543           let data = res.data as SearchResponse;
544           let communities = data.communities.map(u => {
545             return { key: u.name };
546           });
547           cb(communities);
548           this.communitySub.unsubscribe();
549         }
550       },
551       err => console.error(err),
552       () => console.log('complete')
553     );
554   } else {
555     cb([]);
556   }
557 }
558
559 export function getListingTypeFromProps(props: any): ListingType {
560   return props.match.params.listing_type
561     ? routeListingTypeToEnum(props.match.params.listing_type)
562     : UserService.Instance.user
563     ? UserService.Instance.user.default_listing_type
564     : ListingType.All;
565 }
566
567 // TODO might need to add a user setting for this too
568 export function getDataTypeFromProps(props: any): DataType {
569   return props.match.params.data_type
570     ? routeDataTypeToEnum(props.match.params.data_type)
571     : DataType.Post;
572 }
573
574 export function getSortTypeFromProps(props: any): SortType {
575   return props.match.params.sort
576     ? routeSortTypeToEnum(props.match.params.sort)
577     : UserService.Instance.user
578     ? UserService.Instance.user.default_sort_type
579     : SortType.Hot;
580 }
581
582 export function getPageFromProps(props: any): number {
583   return props.match.params.page ? Number(props.match.params.page) : 1;
584 }
585
586 export function editCommentRes(
587   data: CommentResponse,
588   comments: Array<Comment>
589 ) {
590   let found = comments.find(c => c.id == data.comment.id);
591   if (found) {
592     found.content = data.comment.content;
593     found.updated = data.comment.updated;
594     found.removed = data.comment.removed;
595     found.deleted = data.comment.deleted;
596     found.upvotes = data.comment.upvotes;
597     found.downvotes = data.comment.downvotes;
598     found.score = data.comment.score;
599   }
600 }
601
602 export function saveCommentRes(
603   data: CommentResponse,
604   comments: Array<Comment>
605 ) {
606   let found = comments.find(c => c.id == data.comment.id);
607   if (found) {
608     found.saved = data.comment.saved;
609   }
610 }
611
612 export function createCommentLikeRes(
613   data: CommentResponse,
614   comments: Array<Comment>
615 ) {
616   let found: Comment = comments.find(c => c.id === data.comment.id);
617   if (found) {
618     found.score = data.comment.score;
619     found.upvotes = data.comment.upvotes;
620     found.downvotes = data.comment.downvotes;
621     if (data.comment.my_vote !== null) {
622       found.my_vote = data.comment.my_vote;
623     }
624   }
625 }
626
627 export function createPostLikeFindRes(data: PostResponse, posts: Array<Post>) {
628   let found = posts.find(c => c.id == data.post.id);
629   if (found) {
630     createPostLikeRes(data, found);
631   }
632 }
633
634 export function createPostLikeRes(data: PostResponse, post: Post) {
635   if (post) {
636     post.score = data.post.score;
637     post.upvotes = data.post.upvotes;
638     post.downvotes = data.post.downvotes;
639     if (data.post.my_vote !== null) {
640       post.my_vote = data.post.my_vote;
641     }
642   }
643 }
644
645 export function editPostFindRes(data: PostResponse, posts: Array<Post>) {
646   let found = posts.find(c => c.id == data.post.id);
647   if (found) {
648     editPostRes(data, found);
649   }
650 }
651
652 export function editPostRes(data: PostResponse, post: Post) {
653   if (post) {
654     post.url = data.post.url;
655     post.name = data.post.name;
656     post.nsfw = data.post.nsfw;
657   }
658 }
659
660 export function commentsToFlatNodes(
661   comments: Array<Comment>
662 ): Array<CommentNode> {
663   let nodes: Array<CommentNode> = [];
664   for (let comment of comments) {
665     nodes.push({ comment: comment });
666   }
667   return nodes;
668 }
669
670 export function commentSort(tree: Array<CommentNode>, sort: CommentSortType) {
671   // First, put removed and deleted comments at the bottom, then do your other sorts
672   if (sort == CommentSortType.Top) {
673     tree.sort(
674       (a, b) =>
675         +a.comment.removed - +b.comment.removed ||
676         +a.comment.deleted - +b.comment.deleted ||
677         b.comment.score - a.comment.score
678     );
679   } else if (sort == CommentSortType.New) {
680     tree.sort(
681       (a, b) =>
682         +a.comment.removed - +b.comment.removed ||
683         +a.comment.deleted - +b.comment.deleted ||
684         b.comment.published.localeCompare(a.comment.published)
685     );
686   } else if (sort == CommentSortType.Old) {
687     tree.sort(
688       (a, b) =>
689         +a.comment.removed - +b.comment.removed ||
690         +a.comment.deleted - +b.comment.deleted ||
691         a.comment.published.localeCompare(b.comment.published)
692     );
693   } else if (sort == CommentSortType.Hot) {
694     tree.sort(
695       (a, b) =>
696         +a.comment.removed - +b.comment.removed ||
697         +a.comment.deleted - +b.comment.deleted ||
698         hotRankComment(b.comment) - hotRankComment(a.comment)
699     );
700   }
701
702   // Go through the children recursively
703   for (let node of tree) {
704     if (node.children) {
705       commentSort(node.children, sort);
706     }
707   }
708 }
709
710 export function commentSortSortType(tree: Array<CommentNode>, sort: SortType) {
711   commentSort(tree, convertCommentSortType(sort));
712 }
713
714 function convertCommentSortType(sort: SortType): CommentSortType {
715   if (
716     sort == SortType.TopAll ||
717     sort == SortType.TopDay ||
718     sort == SortType.TopWeek ||
719     sort == SortType.TopMonth ||
720     sort == SortType.TopYear
721   ) {
722     return CommentSortType.Top;
723   } else if (sort == SortType.New) {
724     return CommentSortType.New;
725   } else if (sort == SortType.Hot) {
726     return CommentSortType.Hot;
727   } else {
728     return CommentSortType.Hot;
729   }
730 }
731
732 export function postSort(
733   posts: Array<Post>,
734   sort: SortType,
735   communityType: boolean
736 ) {
737   // First, put removed and deleted comments at the bottom, then do your other sorts
738   if (
739     sort == SortType.TopAll ||
740     sort == SortType.TopDay ||
741     sort == SortType.TopWeek ||
742     sort == SortType.TopMonth ||
743     sort == SortType.TopYear
744   ) {
745     posts.sort(
746       (a, b) =>
747         +a.removed - +b.removed ||
748         +a.deleted - +b.deleted ||
749         (communityType && +b.stickied - +a.stickied) ||
750         b.score - a.score
751     );
752   } else if (sort == SortType.New) {
753     posts.sort(
754       (a, b) =>
755         +a.removed - +b.removed ||
756         +a.deleted - +b.deleted ||
757         (communityType && +b.stickied - +a.stickied) ||
758         b.published.localeCompare(a.published)
759     );
760   } else if (sort == SortType.Hot) {
761     posts.sort(
762       (a, b) =>
763         +a.removed - +b.removed ||
764         +a.deleted - +b.deleted ||
765         (communityType && +b.stickied - +a.stickied) ||
766         hotRankPost(b) - hotRankPost(a)
767     );
768   }
769 }
770
771 export const colorList: Array<string> = [...Array(10)].map(() => randomHsl());
772
773 export function randomHsl() {
774   return `hsla(${Math.random() * 360}, 100%, 50%, 1)`;
775 }