]> Untitled Git - lemmy.git/blob - ui/src/utils.ts
Merge branch 'MatteoGgl-master' into dev
[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
28 export const postRefetchSeconds: number = 60 * 1000;
29 export const fetchLimit: number = 20;
30 export const mentionDropdownFetchLimit = 6;
31
32 export function randomStr() {
33   return Math.random()
34     .toString(36)
35     .replace(/[^a-z]+/g, '')
36     .substr(2, 10);
37 }
38
39 export function msgOp(msg: any): UserOperation {
40   let opStr: string = msg.op;
41   return UserOperation[opStr];
42 }
43
44 export const md = new markdown_it({
45   html: false,
46   linkify: true,
47   typographer: true,
48 })
49   .use(markdown_it_container, 'spoiler', {
50     validate: function(params: any) {
51       return params.trim().match(/^spoiler\s+(.*)$/);
52     },
53
54     render: function(tokens: any, idx: any) {
55       var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
56
57       if (tokens[idx].nesting === 1) {
58         // opening tag
59         return (
60           '<details><summary>' + md.utils.escapeHtml(m[1]) + '</summary>\n'
61         );
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 capitalizeFirstLetter(str: string): string {
156   return str.charAt(0).toUpperCase() + str.slice(1);
157 }
158
159 export function routeSortTypeToEnum(sort: string): SortType {
160   if (sort == 'new') {
161     return SortType.New;
162   } else if (sort == 'hot') {
163     return SortType.Hot;
164   } else if (sort == 'topday') {
165     return SortType.TopDay;
166   } else if (sort == 'topweek') {
167     return SortType.TopWeek;
168   } else if (sort == 'topmonth') {
169     return SortType.TopMonth;
170   } else if (sort == 'topyear') {
171     return SortType.TopYear;
172   } else if (sort == 'topall') {
173     return SortType.TopAll;
174   }
175 }
176
177 export function routeListingTypeToEnum(type: string): ListingType {
178   return ListingType[capitalizeFirstLetter(type)];
179 }
180
181 export function routeSearchTypeToEnum(type: string): SearchType {
182   return SearchType[capitalizeFirstLetter(type)];
183 }
184
185 export async function getPageTitle(url: string) {
186   let res = await fetch(`https://textance.herokuapp.com/title/${url}`);
187   let data = await res.text();
188   return data;
189 }
190
191 export function debounce(
192   func: any,
193   wait: number = 500,
194   immediate: boolean = false
195 ) {
196   // 'private' variable for instance
197   // The returned function will be able to reference this due to closure.
198   // Each call to the returned function will share this common timer.
199   let timeout: number;
200
201   // Calling debounce returns a new anonymous function
202   return function() {
203     // reference the context and args for the setTimeout function
204     var context = this,
205       args = arguments;
206
207     // Should the function be called now? If immediate is true
208     //   and not already in a timeout then the answer is: Yes
209     var callNow = immediate && !timeout;
210
211     // This is the basic debounce behaviour where you can call this
212     //   function several times, but it will only execute once
213     //   [before or after imposing a delay].
214     //   Each time the returned function is called, the timer starts over.
215     clearTimeout(timeout);
216
217     // Set the new timeout
218     timeout = setTimeout(function() {
219       // Inside the timeout function, clear the timeout variable
220       // which will let the next execution run when in 'immediate' mode
221       timeout = null;
222
223       // Check if the function already ran with the immediate flag
224       if (!immediate) {
225         // Call the original function with apply
226         // apply lets you define the 'this' object as well as the arguments
227         //    (both captured before setTimeout)
228         func.apply(context, args);
229       }
230     }, wait);
231
232     // Immediate mode and no wait timer? Execute the function..
233     if (callNow) func.apply(context, args);
234   };
235 }
236
237 export function getLanguage(): string {
238   return navigator.language || navigator.userLanguage;
239 }
240
241 export function objectFlip(obj: any) {
242   const ret = {};
243   Object.keys(obj).forEach(key => {
244     ret[obj[key]] = key;
245   });
246   return ret;
247 }
248
249 export function getMomentLanguage(): string {
250   let lang = getLanguage();
251   if (lang.startsWith('zh')) {
252     lang = 'zh-cn';
253   } else if (lang.startsWith('sv')) {
254     lang = 'sv';
255   } else if (lang.startsWith('fr')) {
256     lang = 'fr';
257   } else if (lang.startsWith('de')) {
258     lang = 'de';
259   } else if (lang.startsWith('ru')) {
260     lang = 'ru';
261   } else if (lang.startsWith('es')) {
262     lang = 'es';
263   } else if (lang.startsWith('eo')) {
264     lang = 'eo';
265   } else if (lang.startsWith('nl')) {
266     lang = 'nl';
267   } else if (lang.startsWith('it')) {
268     lang = 'it';
269   } else {
270     lang = 'en';
271   }
272   return lang;
273 }
274
275 export const themes = [
276   'litera',
277   'minty',
278   'solar',
279   'united',
280   'cyborg',
281   'darkly',
282   'journal',
283   'sketchy',
284 ];
285
286 export function setTheme(theme: string = 'darkly') {
287   for (var i = 0; i < themes.length; i++) {
288     let styleSheet = document.getElementById(themes[i]);
289     if (themes[i] == theme) {
290       styleSheet.removeAttribute('disabled');
291     } else {
292       styleSheet.setAttribute('disabled', 'disabled');
293     }
294   }
295 }