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';
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';
13 export let repoUrl = 'https://github.com/dessalines/lemmy';
15 export function msgOp(msg: any): UserOperation {
16 let opStr: string = msg.op;
17 return UserOperation[opStr];
20 var md = new markdown_it({
24 }).use(markdown_it_container, 'spoiler', {
25 validate: function(params: any) {
26 return params.trim().match(/^spoiler\s+(.*)$/);
29 render: function (tokens: any, idx: any) {
30 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
32 if (tokens[idx].nesting === 1) {
34 return '<details><summary>' + md.utils.escapeHtml(m[1]) + '</summary>\n';
38 return '</details>\n';
43 export function hotRank(comment: Comment): number {
44 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
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;
50 let rank = (10000 * Math.log10(Math.max(1, 3 + comment.score))) / Math.pow(hoursElapsed + 2, 1.8);
52 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
57 export function mdToHtml(text: string) {
58 return {__html: md.render(text)};
61 export function getUnixTime(text: string): number {
62 return text ? new Date(text).getTime()/1000 : undefined;
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}});
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.
72 let yourIndex = modIds.findIndex(id => id == user.id);
73 if (yourIndex == -1) {
76 modIds = modIds.slice(0, yourIndex+1); // +1 cause you cant mod yourself
77 return !modIds.includes(creator_id);
84 export function isMod(modIds: Array<number>, creator_id: number): boolean {
85 return modIds.includes(creator_id);
89 var imageRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:png|jpg|jpeg|gif|png|svg))`);
91 export function isImage(url: string) {
92 return imageRegex.test(url);
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);
105 export let fetchLimit: number = 20;
107 export function capitalizeFirstLetter(str: string): string {
108 return str.charAt(0).toUpperCase() + str.slice(1);
112 export function routeSortTypeToEnum(sort: string): SortType {
115 } else if (sort == '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;
128 export function routeListingTypeToEnum(type: string): ListingType {
129 return ListingType[capitalizeFirstLetter(type)];
132 export async function getPageTitle(url: string) {
133 let res = await fetch(`https://textance.herokuapp.com/title/${url}`);
134 let data = await res.text();
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.
144 // Calling debounce returns a new anonymous function
146 // reference the context and args for the setTimeout function
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;
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);
160 // Set the new timeout
161 timeout = setTimeout(function() {
163 // Inside the timeout function, clear the timeout variable
164 // which will let the next execution run when in 'immediate' mode
167 // Check if the function already ran with the immediate flag
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);
176 // Immediate mode and no wait timer? Execute the function..
177 if (callNow) func.apply(context, args);
181 export function getLanguage(): string {
182 return (navigator.language || navigator.userLanguage);
185 export function getMomentLanguage(): string {
186 let lang = getLanguage();
187 if (lang.startsWith('zh')) {
189 } else if (lang.startsWith('sv')) {
191 } else if (lang.startsWith('fr')) {
193 } else if (lang.startsWith('de')) {
195 } else if (lang.startsWith('ru')) {
197 } else if (lang.startsWith('es')) {
199 } else if (lang.startsWith('eo')) {