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