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';
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';
14 export let repoUrl = 'https://github.com/dessalines/lemmy';
16 export function msgOp(msg: any): UserOperation {
17 let opStr: string = msg.op;
18 return UserOperation[opStr];
21 var md = new markdown_it({
25 }).use(markdown_it_container, 'spoiler', {
26 validate: function(params: any) {
27 return params.trim().match(/^spoiler\s+(.*)$/);
30 render: function (tokens: any, idx: any) {
31 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
33 if (tokens[idx].nesting === 1) {
35 return '<details><summary>' + md.utils.escapeHtml(m[1]) + '</summary>\n';
39 return '</details>\n';
44 export function hotRank(comment: Comment): number {
45 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
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;
51 let rank = (10000 * Math.log10(Math.max(1, 3 + comment.score))) / Math.pow(hoursElapsed + 2, 1.8);
53 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
58 export function mdToHtml(text: string) {
59 return {__html: md.render(text)};
62 export function getUnixTime(text: string): number {
63 return text ? new Date(text).getTime()/1000 : undefined;
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}});
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.
73 let yourIndex = modIds.findIndex(id => id == user.id);
74 if (yourIndex == -1) {
77 modIds = modIds.slice(0, yourIndex+1); // +1 cause you cant mod yourself
78 return !modIds.includes(creator_id);
85 export function isMod(modIds: Array<number>, creator_id: number): boolean {
86 return modIds.includes(creator_id);
90 var imageRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:png|jpg|jpeg|gif|png|svg))`);
92 export function isImage(url: string) {
93 return imageRegex.test(url);
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);
106 export let fetchLimit: number = 20;
108 export function capitalizeFirstLetter(str: string): string {
109 return str.charAt(0).toUpperCase() + str.slice(1);
113 export function routeSortTypeToEnum(sort: string): SortType {
116 } else if (sort == '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;
129 export function routeListingTypeToEnum(type: string): ListingType {
130 return ListingType[capitalizeFirstLetter(type)];
133 export async function getPageTitle(url: string) {
134 let res = await fetch(`https://textance.herokuapp.com/title/${url}`);
135 let data = await res.text();
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.
145 // Calling debounce returns a new anonymous function
147 // reference the context and args for the setTimeout function
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;
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);
161 // Set the new timeout
162 timeout = setTimeout(function() {
164 // Inside the timeout function, clear the timeout variable
165 // which will let the next execution run when in 'immediate' mode
168 // Check if the function already ran with the immediate flag
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);
177 // Immediate mode and no wait timer? Execute the function..
178 if (callNow) func.apply(context, args);
182 export function getLanguage(): string {
183 return (navigator.language || navigator.userLanguage);
186 export function getMomentLanguage(): string {
187 let lang = getLanguage();
188 if (lang.startsWith('zh')) {
190 } else if (lang.startsWith('sv')) {
192 } else if (lang.startsWith('fr')) {
194 } else if (lang.startsWith('de')) {
196 } else if (lang.startsWith('ru')) {
198 } else if (lang.startsWith('es')) {
200 } else if (lang.startsWith('eo')) {
202 } else if (lang.startsWith('nl')) {