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 declare var markdownitEmoji: any;
13 import * as markdown_it_container from 'markdown-it-container';
15 export let repoUrl = 'https://github.com/dessalines/lemmy';
17 export function msgOp(msg: any): UserOperation {
18 let opStr: string = msg.op;
19 return UserOperation[opStr];
22 var md = new markdown_it({
26 }).use(markdown_it_container, 'spoiler', {
27 validate: function(params: any) {
28 return params.trim().match(/^spoiler\s+(.*)$/);
31 render: function (tokens: any, idx: any) {
32 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
34 if (tokens[idx].nesting === 1) {
36 return '<details><summary>' + md.utils.escapeHtml(m[1]) + '</summary>\n';
40 return '</details>\n';
43 }).use(markdownitEmoji);
45 export function hotRank(comment: Comment): number {
46 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
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;
52 let rank = (10000 * Math.log10(Math.max(1, 3 + comment.score))) / Math.pow(hoursElapsed + 2, 1.8);
54 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
59 export function mdToHtml(text: string) {
60 return {__html: md.render(text)};
63 export function getUnixTime(text: string): number {
64 return text ? new Date(text).getTime()/1000 : undefined;
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}});
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.
74 let yourIndex = modIds.findIndex(id => id == user.id);
75 if (yourIndex == -1) {
78 modIds = modIds.slice(0, yourIndex+1); // +1 cause you cant mod yourself
79 return !modIds.includes(creator_id);
86 export function isMod(modIds: Array<number>, creator_id: number): boolean {
87 return modIds.includes(creator_id);
91 var imageRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:png|jpg|jpeg|gif|png|svg))`);
93 export function isImage(url: string) {
94 return imageRegex.test(url);
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);
107 export let fetchLimit: number = 20;
109 export function capitalizeFirstLetter(str: string): string {
110 return str.charAt(0).toUpperCase() + str.slice(1);
114 export function routeSortTypeToEnum(sort: string): SortType {
117 } else if (sort == '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;
130 export function routeListingTypeToEnum(type: string): ListingType {
131 return ListingType[capitalizeFirstLetter(type)];
134 export async function getPageTitle(url: string) {
135 let res = await fetch(`https://textance.herokuapp.com/title/${url}`);
136 let data = await res.text();
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.
146 // Calling debounce returns a new anonymous function
148 // reference the context and args for the setTimeout function
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;
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);
162 // Set the new timeout
163 timeout = setTimeout(function() {
165 // Inside the timeout function, clear the timeout variable
166 // which will let the next execution run when in 'immediate' mode
169 // Check if the function already ran with the immediate flag
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);
178 // Immediate mode and no wait timer? Execute the function..
179 if (callNow) func.apply(context, args);
183 export function getLanguage(): string {
184 return (navigator.language || navigator.userLanguage);
187 export function getMomentLanguage(): string {
188 let lang = getLanguage();
189 if (lang.startsWith('zh')) {
191 } else if (lang.startsWith('sv')) {
193 } else if (lang.startsWith('fr')) {
195 } else if (lang.startsWith('de')) {
197 } else if (lang.startsWith('ru')) {
199 } else if (lang.startsWith('es')) {
201 } else if (lang.startsWith('eo')) {
203 } else if (lang.startsWith('nl')) {