]> Untitled Git - lemmy.git/blob - ui/src/utils.ts
Adding Esperanto.
[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
9 import { UserOperation, Comment, User, SortType, ListingType } from './interfaces';
10 import * as markdown_it from 'markdown-it';
11 import * as markdown_it_container from 'markdown-it-container';
12
13 export let repoUrl = 'https://github.com/dessalines/lemmy';
14
15 export function msgOp(msg: any): UserOperation {
16   let opStr: string = msg.op;
17   return UserOperation[opStr];
18 }
19
20 var md = new markdown_it({
21   html: false,
22   linkify: true,
23   typographer: true
24 }).use(markdown_it_container, 'spoiler', {
25   validate: function(params: any) {
26     return params.trim().match(/^spoiler\s+(.*)$/);
27   },
28
29   render: function (tokens: any, idx: any) {
30     var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
31
32     if (tokens[idx].nesting === 1) {
33       // opening tag
34       return '<details><summary>' + md.utils.escapeHtml(m[1]) + '</summary>\n';
35
36     } else {
37       // closing tag
38       return '</details>\n';
39     }
40   }
41 });
42
43 export function hotRank(comment: Comment): number {
44   // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
45
46   let date: Date = new Date(comment.published + 'Z'); // Add Z to convert from UTC date
47   let now: Date = new Date();
48   let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
49
50   let rank = (10000 *  Math.log10(Math.max(1, 3 + comment.score))) / Math.pow(hoursElapsed + 2, 1.8);
51
52   // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
53
54   return rank;
55 }
56
57 export function mdToHtml(text: string) {
58   return {__html: md.render(text)};
59 }
60
61 export function getUnixTime(text: string): number { 
62   return text ? new Date(text).getTime()/1000 : undefined;
63 }
64
65 export function addTypeInfo<T>(arr: Array<T>, name: string): Array<{type_: string, data: T}> {  
66   return arr.map(e => {return {type_: name, data: e}});
67 }
68
69 export function canMod(user: User, modIds: Array<number>, creator_id: number): boolean {
70   // You can do moderator actions only on the mods added after you.
71   if (user) {
72     let yourIndex = modIds.findIndex(id => id == user.id);
73     if (yourIndex == -1) {
74       return false;
75     } else { 
76       modIds = modIds.slice(0, yourIndex+1); // +1 cause you cant mod yourself
77       return !modIds.includes(creator_id);
78     }
79   } else {
80     return false;
81   }
82 }
83
84 export function isMod(modIds: Array<number>, creator_id: number): boolean {
85   return modIds.includes(creator_id);
86 }
87
88
89 var imageRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:png|jpg|jpeg|gif|png|svg))`);
90
91 export function isImage(url: string) {
92   return imageRegex.test(url);
93 }
94
95 export function validURL(str: string) {
96   var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
97     '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
98     '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
99     '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
100     '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
101     '(\\#[-a-z\\d_]*)?$','i'); // fragment locator
102   return !!pattern.test(str);
103 }
104
105 export let fetchLimit: number = 20;
106
107 export function capitalizeFirstLetter(str: string): string {
108   return str.charAt(0).toUpperCase() + str.slice(1);
109 }
110
111
112 export function routeSortTypeToEnum(sort: string): SortType {
113   if (sort == 'new') {
114     return SortType.New;
115   } else if (sort == 'hot') {
116     return SortType.Hot;
117   } else if (sort == 'topday') {
118     return SortType.TopDay;
119   } else if (sort == 'topweek') {
120     return SortType.TopWeek;
121   } else if (sort == 'topmonth') {
122     return SortType.TopMonth;
123   } else if (sort == 'topall') {
124     return SortType.TopAll;
125   }
126 }
127
128 export function routeListingTypeToEnum(type: string): ListingType {
129   return ListingType[capitalizeFirstLetter(type)];
130 }
131
132 export async function getPageTitle(url: string) {
133   let res = await fetch(`https://textance.herokuapp.com/title/${url}`);
134   let data = await res.text();
135   return data;
136 }
137
138 export function debounce(func: any, wait: number = 500, immediate: boolean = false) {
139   // 'private' variable for instance
140   // The returned function will be able to reference this due to closure.
141   // Each call to the returned function will share this common timer.
142   let timeout: number;
143
144   // Calling debounce returns a new anonymous function
145   return function() {
146     // reference the context and args for the setTimeout function
147     var context = this,
148     args = arguments;
149
150   // Should the function be called now? If immediate is true
151   //   and not already in a timeout then the answer is: Yes
152   var callNow = immediate && !timeout;
153
154   // This is the basic debounce behaviour where you can call this 
155   //   function several times, but it will only execute once 
156   //   [before or after imposing a delay]. 
157   //   Each time the returned function is called, the timer starts over.
158   clearTimeout(timeout);
159
160   // Set the new timeout
161   timeout = setTimeout(function() {
162
163     // Inside the timeout function, clear the timeout variable
164     // which will let the next execution run when in 'immediate' mode
165     timeout = null;
166
167     // Check if the function already ran with the immediate flag
168     if (!immediate) {
169       // Call the original function with apply
170       // apply lets you define the 'this' object as well as the arguments 
171       //    (both captured before setTimeout)
172       func.apply(context, args);
173     }
174   }, wait);
175
176   // Immediate mode and no wait timer? Execute the function..
177   if (callNow) func.apply(context, args);
178   }
179 }
180
181 export function getLanguage(): string {
182   return (navigator.language || navigator.userLanguage);
183 }
184
185 export function getMomentLanguage(): string {
186   let lang = getLanguage();
187   if (lang.startsWith('zh')) {
188     lang = 'zh-cn';
189   } else if (lang.startsWith('sv')) {
190     lang = 'sv';
191   } else if (lang.startsWith('fr')) {
192     lang = 'fr';
193   } else if (lang.startsWith('de')) {
194     lang = 'de';
195   } else if (lang.startsWith('ru')) {
196     lang = 'ru';
197   } else if (lang.startsWith('es')) {
198     lang = 'es';
199   } else if (lang.startsWith('eo')) {
200     lang = 'eo';
201   } else {
202     lang = 'en';
203   }
204   return lang;
205 }