]> Untitled Git - lemmy.git/blob - ui/src/utils.ts
Merge branch 'private_messaging' into 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 } from './interfaces';
20 import { UserService } from './services/UserService';
21 import markdown_it from 'markdown-it';
22 import markdownitEmoji from 'markdown-it-emoji/light';
23 import markdown_it_container from 'markdown-it-container';
24 import * as twemoji from 'twemoji';
25 import * as emojiShortName from 'emoji-short-name';
26
27 export const repoUrl = 'https://github.com/dessalines/lemmy';
28 export const markdownHelpUrl = 'https://commonmark.org/help/';
29 export const archiveUrl = 'https://archive.is';
30
31 export const postRefetchSeconds: number = 60 * 1000;
32 export const fetchLimit: number = 20;
33 export const mentionDropdownFetchLimit = 6;
34
35 export function randomStr() {
36   return Math.random()
37     .toString(36)
38     .replace(/[^a-z]+/g, '')
39     .substr(2, 10);
40 }
41
42 export function msgOp(msg: any): UserOperation {
43   let opStr: string = msg.op;
44   return UserOperation[opStr];
45 }
46
47 export const md = new markdown_it({
48   html: false,
49   linkify: true,
50   typographer: true,
51 })
52   .use(markdown_it_container, 'spoiler', {
53     validate: function(params: any) {
54       return params.trim().match(/^spoiler\s+(.*)$/);
55     },
56
57     render: function(tokens: any, idx: any) {
58       var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
59
60       if (tokens[idx].nesting === 1) {
61         // opening tag
62         return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
63       } else {
64         // closing tag
65         return '</details>\n';
66       }
67     },
68   })
69   .use(markdownitEmoji, {
70     defs: objectFlip(emojiShortName),
71   });
72
73 md.renderer.rules.emoji = function(token, idx) {
74   return twemoji.parse(token[idx].content);
75 };
76
77 export function hotRank(comment: Comment): number {
78   // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
79
80   let date: Date = new Date(comment.published + 'Z'); // Add Z to convert from UTC date
81   let now: Date = new Date();
82   let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
83
84   let rank =
85     (10000 * Math.log10(Math.max(1, 3 + comment.score))) /
86     Math.pow(hoursElapsed + 2, 1.8);
87
88   // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
89
90   return rank;
91 }
92
93 export function mdToHtml(text: string) {
94   return { __html: md.render(text) };
95 }
96
97 export function getUnixTime(text: string): number {
98   return text ? new Date(text).getTime() / 1000 : undefined;
99 }
100
101 export function addTypeInfo<T>(
102   arr: Array<T>,
103   name: string
104 ): Array<{ type_: string; data: T }> {
105   return arr.map(e => {
106     return { type_: name, data: e };
107   });
108 }
109
110 export function canMod(
111   user: User,
112   modIds: Array<number>,
113   creator_id: number,
114   onSelf: boolean = false
115 ): boolean {
116   // You can do moderator actions only on the mods added after you.
117   if (user) {
118     let yourIndex = modIds.findIndex(id => id == user.id);
119     if (yourIndex == -1) {
120       return false;
121     } else {
122       // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
123       modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
124       return !modIds.includes(creator_id);
125     }
126   } else {
127     return false;
128   }
129 }
130
131 export function isMod(modIds: Array<number>, creator_id: number): boolean {
132   return modIds.includes(creator_id);
133 }
134
135 var imageRegex = new RegExp(
136   `(http)?s?:?(\/\/[^"']*\.(?:png|jpg|jpeg|gif|png|svg))`
137 );
138 var videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
139
140 export function isImage(url: string) {
141   return imageRegex.test(url);
142 }
143
144 export function isVideo(url: string) {
145   return videoRegex.test(url);
146 }
147
148 export function validURL(str: string) {
149   try {
150     return !!new URL(str);
151   } catch {
152     return false;
153   }
154 }
155
156 export function validEmail(email: string) {
157   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,}))$/;
158   return re.test(String(email).toLowerCase());
159 }
160
161 export function capitalizeFirstLetter(str: string): string {
162   return str.charAt(0).toUpperCase() + str.slice(1);
163 }
164
165 export function routeSortTypeToEnum(sort: string): SortType {
166   if (sort == 'new') {
167     return SortType.New;
168   } else if (sort == 'hot') {
169     return SortType.Hot;
170   } else if (sort == 'topday') {
171     return SortType.TopDay;
172   } else if (sort == 'topweek') {
173     return SortType.TopWeek;
174   } else if (sort == 'topmonth') {
175     return SortType.TopMonth;
176   } else if (sort == 'topyear') {
177     return SortType.TopYear;
178   } else if (sort == 'topall') {
179     return SortType.TopAll;
180   }
181 }
182
183 export function routeListingTypeToEnum(type: string): ListingType {
184   return ListingType[capitalizeFirstLetter(type)];
185 }
186
187 export function routeSearchTypeToEnum(type: string): SearchType {
188   return SearchType[capitalizeFirstLetter(type)];
189 }
190
191 export async function getPageTitle(url: string) {
192   let res = await fetch(`https://textance.herokuapp.com/title/${url}`);
193   let data = await res.text();
194   return data;
195 }
196
197 export function debounce(
198   func: any,
199   wait: number = 1000,
200   immediate: boolean = false
201 ) {
202   // 'private' variable for instance
203   // The returned function will be able to reference this due to closure.
204   // Each call to the returned function will share this common timer.
205   let timeout: any;
206
207   // Calling debounce returns a new anonymous function
208   return function() {
209     // reference the context and args for the setTimeout function
210     var context = this,
211       args = arguments;
212
213     // Should the function be called now? If immediate is true
214     //   and not already in a timeout then the answer is: Yes
215     var callNow = immediate && !timeout;
216
217     // This is the basic debounce behaviour where you can call this
218     //   function several times, but it will only execute once
219     //   [before or after imposing a delay].
220     //   Each time the returned function is called, the timer starts over.
221     clearTimeout(timeout);
222
223     // Set the new timeout
224     timeout = setTimeout(function() {
225       // Inside the timeout function, clear the timeout variable
226       // which will let the next execution run when in 'immediate' mode
227       timeout = null;
228
229       // Check if the function already ran with the immediate flag
230       if (!immediate) {
231         // Call the original function with apply
232         // apply lets you define the 'this' object as well as the arguments
233         //    (both captured before setTimeout)
234         func.apply(context, args);
235       }
236     }, wait);
237
238     // Immediate mode and no wait timer? Execute the function..
239     if (callNow) func.apply(context, args);
240   };
241 }
242
243 export const languages = [
244   { code: 'en', name: 'English' },
245   { code: 'eo', name: 'Esperanto' },
246   { code: 'es', name: 'Español' },
247   { code: 'de', name: 'Deutsch' },
248   { code: 'zh', name: '中文' },
249   { code: 'fr', name: 'Français' },
250   { code: 'sv', name: 'Svenska' },
251   { code: 'ru', name: 'Русский' },
252   { code: 'nl', name: 'Nederlands' },
253   { code: 'it', name: 'Italiano' },
254 ];
255
256 export function getLanguage(): string {
257   let user = UserService.Instance.user;
258   let lang = user && user.lang ? user.lang : 'browser';
259
260   if (lang == 'browser') {
261     return getBrowserLanguage();
262   } else {
263     return lang;
264   }
265 }
266
267 export function getBrowserLanguage(): string {
268   return navigator.language;
269 }
270
271 export function getMomentLanguage(): string {
272   let lang = getLanguage();
273   if (lang.startsWith('zh')) {
274     lang = 'zh-cn';
275   } else if (lang.startsWith('sv')) {
276     lang = 'sv';
277   } else if (lang.startsWith('fr')) {
278     lang = 'fr';
279   } else if (lang.startsWith('de')) {
280     lang = 'de';
281   } else if (lang.startsWith('ru')) {
282     lang = 'ru';
283   } else if (lang.startsWith('es')) {
284     lang = 'es';
285   } else if (lang.startsWith('eo')) {
286     lang = 'eo';
287   } else if (lang.startsWith('nl')) {
288     lang = 'nl';
289   } else if (lang.startsWith('it')) {
290     lang = 'it';
291   } else {
292     lang = 'en';
293   }
294   return lang;
295 }
296
297 export const themes = [
298   'litera',
299   'minty',
300   'solar',
301   'united',
302   'cyborg',
303   'darkly',
304   'journal',
305   'sketchy',
306   'vaporwave',
307   'vaporwave-dark',
308 ];
309
310 export function setTheme(theme: string = 'darkly') {
311   // unload all the other themes
312   for (var i = 0; i < themes.length; i++) {
313     let styleSheet = document.getElementById(themes[i]);
314     if (styleSheet) {
315       styleSheet.setAttribute('disabled', 'disabled');
316     }
317   }
318
319   // Load the theme dynamically
320   if (!document.getElementById(theme)) {
321     var head = document.getElementsByTagName('head')[0];
322     var link = document.createElement('link');
323     link.id = theme;
324     link.rel = 'stylesheet';
325     link.type = 'text/css';
326     link.href = `/static/assets/css/themes/${theme}.min.css`;
327     link.media = 'all';
328     head.appendChild(link);
329   }
330   document.getElementById(theme).removeAttribute('disabled');
331 }
332
333 export function objectFlip(obj: any) {
334   const ret = {};
335   Object.keys(obj).forEach(key => {
336     ret[obj[key]] = key;
337   });
338   return ret;
339 }
340
341 export function pictshareAvatarThumbnail(src: string): string {
342   // sample url: http://localhost:8535/pictshare/gs7xuu.jpg
343   let split = src.split('pictshare');
344   let out = `${split[0]}pictshare/96x96${split[1]}`;
345   return out;
346 }
347
348 export function showAvatars(): boolean {
349   return (
350     (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
351     !UserService.Instance.user
352   );
353 }
354
355 /// Converts to image thumbnail (only supports pictshare currently)
356 export function imageThumbnailer(url: string): string {
357   let split = url.split('pictshare');
358   if (split.length > 1) {
359     let out = `${split[0]}pictshare/140x140${split[1]}`;
360     return out;
361   } else {
362     return url;
363   }
364 }
365
366 export function isCommentType(item: Comment | PrivateMessage): item is Comment {
367   return (item as Comment).community_id !== undefined;
368 }