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