]> Untitled Git - lemmy.git/blob - ui/src/utils.ts
Merge branch 'dev'
[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
11 import {
12   UserOperation,
13   Comment,
14   PrivateMessage,
15   User,
16   SortType,
17   ListingType,
18   SearchType,
19   WebSocketResponse,
20   WebSocketJsonResponse,
21   SearchForm,
22   SearchResponse,
23 } from './interfaces';
24 import { UserService, WebSocketService } from './services';
25
26 import Tribute from 'tributejs/src/Tribute.js';
27 import markdown_it from 'markdown-it';
28 import markdownitEmoji from 'markdown-it-emoji/light';
29 import markdown_it_container from 'markdown-it-container';
30 import twemoji from 'twemoji';
31 import emojiShortName from 'emoji-short-name';
32 import Toastify from 'toastify-js';
33
34 export const repoUrl = 'https://github.com/dessalines/lemmy';
35 export const markdownHelpUrl = 'https://commonmark.org/help/';
36 export const archiveUrl = 'https://archive.is';
37
38 export const postRefetchSeconds: number = 60 * 1000;
39 export const fetchLimit: number = 20;
40 export const mentionDropdownFetchLimit = 10;
41
42 export function randomStr() {
43   return Math.random()
44     .toString(36)
45     .replace(/[^a-z]+/g, '')
46     .substr(2, 10);
47 }
48
49 export function wsJsonToRes(msg: WebSocketJsonResponse): WebSocketResponse {
50   let opStr: string = msg.op;
51   return {
52     op: UserOperation[opStr],
53     data: msg.data,
54   };
55 }
56
57 export const md = new markdown_it({
58   html: false,
59   linkify: true,
60   typographer: true,
61 })
62   .use(markdown_it_container, 'spoiler', {
63     validate: function(params: any) {
64       return params.trim().match(/^spoiler\s+(.*)$/);
65     },
66
67     render: function(tokens: any, idx: any) {
68       var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
69
70       if (tokens[idx].nesting === 1) {
71         // opening tag
72         return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
73       } else {
74         // closing tag
75         return '</details>\n';
76       }
77     },
78   })
79   .use(markdownitEmoji, {
80     defs: objectFlip(emojiShortName),
81   });
82
83 md.renderer.rules.emoji = function(token, idx) {
84   return twemoji.parse(token[idx].content);
85 };
86
87 export function hotRank(comment: Comment): number {
88   // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
89
90   let date: Date = new Date(comment.published + 'Z'); // Add Z to convert from UTC date
91   let now: Date = new Date();
92   let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
93
94   let rank =
95     (10000 * Math.log10(Math.max(1, 3 + comment.score))) /
96     Math.pow(hoursElapsed + 2, 1.8);
97
98   // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
99
100   return rank;
101 }
102
103 export function mdToHtml(text: string) {
104   return { __html: md.render(text) };
105 }
106
107 export function getUnixTime(text: string): number {
108   return text ? new Date(text).getTime() / 1000 : undefined;
109 }
110
111 export function addTypeInfo<T>(
112   arr: Array<T>,
113   name: string
114 ): Array<{ type_: string; data: T }> {
115   return arr.map(e => {
116     return { type_: name, data: e };
117   });
118 }
119
120 export function canMod(
121   user: User,
122   modIds: Array<number>,
123   creator_id: number,
124   onSelf: boolean = false
125 ): boolean {
126   // You can do moderator actions only on the mods added after you.
127   if (user) {
128     let yourIndex = modIds.findIndex(id => id == user.id);
129     if (yourIndex == -1) {
130       return false;
131     } else {
132       // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
133       modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
134       return !modIds.includes(creator_id);
135     }
136   } else {
137     return false;
138   }
139 }
140
141 export function isMod(modIds: Array<number>, creator_id: number): boolean {
142   return modIds.includes(creator_id);
143 }
144
145 var imageRegex = new RegExp(
146   `(http)?s?:?(\/\/[^"']*\.(?:png|jpg|jpeg|gif|png|svg))`
147 );
148 var videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
149
150 export function isImage(url: string) {
151   return imageRegex.test(url);
152 }
153
154 export function isVideo(url: string) {
155   return videoRegex.test(url);
156 }
157
158 export function validURL(str: string) {
159   try {
160     return !!new URL(str);
161   } catch {
162     return false;
163   }
164 }
165
166 export function validEmail(email: string) {
167   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,}))$/;
168   return re.test(String(email).toLowerCase());
169 }
170
171 export function capitalizeFirstLetter(str: string): string {
172   return str.charAt(0).toUpperCase() + str.slice(1);
173 }
174
175 export function routeSortTypeToEnum(sort: string): SortType {
176   if (sort == 'new') {
177     return SortType.New;
178   } else if (sort == 'hot') {
179     return SortType.Hot;
180   } else if (sort == 'topday') {
181     return SortType.TopDay;
182   } else if (sort == 'topweek') {
183     return SortType.TopWeek;
184   } else if (sort == 'topmonth') {
185     return SortType.TopMonth;
186   } else if (sort == 'topyear') {
187     return SortType.TopYear;
188   } else if (sort == 'topall') {
189     return SortType.TopAll;
190   }
191 }
192
193 export function routeListingTypeToEnum(type: string): ListingType {
194   return ListingType[capitalizeFirstLetter(type)];
195 }
196
197 export function routeSearchTypeToEnum(type: string): SearchType {
198   return SearchType[capitalizeFirstLetter(type)];
199 }
200
201 export async function getPageTitle(url: string) {
202   let res = await fetch(`https://textance.herokuapp.com/title/${url}`);
203   let data = await res.text();
204   return data;
205 }
206
207 export function debounce(
208   func: any,
209   wait: number = 1000,
210   immediate: boolean = false
211 ) {
212   // 'private' variable for instance
213   // The returned function will be able to reference this due to closure.
214   // Each call to the returned function will share this common timer.
215   let timeout: any;
216
217   // Calling debounce returns a new anonymous function
218   return function() {
219     // reference the context and args for the setTimeout function
220     var context = this,
221       args = arguments;
222
223     // Should the function be called now? If immediate is true
224     //   and not already in a timeout then the answer is: Yes
225     var callNow = immediate && !timeout;
226
227     // This is the basic debounce behaviour where you can call this
228     //   function several times, but it will only execute once
229     //   [before or after imposing a delay].
230     //   Each time the returned function is called, the timer starts over.
231     clearTimeout(timeout);
232
233     // Set the new timeout
234     timeout = setTimeout(function() {
235       // Inside the timeout function, clear the timeout variable
236       // which will let the next execution run when in 'immediate' mode
237       timeout = null;
238
239       // Check if the function already ran with the immediate flag
240       if (!immediate) {
241         // Call the original function with apply
242         // apply lets you define the 'this' object as well as the arguments
243         //    (both captured before setTimeout)
244         func.apply(context, args);
245       }
246     }, wait);
247
248     // Immediate mode and no wait timer? Execute the function..
249     if (callNow) func.apply(context, args);
250   };
251 }
252
253 export const languages = [
254   { code: 'en', name: 'English' },
255   { code: 'eo', name: 'Esperanto' },
256   { code: 'es', name: 'Español' },
257   { code: 'de', name: 'Deutsch' },
258   { code: 'zh', name: '中文' },
259   { code: 'fr', name: 'Français' },
260   { code: 'sv', name: 'Svenska' },
261   { code: 'ru', name: 'Русский' },
262   { code: 'nl', name: 'Nederlands' },
263   { code: 'it', name: 'Italiano' },
264 ];
265
266 export function getLanguage(): string {
267   let user = UserService.Instance.user;
268   let lang = user && user.lang ? user.lang : 'browser';
269
270   if (lang == 'browser') {
271     return getBrowserLanguage();
272   } else {
273     return lang;
274   }
275 }
276
277 export function getBrowserLanguage(): string {
278   return navigator.language;
279 }
280
281 export function getMomentLanguage(): string {
282   let lang = getLanguage();
283   if (lang.startsWith('zh')) {
284     lang = 'zh-cn';
285   } else if (lang.startsWith('sv')) {
286     lang = 'sv';
287   } else if (lang.startsWith('fr')) {
288     lang = 'fr';
289   } else if (lang.startsWith('de')) {
290     lang = 'de';
291   } else if (lang.startsWith('ru')) {
292     lang = 'ru';
293   } else if (lang.startsWith('es')) {
294     lang = 'es';
295   } else if (lang.startsWith('eo')) {
296     lang = 'eo';
297   } else if (lang.startsWith('nl')) {
298     lang = 'nl';
299   } else if (lang.startsWith('it')) {
300     lang = 'it';
301   } else {
302     lang = 'en';
303   }
304   return lang;
305 }
306
307 export const themes = [
308   'litera',
309   'minty',
310   'solar',
311   'united',
312   'cyborg',
313   'darkly',
314   'journal',
315   'sketchy',
316   'vaporwave',
317   'vaporwave-dark',
318 ];
319
320 export function setTheme(theme: string = 'darkly') {
321   // unload all the other themes
322   for (var i = 0; i < themes.length; i++) {
323     let styleSheet = document.getElementById(themes[i]);
324     if (styleSheet) {
325       styleSheet.setAttribute('disabled', 'disabled');
326     }
327   }
328
329   // Load the theme dynamically
330   if (!document.getElementById(theme)) {
331     var head = document.getElementsByTagName('head')[0];
332     var link = document.createElement('link');
333     link.id = theme;
334     link.rel = 'stylesheet';
335     link.type = 'text/css';
336     link.href = `/static/assets/css/themes/${theme}.min.css`;
337     link.media = 'all';
338     head.appendChild(link);
339   }
340   document.getElementById(theme).removeAttribute('disabled');
341 }
342
343 export function objectFlip(obj: any) {
344   const ret = {};
345   Object.keys(obj).forEach(key => {
346     ret[obj[key]] = key;
347   });
348   return ret;
349 }
350
351 export function pictshareAvatarThumbnail(src: string): string {
352   // sample url: http://localhost:8535/pictshare/gs7xuu.jpg
353   let split = src.split('pictshare');
354   let out = `${split[0]}pictshare/96x96${split[1]}`;
355   return out;
356 }
357
358 export function showAvatars(): boolean {
359   return (
360     (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
361     !UserService.Instance.user
362   );
363 }
364
365 /// Converts to image thumbnail (only supports pictshare currently)
366 export function imageThumbnailer(url: string): string {
367   let split = url.split('pictshare');
368   if (split.length > 1) {
369     let out = `${split[0]}pictshare/140x140${split[1]}`;
370     return out;
371   } else {
372     return url;
373   }
374 }
375
376 export function isCommentType(item: Comment | PrivateMessage): item is Comment {
377   return (item as Comment).community_id !== undefined;
378 }
379
380 export function toast(text: string, background: string = 'success') {
381   let backgroundColor = `var(--${background})`;
382   Toastify({
383     text: text,
384     backgroundColor: backgroundColor,
385     gravity: 'bottom',
386     position: 'left',
387   }).showToast();
388 }
389
390 export function setupTribute(): Tribute {
391   return new Tribute({
392     collection: [
393       // Emojis
394       {
395         trigger: ':',
396         menuItemTemplate: (item: any) => {
397           let emoji = `:${item.original.key}:`;
398           return `${item.original.val} ${emoji}`;
399         },
400         selectTemplate: (item: any) => {
401           return `:${item.original.key}:`;
402         },
403         values: Object.entries(emojiShortName).map(e => {
404           return { key: e[1], val: e[0] };
405         }),
406         allowSpaces: false,
407         autocompleteMode: true,
408         menuItemLimit: mentionDropdownFetchLimit,
409       },
410       // Users
411       {
412         trigger: '@',
413         selectTemplate: (item: any) => {
414           return `[/u/${item.original.key}](/u/${item.original.key})`;
415         },
416         values: (text: string, cb: any) => {
417           userSearch(text, (users: any) => cb(users));
418         },
419         allowSpaces: false,
420         autocompleteMode: true,
421         menuItemLimit: mentionDropdownFetchLimit,
422       },
423
424       // Communities
425       {
426         trigger: '#',
427         selectTemplate: (item: any) => {
428           return `[/c/${item.original.key}](/c/${item.original.key})`;
429         },
430         values: (text: string, cb: any) => {
431           communitySearch(text, (communities: any) => cb(communities));
432         },
433         allowSpaces: false,
434         autocompleteMode: true,
435         menuItemLimit: mentionDropdownFetchLimit,
436       },
437     ],
438   });
439 }
440
441 function userSearch(text: string, cb: any) {
442   if (text) {
443     let form: SearchForm = {
444       q: text,
445       type_: SearchType[SearchType.Users],
446       sort: SortType[SortType.TopAll],
447       page: 1,
448       limit: mentionDropdownFetchLimit,
449     };
450
451     WebSocketService.Instance.search(form);
452
453     this.userSub = WebSocketService.Instance.subject.subscribe(
454       msg => {
455         let res = wsJsonToRes(msg);
456         if (res.op == UserOperation.Search) {
457           let data = res.data as SearchResponse;
458           let users = data.users.map(u => {
459             return { key: u.name };
460           });
461           cb(users);
462           this.userSub.unsubscribe();
463         }
464       },
465       err => console.error(err),
466       () => console.log('complete')
467     );
468   } else {
469     cb([]);
470   }
471 }
472
473 function communitySearch(text: string, cb: any) {
474   if (text) {
475     let form: SearchForm = {
476       q: text,
477       type_: SearchType[SearchType.Communities],
478       sort: SortType[SortType.TopAll],
479       page: 1,
480       limit: mentionDropdownFetchLimit,
481     };
482
483     WebSocketService.Instance.search(form);
484
485     this.communitySub = WebSocketService.Instance.subject.subscribe(
486       msg => {
487         let res = wsJsonToRes(msg);
488         if (res.op == UserOperation.Search) {
489           let data = res.data as SearchResponse;
490           let communities = data.communities.map(u => {
491             return { key: u.name };
492           });
493           cb(communities);
494           this.communitySub.unsubscribe();
495         }
496       },
497       err => console.error(err),
498       () => console.log('complete')
499     );
500   } else {
501     cb([]);
502   }
503 }