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';
20 WebSocketJsonResponse,
21 } from './interfaces';
22 import { UserService } from './services/UserService';
23 import markdown_it from 'markdown-it';
24 import markdownitEmoji from 'markdown-it-emoji/light';
25 import markdown_it_container from 'markdown-it-container';
26 import * as twemoji from 'twemoji';
27 import * as emojiShortName from 'emoji-short-name';
28 import Toastify from 'toastify-js';
30 export const repoUrl = 'https://github.com/dessalines/lemmy';
31 export const markdownHelpUrl = 'https://commonmark.org/help/';
32 export const archiveUrl = 'https://archive.is';
34 export const postRefetchSeconds: number = 60 * 1000;
35 export const fetchLimit: number = 20;
36 export const mentionDropdownFetchLimit = 6;
38 export function randomStr() {
41 .replace(/[^a-z]+/g, '')
45 export function wsJsonToRes(msg: WebSocketJsonResponse): WebSocketResponse {
46 let opStr: string = msg.op;
48 op: UserOperation[opStr],
53 export const md = new markdown_it({
58 .use(markdown_it_container, 'spoiler', {
59 validate: function(params: any) {
60 return params.trim().match(/^spoiler\s+(.*)$/);
63 render: function(tokens: any, idx: any) {
64 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
66 if (tokens[idx].nesting === 1) {
68 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
71 return '</details>\n';
75 .use(markdownitEmoji, {
76 defs: objectFlip(emojiShortName),
79 md.renderer.rules.emoji = function(token, idx) {
80 return twemoji.parse(token[idx].content);
83 export function hotRank(comment: Comment): number {
84 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
86 let date: Date = new Date(comment.published + 'Z'); // Add Z to convert from UTC date
87 let now: Date = new Date();
88 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
91 (10000 * Math.log10(Math.max(1, 3 + comment.score))) /
92 Math.pow(hoursElapsed + 2, 1.8);
94 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
99 export function mdToHtml(text: string) {
100 return { __html: md.render(text) };
103 export function getUnixTime(text: string): number {
104 return text ? new Date(text).getTime() / 1000 : undefined;
107 export function addTypeInfo<T>(
110 ): Array<{ type_: string; data: T }> {
111 return arr.map(e => {
112 return { type_: name, data: e };
116 export function canMod(
118 modIds: Array<number>,
120 onSelf: boolean = false
122 // You can do moderator actions only on the mods added after you.
124 let yourIndex = modIds.findIndex(id => id == user.id);
125 if (yourIndex == -1) {
128 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
129 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
130 return !modIds.includes(creator_id);
137 export function isMod(modIds: Array<number>, creator_id: number): boolean {
138 return modIds.includes(creator_id);
141 var imageRegex = new RegExp(
142 `(http)?s?:?(\/\/[^"']*\.(?:png|jpg|jpeg|gif|png|svg))`
144 var videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
146 export function isImage(url: string) {
147 return imageRegex.test(url);
150 export function isVideo(url: string) {
151 return videoRegex.test(url);
154 export function validURL(str: string) {
156 return !!new URL(str);
162 export function validEmail(email: string) {
163 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,}))$/;
164 return re.test(String(email).toLowerCase());
167 export function capitalizeFirstLetter(str: string): string {
168 return str.charAt(0).toUpperCase() + str.slice(1);
171 export function routeSortTypeToEnum(sort: string): SortType {
174 } else if (sort == 'hot') {
176 } else if (sort == 'topday') {
177 return SortType.TopDay;
178 } else if (sort == 'topweek') {
179 return SortType.TopWeek;
180 } else if (sort == 'topmonth') {
181 return SortType.TopMonth;
182 } else if (sort == 'topyear') {
183 return SortType.TopYear;
184 } else if (sort == 'topall') {
185 return SortType.TopAll;
189 export function routeListingTypeToEnum(type: string): ListingType {
190 return ListingType[capitalizeFirstLetter(type)];
193 export function routeSearchTypeToEnum(type: string): SearchType {
194 return SearchType[capitalizeFirstLetter(type)];
197 export async function getPageTitle(url: string) {
198 let res = await fetch(`https://textance.herokuapp.com/title/${url}`);
199 let data = await res.text();
203 export function debounce(
206 immediate: boolean = false
208 // 'private' variable for instance
209 // The returned function will be able to reference this due to closure.
210 // Each call to the returned function will share this common timer.
213 // Calling debounce returns a new anonymous function
215 // reference the context and args for the setTimeout function
219 // Should the function be called now? If immediate is true
220 // and not already in a timeout then the answer is: Yes
221 var callNow = immediate && !timeout;
223 // This is the basic debounce behaviour where you can call this
224 // function several times, but it will only execute once
225 // [before or after imposing a delay].
226 // Each time the returned function is called, the timer starts over.
227 clearTimeout(timeout);
229 // Set the new timeout
230 timeout = setTimeout(function() {
231 // Inside the timeout function, clear the timeout variable
232 // which will let the next execution run when in 'immediate' mode
235 // Check if the function already ran with the immediate flag
237 // Call the original function with apply
238 // apply lets you define the 'this' object as well as the arguments
239 // (both captured before setTimeout)
240 func.apply(context, args);
244 // Immediate mode and no wait timer? Execute the function..
245 if (callNow) func.apply(context, args);
249 export const languages = [
250 { code: 'en', name: 'English' },
251 { code: 'eo', name: 'Esperanto' },
252 { code: 'es', name: 'Español' },
253 { code: 'de', name: 'Deutsch' },
254 { code: 'zh', name: '中文' },
255 { code: 'fr', name: 'Français' },
256 { code: 'sv', name: 'Svenska' },
257 { code: 'ru', name: 'Русский' },
258 { code: 'nl', name: 'Nederlands' },
259 { code: 'it', name: 'Italiano' },
262 export function getLanguage(): string {
263 let user = UserService.Instance.user;
264 let lang = user && user.lang ? user.lang : 'browser';
266 if (lang == 'browser') {
267 return getBrowserLanguage();
273 export function getBrowserLanguage(): string {
274 return navigator.language;
277 export function getMomentLanguage(): string {
278 let lang = getLanguage();
279 if (lang.startsWith('zh')) {
281 } else if (lang.startsWith('sv')) {
283 } else if (lang.startsWith('fr')) {
285 } else if (lang.startsWith('de')) {
287 } else if (lang.startsWith('ru')) {
289 } else if (lang.startsWith('es')) {
291 } else if (lang.startsWith('eo')) {
293 } else if (lang.startsWith('nl')) {
295 } else if (lang.startsWith('it')) {
303 export const themes = [
316 export function setTheme(theme: string = 'darkly') {
317 // unload all the other themes
318 for (var i = 0; i < themes.length; i++) {
319 let styleSheet = document.getElementById(themes[i]);
321 styleSheet.setAttribute('disabled', 'disabled');
325 // Load the theme dynamically
326 if (!document.getElementById(theme)) {
327 var head = document.getElementsByTagName('head')[0];
328 var link = document.createElement('link');
330 link.rel = 'stylesheet';
331 link.type = 'text/css';
332 link.href = `/static/assets/css/themes/${theme}.min.css`;
334 head.appendChild(link);
336 document.getElementById(theme).removeAttribute('disabled');
339 export function objectFlip(obj: any) {
341 Object.keys(obj).forEach(key => {
347 export function pictshareAvatarThumbnail(src: string): string {
348 // sample url: http://localhost:8535/pictshare/gs7xuu.jpg
349 let split = src.split('pictshare');
350 let out = `${split[0]}pictshare/96x96${split[1]}`;
354 export function showAvatars(): boolean {
356 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
357 !UserService.Instance.user
361 /// Converts to image thumbnail (only supports pictshare currently)
362 export function imageThumbnailer(url: string): string {
363 let split = url.split('pictshare');
364 if (split.length > 1) {
365 let out = `${split[0]}pictshare/140x140${split[1]}`;
372 export function isCommentType(item: Comment | PrivateMessage): item is Comment {
373 return (item as Comment).community_id !== undefined;
376 export function toast(text: string, background: string = 'success') {
377 let backgroundColor = `var(--${background})`;
380 backgroundColor: backgroundColor,