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