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';
17 } from './interfaces';
18 import * as markdown_it from 'markdown-it';
19 import * as markdownitEmoji from 'markdown-it-emoji/light';
20 import * as markdown_it_container from 'markdown-it-container';
21 import * as twemoji from 'twemoji';
22 import * as emojiShortName from 'emoji-short-name';
24 export const repoUrl = 'https://github.com/dessalines/lemmy';
25 export const markdownHelpUrl = 'https://commonmark.org/help/';
27 export const postRefetchSeconds: number = 60 * 1000;
28 export const fetchLimit: number = 20;
29 export const mentionDropdownFetchLimit = 6;
31 export function randomStr() {
34 .replace(/[^a-z]+/g, '')
38 export function msgOp(msg: any): UserOperation {
39 let opStr: string = msg.op;
40 return UserOperation[opStr];
43 export const md = new markdown_it({
48 .use(markdown_it_container, 'spoiler', {
49 validate: function(params: any) {
50 return params.trim().match(/^spoiler\s+(.*)$/);
53 render: function(tokens: any, idx: any) {
54 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
56 if (tokens[idx].nesting === 1) {
59 '<details><summary>' + md.utils.escapeHtml(m[1]) + '</summary>\n'
63 return '</details>\n';
67 .use(markdownitEmoji, {
68 defs: objectFlip(emojiShortName),
71 md.renderer.rules.emoji = function(token, idx) {
72 return twemoji.parse(token[idx].content);
75 export function hotRank(comment: Comment): number {
76 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
78 let date: Date = new Date(comment.published + 'Z'); // Add Z to convert from UTC date
79 let now: Date = new Date();
80 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
83 (10000 * Math.log10(Math.max(1, 3 + comment.score))) /
84 Math.pow(hoursElapsed + 2, 1.8);
86 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
91 export function mdToHtml(text: string) {
92 return { __html: md.render(text) };
95 export function getUnixTime(text: string): number {
96 return text ? new Date(text).getTime() / 1000 : undefined;
99 export function addTypeInfo<T>(
102 ): Array<{ type_: string; data: T }> {
103 return arr.map(e => {
104 return { type_: name, data: e };
108 export function canMod(
110 modIds: Array<number>,
112 onSelf: boolean = false
114 // You can do moderator actions only on the mods added after you.
116 let yourIndex = modIds.findIndex(id => id == user.id);
117 if (yourIndex == -1) {
120 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
121 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
122 return !modIds.includes(creator_id);
129 export function isMod(modIds: Array<number>, creator_id: number): boolean {
130 return modIds.includes(creator_id);
133 var imageRegex = new RegExp(
134 `(http)?s?:?(\/\/[^"']*\.(?:png|jpg|jpeg|gif|png|svg))`
136 var videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
138 export function isImage(url: string) {
139 return imageRegex.test(url);
142 export function isVideo(url: string) {
143 return videoRegex.test(url);
146 export function validURL(str: string) {
148 return !!new URL(str);
154 export function capitalizeFirstLetter(str: string): string {
155 return str.charAt(0).toUpperCase() + str.slice(1);
158 export function routeSortTypeToEnum(sort: string): SortType {
161 } else if (sort == 'hot') {
163 } else if (sort == 'topday') {
164 return SortType.TopDay;
165 } else if (sort == 'topweek') {
166 return SortType.TopWeek;
167 } else if (sort == 'topmonth') {
168 return SortType.TopMonth;
169 } else if (sort == 'topall') {
170 return SortType.TopAll;
174 export function routeListingTypeToEnum(type: string): ListingType {
175 return ListingType[capitalizeFirstLetter(type)];
178 export function routeSearchTypeToEnum(type: string): SearchType {
179 return SearchType[capitalizeFirstLetter(type)];
182 export async function getPageTitle(url: string) {
183 let res = await fetch(`https://textance.herokuapp.com/title/${url}`);
184 let data = await res.text();
188 export function debounce(
191 immediate: boolean = false
193 // 'private' variable for instance
194 // The returned function will be able to reference this due to closure.
195 // Each call to the returned function will share this common timer.
198 // Calling debounce returns a new anonymous function
200 // reference the context and args for the setTimeout function
204 // Should the function be called now? If immediate is true
205 // and not already in a timeout then the answer is: Yes
206 var callNow = immediate && !timeout;
208 // This is the basic debounce behaviour where you can call this
209 // function several times, but it will only execute once
210 // [before or after imposing a delay].
211 // Each time the returned function is called, the timer starts over.
212 clearTimeout(timeout);
214 // Set the new timeout
215 timeout = setTimeout(function() {
216 // Inside the timeout function, clear the timeout variable
217 // which will let the next execution run when in 'immediate' mode
220 // Check if the function already ran with the immediate flag
222 // Call the original function with apply
223 // apply lets you define the 'this' object as well as the arguments
224 // (both captured before setTimeout)
225 func.apply(context, args);
229 // Immediate mode and no wait timer? Execute the function..
230 if (callNow) func.apply(context, args);
234 export function getLanguage(): string {
235 return navigator.language || navigator.userLanguage;
238 export function objectFlip(obj: any) {
240 Object.keys(obj).forEach(key => {
246 export function getMomentLanguage(): string {
247 let lang = getLanguage();
248 if (lang.startsWith('zh')) {
250 } else if (lang.startsWith('sv')) {
252 } else if (lang.startsWith('fr')) {
254 } else if (lang.startsWith('de')) {
256 } else if (lang.startsWith('ru')) {
258 } else if (lang.startsWith('es')) {
260 } else if (lang.startsWith('eo')) {
262 } else if (lang.startsWith('nl')) {
270 export const themes = [
281 export function setTheme(theme: string = 'darkly') {
282 for (var i = 0; i < themes.length; i++) {
283 let styleSheet = document.getElementById(themes[i]);
284 if (themes[i] == theme) {
285 styleSheet.removeAttribute('disabled');
287 styleSheet.setAttribute('disabled', 'disabled');