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