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 msgOp(msg: any): UserOperation {
43 let opStr: string = msg.op;
44 return UserOperation[opStr];
47 export const md = new markdown_it({
52 .use(markdown_it_container, 'spoiler', {
53 validate: function(params: any) {
54 return params.trim().match(/^spoiler\s+(.*)$/);
57 render: function(tokens: any, idx: any) {
58 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
60 if (tokens[idx].nesting === 1) {
62 return `<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 const languages = [
244 { code: 'en', name: 'English' },
245 { code: 'eo', name: 'Esperanto' },
246 { code: 'es', name: 'Español' },
247 { code: 'de', name: 'Deutsch' },
248 { code: 'zh', name: '中文' },
249 { code: 'fr', name: 'Français' },
250 { code: 'sv', name: 'Svenska' },
251 { code: 'ru', name: 'Русский' },
252 { code: 'nl', name: 'Nederlands' },
253 { code: 'it', name: 'Italiano' },
256 export function getLanguage(): string {
257 let user = UserService.Instance.user;
258 let lang = user && user.lang ? user.lang : 'browser';
260 if (lang == 'browser') {
261 return getBrowserLanguage();
267 export function getBrowserLanguage(): string {
268 return navigator.language;
271 export function getMomentLanguage(): string {
272 let lang = getLanguage();
273 if (lang.startsWith('zh')) {
275 } else if (lang.startsWith('sv')) {
277 } else if (lang.startsWith('fr')) {
279 } else if (lang.startsWith('de')) {
281 } else if (lang.startsWith('ru')) {
283 } else if (lang.startsWith('es')) {
285 } else if (lang.startsWith('eo')) {
287 } else if (lang.startsWith('nl')) {
289 } else if (lang.startsWith('it')) {
297 export const themes = [
310 export function setTheme(theme: string = 'darkly') {
311 // unload all the other themes
312 for (var i = 0; i < themes.length; i++) {
313 let styleSheet = document.getElementById(themes[i]);
315 styleSheet.setAttribute('disabled', 'disabled');
319 // Load the theme dynamically
320 if (!document.getElementById(theme)) {
321 var head = document.getElementsByTagName('head')[0];
322 var link = document.createElement('link');
324 link.rel = 'stylesheet';
325 link.type = 'text/css';
326 link.href = `/static/assets/css/themes/${theme}.min.css`;
328 head.appendChild(link);
330 document.getElementById(theme).removeAttribute('disabled');
333 export function objectFlip(obj: any) {
335 Object.keys(obj).forEach(key => {
341 export function pictshareAvatarThumbnail(src: string): string {
342 // sample url: http://localhost:8535/pictshare/gs7xuu.jpg
343 let split = src.split('pictshare');
344 let out = `${split[0]}pictshare/96x96${split[1]}`;
348 export function showAvatars(): boolean {
350 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
351 !UserService.Instance.user
355 /// Converts to image thumbnail (only supports pictshare currently)
356 export function imageThumbnailer(url: string): string {
357 let split = url.split('pictshare');
358 if (split.length > 1) {
359 let out = `${split[0]}pictshare/140x140${split[1]}`;
366 export function isCommentType(item: Comment | PrivateMessage): item is Comment {
367 return (item as Comment).community_id !== undefined;