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