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';
5 export let repoUrl = 'https://github.com/dessalines/lemmy';
7 export function msgOp(msg: any): UserOperation {
8 let opStr: string = msg.op;
9 return UserOperation[opStr];
12 var md = new markdown_it({
16 }).use(markdown_it_container, 'spoiler', {
17 validate: function(params: any) {
18 return params.trim().match(/^spoiler\s+(.*)$/);
21 render: function (tokens: any, idx: any) {
22 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
24 if (tokens[idx].nesting === 1) {
26 return '<details><summary>' + md.utils.escapeHtml(m[1]) + '</summary>\n';
30 return '</details>\n';
35 export function hotRank(comment: Comment): number {
36 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
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;
42 let rank = (10000 * Math.log10(Math.max(1, 3 + comment.score))) / Math.pow(hoursElapsed + 2, 1.8);
44 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
49 export function mdToHtml(text: string) {
50 return {__html: md.render(text)};
53 export function getUnixTime(text: string): number {
54 return text ? new Date(text).getTime()/1000 : undefined;
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}});
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.
64 let yourIndex = modIds.findIndex(id => id == user.id);
65 if (yourIndex == -1) {
68 modIds = modIds.slice(0, yourIndex+1); // +1 cause you cant mod yourself
69 return !modIds.includes(creator_id);
76 export function isMod(modIds: Array<number>, creator_id: number): boolean {
77 return modIds.includes(creator_id);
81 var imageRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:png|jpg|jpeg|gif|png|svg))`);
83 export function isImage(url: string) {
84 return imageRegex.test(url);
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);
97 export let fetchLimit: number = 20;
99 export function capitalizeFirstLetter(str: string): string {
100 return str.charAt(0).toUpperCase() + str.slice(1);
104 export function routeSortTypeToEnum(sort: string): SortType {
107 } else if (sort == '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;
120 export function routeListingTypeToEnum(type: string): ListingType {
121 return ListingType[capitalizeFirstLetter(type)];
124 export async function getPageTitle(url: string) {
125 let res = await fetch(`https://textance.herokuapp.com/title/${url}`);
126 let data = await res.text();
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.
136 // Calling debounce returns a new anonymous function
138 // reference the context and args for the setTimeout function
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;
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);
152 // Set the new timeout
153 timeout = setTimeout(function() {
155 // Inside the timeout function, clear the timeout variable
156 // which will let the next execution run when in 'immediate' mode
159 // Check if the function already ran with the immediate flag
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);
168 // Immediate mode and no wait timer? Execute the function..
169 if (callNow) func.apply(context, args);
173 export function getLanguage(): string {
174 return (navigator.language || navigator.userLanguage);
177 export function getMomentLanguage(): string {
178 let lang = getLanguage();
179 if (lang.startsWith('zh')) {
181 } else if (lang.startsWith('sv')) {
183 } else if (lang.startsWith('fr')) {
185 } else if (lang.startsWith('de')) {