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 WebSocketJsonResponse,
20 } from './interfaces';
21 import { UserService } from './services/UserService';
22 import markdown_it from 'markdown-it';
23 import markdownitEmoji from 'markdown-it-emoji/light';
24 import markdown_it_container from 'markdown-it-container';
25 import * as twemoji from 'twemoji';
26 import * as emojiShortName from 'emoji-short-name';
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 wsJsonToRes(msg: WebSocketJsonResponse): WebSocketResponse {
44 let opStr: string = msg.op;
46 op: UserOperation[opStr],
51 export const md = new markdown_it({
56 .use(markdown_it_container, 'spoiler', {
57 validate: function(params: any) {
58 return params.trim().match(/^spoiler\s+(.*)$/);
61 render: function(tokens: any, idx: any) {
62 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
64 if (tokens[idx].nesting === 1) {
66 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
69 return '</details>\n';
73 .use(markdownitEmoji, {
74 defs: objectFlip(emojiShortName),
77 md.renderer.rules.emoji = function(token, idx) {
78 return twemoji.parse(token[idx].content);
81 export function hotRank(comment: Comment): number {
82 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
84 let date: Date = new Date(comment.published + 'Z'); // Add Z to convert from UTC date
85 let now: Date = new Date();
86 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
89 (10000 * Math.log10(Math.max(1, 3 + comment.score))) /
90 Math.pow(hoursElapsed + 2, 1.8);
92 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
97 export function mdToHtml(text: string) {
98 return { __html: md.render(text) };
101 export function getUnixTime(text: string): number {
102 return text ? new Date(text).getTime() / 1000 : undefined;
105 export function addTypeInfo<T>(
108 ): Array<{ type_: string; data: T }> {
109 return arr.map(e => {
110 return { type_: name, data: e };
114 export function canMod(
116 modIds: Array<number>,
118 onSelf: boolean = false
120 // You can do moderator actions only on the mods added after you.
122 let yourIndex = modIds.findIndex(id => id == user.id);
123 if (yourIndex == -1) {
126 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
127 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
128 return !modIds.includes(creator_id);
135 export function isMod(modIds: Array<number>, creator_id: number): boolean {
136 return modIds.includes(creator_id);
139 var imageRegex = new RegExp(
140 `(http)?s?:?(\/\/[^"']*\.(?:png|jpg|jpeg|gif|png|svg))`
142 var videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
144 export function isImage(url: string) {
145 return imageRegex.test(url);
148 export function isVideo(url: string) {
149 return videoRegex.test(url);
152 export function validURL(str: string) {
154 return !!new URL(str);
160 export function validEmail(email: string) {
161 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,}))$/;
162 return re.test(String(email).toLowerCase());
165 export function capitalizeFirstLetter(str: string): string {
166 return str.charAt(0).toUpperCase() + str.slice(1);
169 export function routeSortTypeToEnum(sort: string): SortType {
172 } else if (sort == 'hot') {
174 } else if (sort == 'topday') {
175 return SortType.TopDay;
176 } else if (sort == 'topweek') {
177 return SortType.TopWeek;
178 } else if (sort == 'topmonth') {
179 return SortType.TopMonth;
180 } else if (sort == 'topyear') {
181 return SortType.TopYear;
182 } else if (sort == 'topall') {
183 return SortType.TopAll;
187 export function routeListingTypeToEnum(type: string): ListingType {
188 return ListingType[capitalizeFirstLetter(type)];
191 export function routeSearchTypeToEnum(type: string): SearchType {
192 return SearchType[capitalizeFirstLetter(type)];
195 export async function getPageTitle(url: string) {
196 let res = await fetch(`https://textance.herokuapp.com/title/${url}`);
197 let data = await res.text();
201 export function debounce(
204 immediate: boolean = false
206 // 'private' variable for instance
207 // The returned function will be able to reference this due to closure.
208 // Each call to the returned function will share this common timer.
211 // Calling debounce returns a new anonymous function
213 // reference the context and args for the setTimeout function
217 // Should the function be called now? If immediate is true
218 // and not already in a timeout then the answer is: Yes
219 var callNow = immediate && !timeout;
221 // This is the basic debounce behaviour where you can call this
222 // function several times, but it will only execute once
223 // [before or after imposing a delay].
224 // Each time the returned function is called, the timer starts over.
225 clearTimeout(timeout);
227 // Set the new timeout
228 timeout = setTimeout(function() {
229 // Inside the timeout function, clear the timeout variable
230 // which will let the next execution run when in 'immediate' mode
233 // Check if the function already ran with the immediate flag
235 // Call the original function with apply
236 // apply lets you define the 'this' object as well as the arguments
237 // (both captured before setTimeout)
238 func.apply(context, args);
242 // Immediate mode and no wait timer? Execute the function..
243 if (callNow) func.apply(context, args);
247 export const languages = [
248 { code: 'en', name: 'English' },
249 { code: 'eo', name: 'Esperanto' },
250 { code: 'es', name: 'Español' },
251 { code: 'de', name: 'Deutsch' },
252 { code: 'zh', name: '中文' },
253 { code: 'fr', name: 'Français' },
254 { code: 'sv', name: 'Svenska' },
255 { code: 'ru', name: 'Русский' },
256 { code: 'nl', name: 'Nederlands' },
257 { code: 'it', name: 'Italiano' },
260 export function getLanguage(): string {
261 let user = UserService.Instance.user;
262 let lang = user && user.lang ? user.lang : 'browser';
264 if (lang == 'browser') {
265 return getBrowserLanguage();
271 export function getBrowserLanguage(): string {
272 return navigator.language;
275 export function getMomentLanguage(): string {
276 let lang = getLanguage();
277 if (lang.startsWith('zh')) {
279 } else if (lang.startsWith('sv')) {
281 } else if (lang.startsWith('fr')) {
283 } else if (lang.startsWith('de')) {
285 } else if (lang.startsWith('ru')) {
287 } else if (lang.startsWith('es')) {
289 } else if (lang.startsWith('eo')) {
291 } else if (lang.startsWith('nl')) {
293 } else if (lang.startsWith('it')) {
301 export const themes = [
314 export function setTheme(theme: string = 'darkly') {
315 // unload all the other themes
316 for (var i = 0; i < themes.length; i++) {
317 let styleSheet = document.getElementById(themes[i]);
319 styleSheet.setAttribute('disabled', 'disabled');
323 // Load the theme dynamically
324 if (!document.getElementById(theme)) {
325 var head = document.getElementsByTagName('head')[0];
326 var link = document.createElement('link');
328 link.rel = 'stylesheet';
329 link.type = 'text/css';
330 link.href = `/static/assets/css/themes/${theme}.min.css`;
332 head.appendChild(link);
334 document.getElementById(theme).removeAttribute('disabled');
337 export function objectFlip(obj: any) {
339 Object.keys(obj).forEach(key => {
345 export function pictshareAvatarThumbnail(src: string): string {
346 // sample url: http://localhost:8535/pictshare/gs7xuu.jpg
347 let split = src.split('pictshare');
348 let out = `${split[0]}pictshare/96x96${split[1]}`;
352 export function showAvatars(): boolean {
354 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
355 !UserService.Instance.user
359 /// Converts to image thumbnail (only supports pictshare currently)
360 export function imageThumbnailer(url: string): string {
361 let split = url.split('pictshare');
362 if (split.length > 1) {
363 let out = `${split[0]}pictshare/140x140${split[1]}`;