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