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