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/';
27 export const archiveUrl = 'https://archive.is';
29 export const postRefetchSeconds: number = 60 * 1000;
30 export const fetchLimit: number = 20;
31 export const mentionDropdownFetchLimit = 6;
33 export function randomStr() {
36 .replace(/[^a-z]+/g, '')
40 export function msgOp(msg: any): UserOperation {
41 let opStr: string = msg.op;
42 return UserOperation[opStr];
45 export const md = new markdown_it({
50 .use(markdown_it_container, 'spoiler', {
51 validate: function(params: any) {
52 return params.trim().match(/^spoiler\s+(.*)$/);
55 render: function(tokens: any, idx: any) {
56 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
58 if (tokens[idx].nesting === 1) {
61 '<details><summary>' + md.utils.escapeHtml(m[1]) + '</summary>\n'
65 return '</details>\n';
69 .use(markdownitEmoji, {
70 defs: objectFlip(emojiShortName),
73 md.renderer.rules.emoji = function(token, idx) {
74 return twemoji.parse(token[idx].content);
77 export function hotRank(comment: Comment): number {
78 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
80 let date: Date = new Date(comment.published + 'Z'); // Add Z to convert from UTC date
81 let now: Date = new Date();
82 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
85 (10000 * Math.log10(Math.max(1, 3 + comment.score))) /
86 Math.pow(hoursElapsed + 2, 1.8);
88 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
93 export function mdToHtml(text: string) {
94 return { __html: md.render(text) };
97 export function getUnixTime(text: string): number {
98 return text ? new Date(text).getTime() / 1000 : undefined;
101 export function addTypeInfo<T>(
104 ): Array<{ type_: string; data: T }> {
105 return arr.map(e => {
106 return { type_: name, data: e };
110 export function canMod(
112 modIds: Array<number>,
114 onSelf: boolean = false
116 // You can do moderator actions only on the mods added after you.
118 let yourIndex = modIds.findIndex(id => id == user.id);
119 if (yourIndex == -1) {
122 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
123 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
124 return !modIds.includes(creator_id);
131 export function isMod(modIds: Array<number>, creator_id: number): boolean {
132 return modIds.includes(creator_id);
135 var imageRegex = new RegExp(
136 `(http)?s?:?(\/\/[^"']*\.(?:png|jpg|jpeg|gif|png|svg))`
138 var videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
140 export function isImage(url: string) {
141 return imageRegex.test(url);
144 export function isVideo(url: string) {
145 return videoRegex.test(url);
148 export function validURL(str: string) {
150 return !!new URL(str);
156 export function validEmail(email: string) {
157 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,}))$/;
158 return re.test(String(email).toLowerCase());
161 export function capitalizeFirstLetter(str: string): string {
162 return str.charAt(0).toUpperCase() + str.slice(1);
165 export function routeSortTypeToEnum(sort: string): SortType {
168 } else if (sort == 'hot') {
170 } else if (sort == 'topday') {
171 return SortType.TopDay;
172 } else if (sort == 'topweek') {
173 return SortType.TopWeek;
174 } else if (sort == 'topmonth') {
175 return SortType.TopMonth;
176 } else if (sort == 'topyear') {
177 return SortType.TopYear;
178 } else if (sort == 'topall') {
179 return SortType.TopAll;
183 export function routeListingTypeToEnum(type: string): ListingType {
184 return ListingType[capitalizeFirstLetter(type)];
187 export function routeSearchTypeToEnum(type: string): SearchType {
188 return SearchType[capitalizeFirstLetter(type)];
191 export async function getPageTitle(url: string) {
192 let res = await fetch(`https://textance.herokuapp.com/title/${url}`);
193 let data = await res.text();
197 export function debounce(
200 immediate: boolean = false
202 // 'private' variable for instance
203 // The returned function will be able to reference this due to closure.
204 // Each call to the returned function will share this common timer.
207 // Calling debounce returns a new anonymous function
209 // reference the context and args for the setTimeout function
213 // Should the function be called now? If immediate is true
214 // and not already in a timeout then the answer is: Yes
215 var callNow = immediate && !timeout;
217 // This is the basic debounce behaviour where you can call this
218 // function several times, but it will only execute once
219 // [before or after imposing a delay].
220 // Each time the returned function is called, the timer starts over.
221 clearTimeout(timeout);
223 // Set the new timeout
224 timeout = setTimeout(function() {
225 // Inside the timeout function, clear the timeout variable
226 // which will let the next execution run when in 'immediate' mode
229 // Check if the function already ran with the immediate flag
231 // Call the original function with apply
232 // apply lets you define the 'this' object as well as the arguments
233 // (both captured before setTimeout)
234 func.apply(context, args);
238 // Immediate mode and no wait timer? Execute the function..
239 if (callNow) func.apply(context, args);
243 export function getLanguage(): string {
244 return navigator.language || navigator.userLanguage;
247 export function objectFlip(obj: any) {
249 Object.keys(obj).forEach(key => {
255 export function getMomentLanguage(): string {
256 let lang = getLanguage();
257 if (lang.startsWith('zh')) {
259 } else if (lang.startsWith('sv')) {
261 } else if (lang.startsWith('fr')) {
263 } else if (lang.startsWith('de')) {
265 } else if (lang.startsWith('ru')) {
267 } else if (lang.startsWith('es')) {
269 } else if (lang.startsWith('eo')) {
271 } else if (lang.startsWith('nl')) {
273 } else if (lang.startsWith('it')) {
281 export const themes = [
294 export function setTheme(theme: string = 'darkly') {
295 // unload all the other themes
296 for (var i = 0; i < themes.length; i++) {
297 let styleSheet = document.getElementById(themes[i]);
299 styleSheet.setAttribute('disabled', 'disabled');
303 // Load the theme dynamically
304 if (!document.getElementById(theme)) {
305 var head = document.getElementsByTagName('head')[0];
306 var link = document.createElement('link');
308 link.rel = 'stylesheet';
309 link.type = 'text/css';
310 link.href = `/static/assets/css/themes/${theme}.min.css`;
312 head.appendChild(link);
314 document.getElementById(theme).removeAttribute('disabled');