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