]> Untitled Git - lemmy.git/blob - ui/src/utils.ts
Adding user avatars / icons. Requires pictshare.
[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 * as markdown_it from 'markdown-it';
21 import * as markdownitEmoji from 'markdown-it-emoji/light';
22 import * as 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 (
62           '<details><summary>' + md.utils.escapeHtml(m[1]) + '</summary>\n'
63         );
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: number;
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 || navigator.userLanguage;
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 }