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';
18 } from './interfaces';
19 import * as markdown_it from 'markdown-it';
20 import * as markdownitEmoji from 'markdown-it-emoji/light';
21 import * as markdown_it_container from 'markdown-it-container';
22 import * as twemoji from 'twemoji';
23 import * as emojiShortName from 'emoji-short-name';
25 export const repoUrl = 'https://github.com/dessalines/lemmy';
26 export const markdownHelpUrl = 'https://commonmark.org/help/';
28 export const postRefetchSeconds: number = 60 * 1000;
29 export const fetchLimit: number = 20;
30 export const mentionDropdownFetchLimit = 6;
32 export function randomStr() {
35 .replace(/[^a-z]+/g, '')
39 export function msgOp(msg: any): UserOperation {
40 let opStr: string = msg.op;
41 return UserOperation[opStr];
44 export const md = new markdown_it({
49 .use(markdown_it_container, 'spoiler', {
50 validate: function(params: any) {
51 return params.trim().match(/^spoiler\s+(.*)$/);
54 render: function(tokens: any, idx: any) {
55 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
57 if (tokens[idx].nesting === 1) {
60 '<details><summary>' + md.utils.escapeHtml(m[1]) + '</summary>\n'
64 return '</details>\n';
68 .use(markdownitEmoji, {
69 defs: objectFlip(emojiShortName),
72 md.renderer.rules.emoji = function(token, idx) {
73 return twemoji.parse(token[idx].content);
76 export function hotRank(comment: Comment): number {
77 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
79 let date: Date = new Date(comment.published + 'Z'); // Add Z to convert from UTC date
80 let now: Date = new Date();
81 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
84 (10000 * Math.log10(Math.max(1, 3 + comment.score))) /
85 Math.pow(hoursElapsed + 2, 1.8);
87 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
92 export function mdToHtml(text: string) {
93 return { __html: md.render(text) };
96 export function getUnixTime(text: string): number {
97 return text ? new Date(text).getTime() / 1000 : undefined;
100 export function addTypeInfo<T>(
103 ): Array<{ type_: string; data: T }> {
104 return arr.map(e => {
105 return { type_: name, data: e };
109 export function canMod(
111 modIds: Array<number>,
113 onSelf: boolean = false
115 // You can do moderator actions only on the mods added after you.
117 let yourIndex = modIds.findIndex(id => id == user.id);
118 if (yourIndex == -1) {
121 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
122 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
123 return !modIds.includes(creator_id);
130 export function isMod(modIds: Array<number>, creator_id: number): boolean {
131 return modIds.includes(creator_id);
134 var imageRegex = new RegExp(
135 `(http)?s?:?(\/\/[^"']*\.(?:png|jpg|jpeg|gif|png|svg))`
137 var videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
139 export function isImage(url: string) {
140 return imageRegex.test(url);
143 export function isVideo(url: string) {
144 return videoRegex.test(url);
147 export function validURL(str: string) {
149 return !!new URL(str);
155 export function validEmail(email: string) {
156 let re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
157 return re.test(String(email).toLowerCase());
160 export function capitalizeFirstLetter(str: string): string {
161 return str.charAt(0).toUpperCase() + str.slice(1);
164 export function routeSortTypeToEnum(sort: string): SortType {
167 } else if (sort == 'hot') {
169 } else if (sort == 'topday') {
170 return SortType.TopDay;
171 } else if (sort == 'topweek') {
172 return SortType.TopWeek;
173 } else if (sort == 'topmonth') {
174 return SortType.TopMonth;
175 } else if (sort == 'topyear') {
176 return SortType.TopYear;
177 } else if (sort == 'topall') {
178 return SortType.TopAll;
182 export function routeListingTypeToEnum(type: string): ListingType {
183 return ListingType[capitalizeFirstLetter(type)];
186 export function routeSearchTypeToEnum(type: string): SearchType {
187 return SearchType[capitalizeFirstLetter(type)];
190 export async function getPageTitle(url: string) {
191 let res = await fetch(`https://textance.herokuapp.com/title/${url}`);
192 let data = await res.text();
196 export function debounce(
199 immediate: boolean = false
201 // 'private' variable for instance
202 // The returned function will be able to reference this due to closure.
203 // Each call to the returned function will share this common timer.
206 // Calling debounce returns a new anonymous function
208 // reference the context and args for the setTimeout function
212 // Should the function be called now? If immediate is true
213 // and not already in a timeout then the answer is: Yes
214 var callNow = immediate && !timeout;
216 // This is the basic debounce behaviour where you can call this
217 // function several times, but it will only execute once
218 // [before or after imposing a delay].
219 // Each time the returned function is called, the timer starts over.
220 clearTimeout(timeout);
222 // Set the new timeout
223 timeout = setTimeout(function() {
224 // Inside the timeout function, clear the timeout variable
225 // which will let the next execution run when in 'immediate' mode
228 // Check if the function already ran with the immediate flag
230 // Call the original function with apply
231 // apply lets you define the 'this' object as well as the arguments
232 // (both captured before setTimeout)
233 func.apply(context, args);
237 // Immediate mode and no wait timer? Execute the function..
238 if (callNow) func.apply(context, args);
242 export function getLanguage(): string {
243 return navigator.language || navigator.userLanguage;
246 export function objectFlip(obj: any) {
248 Object.keys(obj).forEach(key => {
254 export function getMomentLanguage(): string {
255 let lang = getLanguage();
256 if (lang.startsWith('zh')) {
258 } else if (lang.startsWith('sv')) {
260 } else if (lang.startsWith('fr')) {
262 } else if (lang.startsWith('de')) {
264 } else if (lang.startsWith('ru')) {
266 } else if (lang.startsWith('es')) {
268 } else if (lang.startsWith('eo')) {
270 } else if (lang.startsWith('nl')) {
272 } else if (lang.startsWith('it')) {
280 export const themes = [
292 export function setTheme(theme: string = 'darkly') {
293 for (var i = 0; i < themes.length; i++) {
294 let styleSheet = document.getElementById(themes[i]);
295 if (themes[i] == theme) {
296 styleSheet.removeAttribute('disabled');
298 styleSheet.setAttribute('disabled', 'disabled');