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