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 == 'topyear') {
170 return SortType.TopYear;
171 } else if (sort == 'topall') {
172 return SortType.TopAll;
176 export function routeListingTypeToEnum(type: string): ListingType {
177 return ListingType[capitalizeFirstLetter(type)];
180 export function routeSearchTypeToEnum(type: string): SearchType {
181 return SearchType[capitalizeFirstLetter(type)];
184 export async function getPageTitle(url: string) {
185 let res = await fetch(`https://textance.herokuapp.com/title/${url}`);
186 let data = await res.text();
190 export function debounce(
193 immediate: boolean = false
195 // 'private' variable for instance
196 // The returned function will be able to reference this due to closure.
197 // Each call to the returned function will share this common timer.
200 // Calling debounce returns a new anonymous function
202 // reference the context and args for the setTimeout function
206 // Should the function be called now? If immediate is true
207 // and not already in a timeout then the answer is: Yes
208 var callNow = immediate && !timeout;
210 // This is the basic debounce behaviour where you can call this
211 // function several times, but it will only execute once
212 // [before or after imposing a delay].
213 // Each time the returned function is called, the timer starts over.
214 clearTimeout(timeout);
216 // Set the new timeout
217 timeout = setTimeout(function() {
218 // Inside the timeout function, clear the timeout variable
219 // which will let the next execution run when in 'immediate' mode
222 // Check if the function already ran with the immediate flag
224 // Call the original function with apply
225 // apply lets you define the 'this' object as well as the arguments
226 // (both captured before setTimeout)
227 func.apply(context, args);
231 // Immediate mode and no wait timer? Execute the function..
232 if (callNow) func.apply(context, args);
236 export function getLanguage(): string {
237 return navigator.language || navigator.userLanguage;
240 export function objectFlip(obj: any) {
242 Object.keys(obj).forEach(key => {
248 export function getMomentLanguage(): string {
249 let lang = getLanguage();
250 if (lang.startsWith('zh')) {
252 } else if (lang.startsWith('sv')) {
254 } else if (lang.startsWith('fr')) {
256 } else if (lang.startsWith('de')) {
258 } else if (lang.startsWith('ru')) {
260 } else if (lang.startsWith('es')) {
262 } else if (lang.startsWith('eo')) {
264 } else if (lang.startsWith('nl')) {
272 export const themes = [
283 export function setTheme(theme: string = 'darkly') {
284 for (var i = 0; i < themes.length; i++) {
285 let styleSheet = document.getElementById(themes[i]);
286 if (themes[i] == theme) {
287 styleSheet.removeAttribute('disabled');
289 styleSheet.setAttribute('disabled', 'disabled');