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';
9 import 'moment/locale/it';
11 import { UserOperation, Comment, User, SortType, ListingType, SearchType } from './interfaces';
12 import * as markdown_it from 'markdown-it';
13 import * as markdownitEmoji from 'markdown-it-emoji/light';
14 import * as markdown_it_container from 'markdown-it-container';
15 import * as twemoji from 'twemoji';
16 import * as emojiShortName from 'emoji-short-name';
18 export const repoUrl = 'https://github.com/dessalines/lemmy';
19 export const markdownHelpUrl = 'https://commonmark.org/help/';
21 export const postRefetchSeconds: number = 60*1000;
22 export const fetchLimit: number = 20;
23 export const mentionDropdownFetchLimit = 6;
25 export function randomStr() {return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(2, 10)}
27 export function msgOp(msg: any): UserOperation {
28 let opStr: string = msg.op;
29 return UserOperation[opStr];
32 export const md = new markdown_it({
36 }).use(markdown_it_container, 'spoiler', {
37 validate: function(params: any) {
38 return params.trim().match(/^spoiler\s+(.*)$/);
41 render: function (tokens: any, idx: any) {
42 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
44 if (tokens[idx].nesting === 1) {
46 return '<details><summary>' + md.utils.escapeHtml(m[1]) + '</summary>\n';
50 return '</details>\n';
53 }).use(markdownitEmoji, {
54 defs: objectFlip(emojiShortName)
57 md.renderer.rules.emoji = function(token, idx) {
58 return twemoji.parse(token[idx].content);
61 export function hotRank(comment: Comment): number {
62 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
64 let date: Date = new Date(comment.published + 'Z'); // Add Z to convert from UTC date
65 let now: Date = new Date();
66 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
68 let rank = (10000 * Math.log10(Math.max(1, 3 + comment.score))) / Math.pow(hoursElapsed + 2, 1.8);
70 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
75 export function mdToHtml(text: string) {
76 return {__html: md.render(text)};
79 export function getUnixTime(text: string): number {
80 return text ? new Date(text).getTime()/1000 : undefined;
83 export function addTypeInfo<T>(arr: Array<T>, name: string): Array<{type_: string, data: T}> {
84 return arr.map(e => {return {type_: name, data: e}});
87 export function canMod(user: User, modIds: Array<number>, creator_id: number, onSelf: boolean = false): boolean {
88 // You can do moderator actions only on the mods added after you.
90 let yourIndex = modIds.findIndex(id => id == user.id);
91 if (yourIndex == -1) {
94 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
95 modIds = modIds.slice(0, yourIndex+(onSelf ? 0 : 1));
96 return !modIds.includes(creator_id);
103 export function isMod(modIds: Array<number>, creator_id: number): boolean {
104 return modIds.includes(creator_id);
108 var imageRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:png|jpg|jpeg|gif|png|svg))`);
109 var videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
111 export function isImage(url: string) {
112 return imageRegex.test(url);
115 export function isVideo(url: string) {
116 return videoRegex.test(url);
119 export function validURL(str: string) {
121 return !!new URL(str);
127 export function capitalizeFirstLetter(str: string): string {
128 return str.charAt(0).toUpperCase() + str.slice(1);
132 export function routeSortTypeToEnum(sort: string): SortType {
135 } else if (sort == 'hot') {
137 } else if (sort == 'topday') {
138 return SortType.TopDay;
139 } else if (sort == 'topweek') {
140 return SortType.TopWeek;
141 } else if (sort == 'topmonth') {
142 return SortType.TopMonth;
143 } else if (sort == 'topall') {
144 return SortType.TopAll;
148 export function routeListingTypeToEnum(type: string): ListingType {
149 return ListingType[capitalizeFirstLetter(type)];
152 export function routeSearchTypeToEnum(type: string): SearchType {
153 return SearchType[capitalizeFirstLetter(type)];
156 export async function getPageTitle(url: string) {
157 let res = await fetch(`https://textance.herokuapp.com/title/${url}`);
158 let data = await res.text();
162 export function debounce(func: any, wait: number = 500, immediate: boolean = false) {
163 // 'private' variable for instance
164 // The returned function will be able to reference this due to closure.
165 // Each call to the returned function will share this common timer.
168 // Calling debounce returns a new anonymous function
170 // reference the context and args for the setTimeout function
174 // Should the function be called now? If immediate is true
175 // and not already in a timeout then the answer is: Yes
176 var callNow = immediate && !timeout;
178 // This is the basic debounce behaviour where you can call this
179 // function several times, but it will only execute once
180 // [before or after imposing a delay].
181 // Each time the returned function is called, the timer starts over.
182 clearTimeout(timeout);
184 // Set the new timeout
185 timeout = setTimeout(function() {
187 // Inside the timeout function, clear the timeout variable
188 // which will let the next execution run when in 'immediate' mode
191 // Check if the function already ran with the immediate flag
193 // Call the original function with apply
194 // apply lets you define the 'this' object as well as the arguments
195 // (both captured before setTimeout)
196 func.apply(context, args);
200 // Immediate mode and no wait timer? Execute the function..
201 if (callNow) func.apply(context, args);
205 export function getLanguage(): string {
206 return (navigator.language || navigator.userLanguage);
209 export function objectFlip(obj: any) {
211 Object.keys(obj).forEach((key) => {
217 export function getMomentLanguage(): string {
218 let lang = getLanguage();
219 if (lang.startsWith('zh')) {
221 } else if (lang.startsWith('sv')) {
223 } else if (lang.startsWith('fr')) {
225 } else if (lang.startsWith('de')) {
227 } else if (lang.startsWith('ru')) {
229 } else if (lang.startsWith('es')) {
231 } else if (lang.startsWith('eo')) {
233 } else if (lang.startsWith('nl')) {
235 } else if (lang.startsWith('it')) {
243 export const themes = ['litera', 'minty', 'solar', 'united', 'cyborg','darkly', 'journal', 'sketchy'];
245 export function setTheme(theme: string = 'darkly') {
246 for (var i=0; i < themes.length; i++) {
248 let styleSheet = document.getElementById(themes[i]);
249 if (themes[i] == theme) {
250 styleSheet.removeAttribute("disabled");
252 styleSheet.setAttribute("disabled", "disabled");