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';
19 } from './interfaces';
20 import { UserService } from './services/UserService';
21 import markdown_it from 'markdown-it';
22 import markdownitEmoji from 'markdown-it-emoji/light';
23 import markdown_it_container from 'markdown-it-container';
24 import * as twemoji from 'twemoji';
25 import * as emojiShortName from 'emoji-short-name';
26 import Toastify from 'toastify-js';
28 export const repoUrl = 'https://github.com/dessalines/lemmy';
29 export const markdownHelpUrl = 'https://commonmark.org/help/';
30 export const archiveUrl = 'https://archive.is';
32 export const postRefetchSeconds: number = 60 * 1000;
33 export const fetchLimit: number = 20;
34 export const mentionDropdownFetchLimit = 6;
36 export function randomStr() {
39 .replace(/[^a-z]+/g, '')
43 export function msgOp(msg: any): UserOperation {
44 let opStr: string = msg.op;
45 return UserOperation[opStr];
48 export const md = new markdown_it({
53 .use(markdown_it_container, 'spoiler', {
54 validate: function(params: any) {
55 return params.trim().match(/^spoiler\s+(.*)$/);
58 render: function(tokens: any, idx: any) {
59 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
61 if (tokens[idx].nesting === 1) {
63 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
66 return '</details>\n';
70 .use(markdownitEmoji, {
71 defs: objectFlip(emojiShortName),
74 md.renderer.rules.emoji = function(token, idx) {
75 return twemoji.parse(token[idx].content);
78 export function hotRank(comment: Comment): number {
79 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
81 let date: Date = new Date(comment.published + 'Z'); // Add Z to convert from UTC date
82 let now: Date = new Date();
83 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
86 (10000 * Math.log10(Math.max(1, 3 + comment.score))) /
87 Math.pow(hoursElapsed + 2, 1.8);
89 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
94 export function mdToHtml(text: string) {
95 return { __html: md.render(text) };
98 export function getUnixTime(text: string): number {
99 return text ? new Date(text).getTime() / 1000 : undefined;
102 export function addTypeInfo<T>(
105 ): Array<{ type_: string; data: T }> {
106 return arr.map(e => {
107 return { type_: name, data: e };
111 export function canMod(
113 modIds: Array<number>,
115 onSelf: boolean = false
117 // You can do moderator actions only on the mods added after you.
119 let yourIndex = modIds.findIndex(id => id == user.id);
120 if (yourIndex == -1) {
123 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
124 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
125 return !modIds.includes(creator_id);
132 export function isMod(modIds: Array<number>, creator_id: number): boolean {
133 return modIds.includes(creator_id);
136 var imageRegex = new RegExp(
137 `(http)?s?:?(\/\/[^"']*\.(?:png|jpg|jpeg|gif|png|svg))`
139 var videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
141 export function isImage(url: string) {
142 return imageRegex.test(url);
145 export function isVideo(url: string) {
146 return videoRegex.test(url);
149 export function validURL(str: string) {
151 return !!new URL(str);
157 export function validEmail(email: string) {
158 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,}))$/;
159 return re.test(String(email).toLowerCase());
162 export function capitalizeFirstLetter(str: string): string {
163 return str.charAt(0).toUpperCase() + str.slice(1);
166 export function routeSortTypeToEnum(sort: string): SortType {
169 } else if (sort == 'hot') {
171 } else if (sort == 'topday') {
172 return SortType.TopDay;
173 } else if (sort == 'topweek') {
174 return SortType.TopWeek;
175 } else if (sort == 'topmonth') {
176 return SortType.TopMonth;
177 } else if (sort == 'topyear') {
178 return SortType.TopYear;
179 } else if (sort == 'topall') {
180 return SortType.TopAll;
184 export function routeListingTypeToEnum(type: string): ListingType {
185 return ListingType[capitalizeFirstLetter(type)];
188 export function routeSearchTypeToEnum(type: string): SearchType {
189 return SearchType[capitalizeFirstLetter(type)];
192 export async function getPageTitle(url: string) {
193 let res = await fetch(`https://textance.herokuapp.com/title/${url}`);
194 let data = await res.text();
198 export function debounce(
201 immediate: boolean = false
203 // 'private' variable for instance
204 // The returned function will be able to reference this due to closure.
205 // Each call to the returned function will share this common timer.
208 // Calling debounce returns a new anonymous function
210 // reference the context and args for the setTimeout function
214 // Should the function be called now? If immediate is true
215 // and not already in a timeout then the answer is: Yes
216 var callNow = immediate && !timeout;
218 // This is the basic debounce behaviour where you can call this
219 // function several times, but it will only execute once
220 // [before or after imposing a delay].
221 // Each time the returned function is called, the timer starts over.
222 clearTimeout(timeout);
224 // Set the new timeout
225 timeout = setTimeout(function() {
226 // Inside the timeout function, clear the timeout variable
227 // which will let the next execution run when in 'immediate' mode
230 // Check if the function already ran with the immediate flag
232 // Call the original function with apply
233 // apply lets you define the 'this' object as well as the arguments
234 // (both captured before setTimeout)
235 func.apply(context, args);
239 // Immediate mode and no wait timer? Execute the function..
240 if (callNow) func.apply(context, args);
244 export const languages = [
245 { code: 'en', name: 'English' },
246 { code: 'eo', name: 'Esperanto' },
247 { code: 'es', name: 'Español' },
248 { code: 'de', name: 'Deutsch' },
249 { code: 'zh', name: '中文' },
250 { code: 'fr', name: 'Français' },
251 { code: 'sv', name: 'Svenska' },
252 { code: 'ru', name: 'Русский' },
253 { code: 'nl', name: 'Nederlands' },
254 { code: 'it', name: 'Italiano' },
257 export function getLanguage(): string {
258 let user = UserService.Instance.user;
259 let lang = user && user.lang ? user.lang : 'browser';
261 if (lang == 'browser') {
262 return getBrowserLanguage();
268 export function getBrowserLanguage(): string {
269 return navigator.language;
272 export function getMomentLanguage(): string {
273 let lang = getLanguage();
274 if (lang.startsWith('zh')) {
276 } else if (lang.startsWith('sv')) {
278 } else if (lang.startsWith('fr')) {
280 } else if (lang.startsWith('de')) {
282 } else if (lang.startsWith('ru')) {
284 } else if (lang.startsWith('es')) {
286 } else if (lang.startsWith('eo')) {
288 } else if (lang.startsWith('nl')) {
290 } else if (lang.startsWith('it')) {
298 export const themes = [
311 export function setTheme(theme: string = 'darkly') {
312 // unload all the other themes
313 for (var i = 0; i < themes.length; i++) {
314 let styleSheet = document.getElementById(themes[i]);
316 styleSheet.setAttribute('disabled', 'disabled');
320 // Load the theme dynamically
321 if (!document.getElementById(theme)) {
322 var head = document.getElementsByTagName('head')[0];
323 var link = document.createElement('link');
325 link.rel = 'stylesheet';
326 link.type = 'text/css';
327 link.href = `/static/assets/css/themes/${theme}.min.css`;
329 head.appendChild(link);
331 document.getElementById(theme).removeAttribute('disabled');
334 export function objectFlip(obj: any) {
336 Object.keys(obj).forEach(key => {
342 export function pictshareAvatarThumbnail(src: string): string {
343 // sample url: http://localhost:8535/pictshare/gs7xuu.jpg
344 let split = src.split('pictshare');
345 let out = `${split[0]}pictshare/96x96${split[1]}`;
349 export function showAvatars(): boolean {
351 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
352 !UserService.Instance.user
356 /// Converts to image thumbnail (only supports pictshare currently)
357 export function imageThumbnailer(url: string): string {
358 let split = url.split('pictshare');
359 if (split.length > 1) {
360 let out = `${split[0]}pictshare/140x140${split[1]}`;
367 export function isCommentType(item: Comment | PrivateMessage): item is Comment {
368 return (item as Comment).community_id !== undefined;
371 export function toast(text: string, background: string = 'success') {
372 let backgroundColor = `var(--${background})`;
375 backgroundColor: backgroundColor,