]> Untitled Git - lemmy.git/blob - ui/src/utils.ts
Fixing some technical debt. Fixes #524
[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
15 import {
16   UserOperation,
17   Comment,
18   CommentNode,
19   Post,
20   PrivateMessage,
21   User,
22   SortType,
23   ListingType,
24   DataType,
25   SearchType,
26   WebSocketResponse,
27   WebSocketJsonResponse,
28   SearchForm,
29   SearchResponse,
30   CommentResponse,
31   PostResponse,
32 } from './interfaces';
33 import { UserService, WebSocketService } from './services';
34
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';
42
43 export const repoUrl = 'https://github.com/dessalines/lemmy';
44 export const markdownHelpUrl = 'https://commonmark.org/help/';
45 export const archiveUrl = 'https://archive.is';
46
47 export const postRefetchSeconds: number = 60 * 1000;
48 export const fetchLimit: number = 20;
49 export const mentionDropdownFetchLimit = 10;
50
51 export function randomStr() {
52   return Math.random()
53     .toString(36)
54     .replace(/[^a-z]+/g, '')
55     .substr(2, 10);
56 }
57
58 export function wsJsonToRes(msg: WebSocketJsonResponse): WebSocketResponse {
59   let opStr: string = msg.op;
60   return {
61     op: UserOperation[opStr],
62     data: msg.data,
63   };
64 }
65
66 export const md = new markdown_it({
67   html: false,
68   linkify: true,
69   typographer: true,
70 })
71   .use(markdown_it_container, 'spoiler', {
72     validate: function(params: any) {
73       return params.trim().match(/^spoiler\s+(.*)$/);
74     },
75
76     render: function(tokens: any, idx: any) {
77       var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
78
79       if (tokens[idx].nesting === 1) {
80         // opening tag
81         return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
82       } else {
83         // closing tag
84         return '</details>\n';
85       }
86     },
87   })
88   .use(markdownitEmoji, {
89     defs: objectFlip(emojiShortName),
90   });
91
92 md.renderer.rules.emoji = function(token, idx) {
93   return twemoji.parse(token[idx].content);
94 };
95
96 export function hotRank(comment: Comment): number {
97   // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
98
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;
102
103   let rank =
104     (10000 * Math.log10(Math.max(1, 3 + comment.score))) /
105     Math.pow(hoursElapsed + 2, 1.8);
106
107   // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
108
109   return rank;
110 }
111
112 export function mdToHtml(text: string) {
113   return { __html: md.render(text) };
114 }
115
116 export function getUnixTime(text: string): number {
117   return text ? new Date(text).getTime() / 1000 : undefined;
118 }
119
120 export function addTypeInfo<T>(
121   arr: Array<T>,
122   name: string
123 ): Array<{ type_: string; data: T }> {
124   return arr.map(e => {
125     return { type_: name, data: e };
126   });
127 }
128
129 export function canMod(
130   user: User,
131   modIds: Array<number>,
132   creator_id: number,
133   onSelf: boolean = false
134 ): boolean {
135   // You can do moderator actions only on the mods added after you.
136   if (user) {
137     let yourIndex = modIds.findIndex(id => id == user.id);
138     if (yourIndex == -1) {
139       return false;
140     } else {
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);
144     }
145   } else {
146     return false;
147   }
148 }
149
150 export function isMod(modIds: Array<number>, creator_id: number): boolean {
151   return modIds.includes(creator_id);
152 }
153
154 var imageRegex = new RegExp(
155   `(http)?s?:?(\/\/[^"']*\.(?:png|jpg|jpeg|gif|png|svg))`
156 );
157 var videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
158
159 export function isImage(url: string) {
160   return imageRegex.test(url);
161 }
162
163 export function isVideo(url: string) {
164   return videoRegex.test(url);
165 }
166
167 export function validURL(str: string) {
168   try {
169     return !!new URL(str);
170   } catch {
171     return false;
172   }
173 }
174
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());
178 }
179
180 export function capitalizeFirstLetter(str: string): string {
181   return str.charAt(0).toUpperCase() + str.slice(1);
182 }
183
184 export function routeSortTypeToEnum(sort: string): SortType {
185   if (sort == 'new') {
186     return SortType.New;
187   } else if (sort == 'hot') {
188     return SortType.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;
199   }
200 }
201
202 export function routeListingTypeToEnum(type: string): ListingType {
203   return ListingType[capitalizeFirstLetter(type)];
204 }
205
206 export function routeDataTypeToEnum(type: string): DataType {
207   return DataType[capitalizeFirstLetter(type)];
208 }
209
210 export function routeSearchTypeToEnum(type: string): SearchType {
211   return SearchType[capitalizeFirstLetter(type)];
212 }
213
214 export async function getPageTitle(url: string) {
215   let res = await fetch(`https://textance.herokuapp.com/title/${url}`);
216   let data = await res.text();
217   return data;
218 }
219
220 export function debounce(
221   func: any,
222   wait: number = 1000,
223   immediate: boolean = false
224 ) {
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.
228   let timeout: any;
229
230   // Calling debounce returns a new anonymous function
231   return function() {
232     // reference the context and args for the setTimeout function
233     var context = this,
234       args = arguments;
235
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;
239
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);
245
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
250       timeout = null;
251
252       // Check if the function already ran with the immediate flag
253       if (!immediate) {
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);
258       }
259     }, wait);
260
261     // Immediate mode and no wait timer? Execute the function..
262     if (callNow) func.apply(context, args);
263   };
264 }
265
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' },
281 ];
282
283 export function getLanguage(): string {
284   let user = UserService.Instance.user;
285   let lang = user && user.lang ? user.lang : 'browser';
286
287   if (lang == 'browser') {
288     return getBrowserLanguage();
289   } else {
290     return lang;
291   }
292 }
293
294 export function getBrowserLanguage(): string {
295   return navigator.language;
296 }
297
298 export function getMomentLanguage(): string {
299   let lang = getLanguage();
300   if (lang.startsWith('zh')) {
301     lang = 'zh-cn';
302   } else if (lang.startsWith('sv')) {
303     lang = 'sv';
304   } else if (lang.startsWith('fr')) {
305     lang = 'fr';
306   } else if (lang.startsWith('de')) {
307     lang = 'de';
308   } else if (lang.startsWith('ru')) {
309     lang = 'ru';
310   } else if (lang.startsWith('es')) {
311     lang = 'es';
312   } else if (lang.startsWith('eo')) {
313     lang = 'eo';
314   } else if (lang.startsWith('nl')) {
315     lang = 'nl';
316   } else if (lang.startsWith('it')) {
317     lang = 'it';
318   } else if (lang.startsWith('fi')) {
319     lang = 'fi';
320   } else if (lang.startsWith('ca')) {
321     lang = 'ca';
322   } else if (lang.startsWith('fa')) {
323     lang = 'fa';
324   } else if (lang.startsWith('pt')) {
325     lang = 'pt-br';
326   } else {
327     lang = 'en';
328   }
329   return lang;
330 }
331
332 export const themes = [
333   'litera',
334   'materia',
335   'minty',
336   'solar',
337   'united',
338   'cyborg',
339   'darkly',
340   'journal',
341   'sketchy',
342   'vaporwave',
343   'vaporwave-dark',
344   'i386',
345 ];
346
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]);
351     if (styleSheet) {
352       styleSheet.setAttribute('disabled', 'disabled');
353     }
354   }
355
356   // Load the theme dynamically
357   if (!document.getElementById(theme)) {
358     var head = document.getElementsByTagName('head')[0];
359     var link = document.createElement('link');
360     link.id = theme;
361     link.rel = 'stylesheet';
362     link.type = 'text/css';
363     link.href = `/static/assets/css/themes/${theme}.min.css`;
364     link.media = 'all';
365     head.appendChild(link);
366   }
367   document.getElementById(theme).removeAttribute('disabled');
368 }
369
370 export function objectFlip(obj: any) {
371   const ret = {};
372   Object.keys(obj).forEach(key => {
373     ret[obj[key]] = key;
374   });
375   return ret;
376 }
377
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]}`;
382   return out;
383 }
384
385 export function showAvatars(): boolean {
386   return (
387     (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
388     !UserService.Instance.user
389   );
390 }
391
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]}`;
397     return out;
398   } else {
399     return url;
400   }
401 }
402
403 export function isCommentType(item: Comment | PrivateMessage): item is Comment {
404   return (item as Comment).community_id !== undefined;
405 }
406
407 export function toast(text: string, background: string = 'success') {
408   let backgroundColor = `var(--${background})`;
409   Toastify({
410     text: text,
411     backgroundColor: backgroundColor,
412     gravity: 'bottom',
413     position: 'left',
414   }).showToast();
415 }
416
417 export function setupTribute(): Tribute {
418   return new Tribute({
419     collection: [
420       // Emojis
421       {
422         trigger: ':',
423         menuItemTemplate: (item: any) => {
424           let emoji = `:${item.original.key}:`;
425           return `${item.original.val} ${emoji}`;
426         },
427         selectTemplate: (item: any) => {
428           return `:${item.original.key}:`;
429         },
430         values: Object.entries(emojiShortName).map(e => {
431           return { key: e[1], val: e[0] };
432         }),
433         allowSpaces: false,
434         autocompleteMode: true,
435         menuItemLimit: mentionDropdownFetchLimit,
436       },
437       // Users
438       {
439         trigger: '@',
440         selectTemplate: (item: any) => {
441           return `[/u/${item.original.key}](/u/${item.original.key})`;
442         },
443         values: (text: string, cb: any) => {
444           userSearch(text, (users: any) => cb(users));
445         },
446         allowSpaces: false,
447         autocompleteMode: true,
448         menuItemLimit: mentionDropdownFetchLimit,
449       },
450
451       // Communities
452       {
453         trigger: '#',
454         selectTemplate: (item: any) => {
455           return `[/c/${item.original.key}](/c/${item.original.key})`;
456         },
457         values: (text: string, cb: any) => {
458           communitySearch(text, (communities: any) => cb(communities));
459         },
460         allowSpaces: false,
461         autocompleteMode: true,
462         menuItemLimit: mentionDropdownFetchLimit,
463       },
464     ],
465   });
466 }
467
468 function userSearch(text: string, cb: any) {
469   if (text) {
470     let form: SearchForm = {
471       q: text,
472       type_: SearchType[SearchType.Users],
473       sort: SortType[SortType.TopAll],
474       page: 1,
475       limit: mentionDropdownFetchLimit,
476     };
477
478     WebSocketService.Instance.search(form);
479
480     this.userSub = WebSocketService.Instance.subject.subscribe(
481       msg => {
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 };
487           });
488           cb(users);
489           this.userSub.unsubscribe();
490         }
491       },
492       err => console.error(err),
493       () => console.log('complete')
494     );
495   } else {
496     cb([]);
497   }
498 }
499
500 function communitySearch(text: string, cb: any) {
501   if (text) {
502     let form: SearchForm = {
503       q: text,
504       type_: SearchType[SearchType.Communities],
505       sort: SortType[SortType.TopAll],
506       page: 1,
507       limit: mentionDropdownFetchLimit,
508     };
509
510     WebSocketService.Instance.search(form);
511
512     this.communitySub = WebSocketService.Instance.subject.subscribe(
513       msg => {
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 };
519           });
520           cb(communities);
521           this.communitySub.unsubscribe();
522         }
523       },
524       err => console.error(err),
525       () => console.log('complete')
526     );
527   } else {
528     cb([]);
529   }
530 }
531
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
537     : ListingType.All;
538 }
539
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)
544     : DataType.Post;
545 }
546
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
552     : SortType.Hot;
553 }
554
555 export function getPageFromProps(props: any): number {
556   return props.match.params.page ? Number(props.match.params.page) : 1;
557 }
558
559 export function editCommentRes(
560   data: CommentResponse,
561   comments: Array<Comment>
562 ) {
563   let found = comments.find(c => c.id == data.comment.id);
564   if (found) {
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;
572   }
573 }
574
575 export function saveCommentRes(
576   data: CommentResponse,
577   comments: Array<Comment>
578 ) {
579   let found = comments.find(c => c.id == data.comment.id);
580   if (found) {
581     found.saved = data.comment.saved;
582   }
583 }
584
585 export function createCommentLikeRes(
586   data: CommentResponse,
587   comments: Array<Comment>
588 ) {
589   let found: Comment = comments.find(c => c.id === data.comment.id);
590   if (found) {
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;
598     }
599   }
600 }
601
602 export function createPostLikeFindRes(data: PostResponse, posts: Array<Post>) {
603   let found = posts.find(c => c.id == data.post.id);
604   if (found) {
605     createPostLikeRes(data, found);
606   }
607 }
608
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;
617   }
618 }
619
620 export function editPostFindRes(data: PostResponse, posts: Array<Post>) {
621   let found = posts.find(c => c.id == data.post.id);
622   if (found) {
623     editPostRes(data, found);
624   }
625 }
626
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;
631 }
632
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 });
639   }
640   return nodes;
641 }