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