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