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';
27 export const repoUrl = 'https://github.com/dessalines/lemmy';
28 export const markdownHelpUrl = 'https://commonmark.org/help/';
29 export const archiveUrl = 'https://archive.is';
31 export const postRefetchSeconds: number = 60 * 1000;
32 export const fetchLimit: number = 20;
33 export const mentionDropdownFetchLimit = 6;
35 export function randomStr() {
38 .replace(/[^a-z]+/g, '')
42 export function wsJsonToRes(msg: any): WebSocketResponse {
43 let opStr: string = msg.op;
45 op: UserOperation[opStr],
50 export const md = new markdown_it({
55 .use(markdown_it_container, 'spoiler', {
56 validate: function(params: any) {
57 return params.trim().match(/^spoiler\s+(.*)$/);
60 render: function(tokens: any, idx: any) {
61 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
63 if (tokens[idx].nesting === 1) {
65 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
68 return '</details>\n';
72 .use(markdownitEmoji, {
73 defs: objectFlip(emojiShortName),
76 md.renderer.rules.emoji = function(token, idx) {
77 return twemoji.parse(token[idx].content);
80 export function hotRank(comment: Comment): number {
81 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
83 let date: Date = new Date(comment.published + 'Z'); // Add Z to convert from UTC date
84 let now: Date = new Date();
85 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
88 (10000 * Math.log10(Math.max(1, 3 + comment.score))) /
89 Math.pow(hoursElapsed + 2, 1.8);
91 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
96 export function mdToHtml(text: string) {
97 return { __html: md.render(text) };
100 export function getUnixTime(text: string): number {
101 return text ? new Date(text).getTime() / 1000 : undefined;
104 export function addTypeInfo<T>(
107 ): Array<{ type_: string; data: T }> {
108 return arr.map(e => {
109 return { type_: name, data: e };
113 export function canMod(
115 modIds: Array<number>,
117 onSelf: boolean = false
119 // You can do moderator actions only on the mods added after you.
121 let yourIndex = modIds.findIndex(id => id == user.id);
122 if (yourIndex == -1) {
125 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
126 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
127 return !modIds.includes(creator_id);
134 export function isMod(modIds: Array<number>, creator_id: number): boolean {
135 return modIds.includes(creator_id);
138 var imageRegex = new RegExp(
139 `(http)?s?:?(\/\/[^"']*\.(?:png|jpg|jpeg|gif|png|svg))`
141 var videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
143 export function isImage(url: string) {
144 return imageRegex.test(url);
147 export function isVideo(url: string) {
148 return videoRegex.test(url);
151 export function validURL(str: string) {
153 return !!new URL(str);
159 export function validEmail(email: string) {
160 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,}))$/;
161 return re.test(String(email).toLowerCase());
164 export function capitalizeFirstLetter(str: string): string {
165 return str.charAt(0).toUpperCase() + str.slice(1);
168 export function routeSortTypeToEnum(sort: string): SortType {
171 } else if (sort == 'hot') {
173 } else if (sort == 'topday') {
174 return SortType.TopDay;
175 } else if (sort == 'topweek') {
176 return SortType.TopWeek;
177 } else if (sort == 'topmonth') {
178 return SortType.TopMonth;
179 } else if (sort == 'topyear') {
180 return SortType.TopYear;
181 } else if (sort == 'topall') {
182 return SortType.TopAll;
186 export function routeListingTypeToEnum(type: string): ListingType {
187 return ListingType[capitalizeFirstLetter(type)];
190 export function routeSearchTypeToEnum(type: string): SearchType {
191 return SearchType[capitalizeFirstLetter(type)];
194 export async function getPageTitle(url: string) {
195 let res = await fetch(`https://textance.herokuapp.com/title/${url}`);
196 let data = await res.text();
200 export function debounce(
203 immediate: boolean = false
205 // 'private' variable for instance
206 // The returned function will be able to reference this due to closure.
207 // Each call to the returned function will share this common timer.
210 // Calling debounce returns a new anonymous function
212 // reference the context and args for the setTimeout function
216 // Should the function be called now? If immediate is true
217 // and not already in a timeout then the answer is: Yes
218 var callNow = immediate && !timeout;
220 // This is the basic debounce behaviour where you can call this
221 // function several times, but it will only execute once
222 // [before or after imposing a delay].
223 // Each time the returned function is called, the timer starts over.
224 clearTimeout(timeout);
226 // Set the new timeout
227 timeout = setTimeout(function() {
228 // Inside the timeout function, clear the timeout variable
229 // which will let the next execution run when in 'immediate' mode
232 // Check if the function already ran with the immediate flag
234 // Call the original function with apply
235 // apply lets you define the 'this' object as well as the arguments
236 // (both captured before setTimeout)
237 func.apply(context, args);
241 // Immediate mode and no wait timer? Execute the function..
242 if (callNow) func.apply(context, args);
246 export const languages = [
247 { code: 'en', name: 'English' },
248 { code: 'eo', name: 'Esperanto' },
249 { code: 'es', name: 'Español' },
250 { code: 'de', name: 'Deutsch' },
251 { code: 'zh', name: '中文' },
252 { code: 'fr', name: 'Français' },
253 { code: 'sv', name: 'Svenska' },
254 { code: 'ru', name: 'Русский' },
255 { code: 'nl', name: 'Nederlands' },
256 { code: 'it', name: 'Italiano' },
259 export function getLanguage(): string {
260 let user = UserService.Instance.user;
261 let lang = user && user.lang ? user.lang : 'browser';
263 if (lang == 'browser') {
264 return getBrowserLanguage();
270 export function getBrowserLanguage(): string {
271 return navigator.language;
274 export function getMomentLanguage(): string {
275 let lang = getLanguage();
276 if (lang.startsWith('zh')) {
278 } else if (lang.startsWith('sv')) {
280 } else if (lang.startsWith('fr')) {
282 } else if (lang.startsWith('de')) {
284 } else if (lang.startsWith('ru')) {
286 } else if (lang.startsWith('es')) {
288 } else if (lang.startsWith('eo')) {
290 } else if (lang.startsWith('nl')) {
292 } else if (lang.startsWith('it')) {
300 export const themes = [
313 export function setTheme(theme: string = 'darkly') {
314 // unload all the other themes
315 for (var i = 0; i < themes.length; i++) {
316 let styleSheet = document.getElementById(themes[i]);
318 styleSheet.setAttribute('disabled', 'disabled');
322 // Load the theme dynamically
323 if (!document.getElementById(theme)) {
324 var head = document.getElementsByTagName('head')[0];
325 var link = document.createElement('link');
327 link.rel = 'stylesheet';
328 link.type = 'text/css';
329 link.href = `/static/assets/css/themes/${theme}.min.css`;
331 head.appendChild(link);
333 document.getElementById(theme).removeAttribute('disabled');
336 export function objectFlip(obj: any) {
338 Object.keys(obj).forEach(key => {
344 export function pictshareAvatarThumbnail(src: string): string {
345 // sample url: http://localhost:8535/pictshare/gs7xuu.jpg
346 let split = src.split('pictshare');
347 let out = `${split[0]}pictshare/96x96${split[1]}`;
351 export function showAvatars(): boolean {
353 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
354 !UserService.Instance.user
358 /// Converts to image thumbnail (only supports pictshare currently)
359 export function imageThumbnailer(url: string): string {
360 let split = url.split('pictshare');
361 if (split.length > 1) {
362 let out = `${split[0]}pictshare/140x140${split[1]}`;