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';
10 import 'moment/locale/fi';
11 import 'moment/locale/ca';
12 import 'moment/locale/fa';
13 import 'moment/locale/pt-br';
24 WebSocketJsonResponse,
27 } from './interfaces';
28 import { UserService, WebSocketService } from './services';
30 import Tribute from 'tributejs/src/Tribute.js';
31 import markdown_it from 'markdown-it';
32 import markdownitEmoji from 'markdown-it-emoji/light';
33 import markdown_it_container from 'markdown-it-container';
34 import twemoji from 'twemoji';
35 import emojiShortName from 'emoji-short-name';
36 import Toastify from 'toastify-js';
38 export const repoUrl = 'https://github.com/dessalines/lemmy';
39 export const markdownHelpUrl = 'https://commonmark.org/help/';
40 export const archiveUrl = 'https://archive.is';
42 export const postRefetchSeconds: number = 60 * 1000;
43 export const fetchLimit: number = 20;
44 export const mentionDropdownFetchLimit = 10;
46 export function randomStr() {
49 .replace(/[^a-z]+/g, '')
53 export function wsJsonToRes(msg: WebSocketJsonResponse): WebSocketResponse {
54 let opStr: string = msg.op;
56 op: UserOperation[opStr],
61 export const md = new markdown_it({
66 .use(markdown_it_container, 'spoiler', {
67 validate: function(params: any) {
68 return params.trim().match(/^spoiler\s+(.*)$/);
71 render: function(tokens: any, idx: any) {
72 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
74 if (tokens[idx].nesting === 1) {
76 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
79 return '</details>\n';
83 .use(markdownitEmoji, {
84 defs: objectFlip(emojiShortName),
87 md.renderer.rules.emoji = function(token, idx) {
88 return twemoji.parse(token[idx].content);
91 export function hotRank(comment: Comment): number {
92 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
94 let date: Date = new Date(comment.published + 'Z'); // Add Z to convert from UTC date
95 let now: Date = new Date();
96 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
99 (10000 * Math.log10(Math.max(1, 3 + comment.score))) /
100 Math.pow(hoursElapsed + 2, 1.8);
102 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
107 export function mdToHtml(text: string) {
108 return { __html: md.render(text) };
111 export function getUnixTime(text: string): number {
112 return text ? new Date(text).getTime() / 1000 : undefined;
115 export function addTypeInfo<T>(
118 ): Array<{ type_: string; data: T }> {
119 return arr.map(e => {
120 return { type_: name, data: e };
124 export function canMod(
126 modIds: Array<number>,
128 onSelf: boolean = false
130 // You can do moderator actions only on the mods added after you.
132 let yourIndex = modIds.findIndex(id => id == user.id);
133 if (yourIndex == -1) {
136 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
137 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
138 return !modIds.includes(creator_id);
145 export function isMod(modIds: Array<number>, creator_id: number): boolean {
146 return modIds.includes(creator_id);
149 var imageRegex = new RegExp(
150 `(http)?s?:?(\/\/[^"']*\.(?:png|jpg|jpeg|gif|png|svg))`
152 var videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
154 export function isImage(url: string) {
155 return imageRegex.test(url);
158 export function isVideo(url: string) {
159 return videoRegex.test(url);
162 export function validURL(str: string) {
164 return !!new URL(str);
170 export function validEmail(email: string) {
171 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,}))$/;
172 return re.test(String(email).toLowerCase());
175 export function capitalizeFirstLetter(str: string): string {
176 return str.charAt(0).toUpperCase() + str.slice(1);
179 export function routeSortTypeToEnum(sort: string): SortType {
182 } else if (sort == 'hot') {
184 } else if (sort == 'topday') {
185 return SortType.TopDay;
186 } else if (sort == 'topweek') {
187 return SortType.TopWeek;
188 } else if (sort == 'topmonth') {
189 return SortType.TopMonth;
190 } else if (sort == 'topyear') {
191 return SortType.TopYear;
192 } else if (sort == 'topall') {
193 return SortType.TopAll;
197 export function routeListingTypeToEnum(type: string): ListingType {
198 return ListingType[capitalizeFirstLetter(type)];
201 export function routeSearchTypeToEnum(type: string): SearchType {
202 return SearchType[capitalizeFirstLetter(type)];
205 export async function getPageTitle(url: string) {
206 let res = await fetch(`https://textance.herokuapp.com/title/${url}`);
207 let data = await res.text();
211 export function debounce(
214 immediate: boolean = false
216 // 'private' variable for instance
217 // The returned function will be able to reference this due to closure.
218 // Each call to the returned function will share this common timer.
221 // Calling debounce returns a new anonymous function
223 // reference the context and args for the setTimeout function
227 // Should the function be called now? If immediate is true
228 // and not already in a timeout then the answer is: Yes
229 var callNow = immediate && !timeout;
231 // This is the basic debounce behaviour where you can call this
232 // function several times, but it will only execute once
233 // [before or after imposing a delay].
234 // Each time the returned function is called, the timer starts over.
235 clearTimeout(timeout);
237 // Set the new timeout
238 timeout = setTimeout(function() {
239 // Inside the timeout function, clear the timeout variable
240 // which will let the next execution run when in 'immediate' mode
243 // Check if the function already ran with the immediate flag
245 // Call the original function with apply
246 // apply lets you define the 'this' object as well as the arguments
247 // (both captured before setTimeout)
248 func.apply(context, args);
252 // Immediate mode and no wait timer? Execute the function..
253 if (callNow) func.apply(context, args);
257 export const languages = [
258 { code: 'ca', name: 'Català' },
259 { code: 'en', name: 'English' },
260 { code: 'eo', name: 'Esperanto' },
261 { code: 'es', name: 'Español' },
262 { code: 'de', name: 'Deutsch' },
263 { code: 'fa', name: 'فارسی' },
264 { code: 'pt_BR', name: 'Português Brasileiro' },
265 { code: 'zh', name: '中文' },
266 { code: 'fi', name: 'Suomi' },
267 { code: 'fr', name: 'Français' },
268 { code: 'sv', name: 'Svenska' },
269 { code: 'ru', name: 'Русский' },
270 { code: 'nl', name: 'Nederlands' },
271 { code: 'it', name: 'Italiano' },
274 export function getLanguage(): string {
275 let user = UserService.Instance.user;
276 let lang = user && user.lang ? user.lang : 'browser';
278 if (lang == 'browser') {
279 return getBrowserLanguage();
285 export function getBrowserLanguage(): string {
286 return navigator.language;
289 export function getMomentLanguage(): string {
290 let lang = getLanguage();
291 if (lang.startsWith('zh')) {
293 } else if (lang.startsWith('sv')) {
295 } else if (lang.startsWith('fr')) {
297 } else if (lang.startsWith('de')) {
299 } else if (lang.startsWith('ru')) {
301 } else if (lang.startsWith('es')) {
303 } else if (lang.startsWith('eo')) {
305 } else if (lang.startsWith('nl')) {
307 } else if (lang.startsWith('it')) {
309 } else if (lang.startsWith('fi')) {
311 } else if (lang.startsWith('ca')) {
313 } else if (lang.startsWith('fa')) {
315 } else if (lang.startsWith('pt')) {
323 export const themes = [
338 export function setTheme(theme: string = 'darkly') {
339 // unload all the other themes
340 for (var i = 0; i < themes.length; i++) {
341 let styleSheet = document.getElementById(themes[i]);
343 styleSheet.setAttribute('disabled', 'disabled');
347 // Load the theme dynamically
348 if (!document.getElementById(theme)) {
349 var head = document.getElementsByTagName('head')[0];
350 var link = document.createElement('link');
352 link.rel = 'stylesheet';
353 link.type = 'text/css';
354 link.href = `/static/assets/css/themes/${theme}.min.css`;
356 head.appendChild(link);
358 document.getElementById(theme).removeAttribute('disabled');
361 export function objectFlip(obj: any) {
363 Object.keys(obj).forEach(key => {
369 export function pictshareAvatarThumbnail(src: string): string {
370 // sample url: http://localhost:8535/pictshare/gs7xuu.jpg
371 let split = src.split('pictshare');
372 let out = `${split[0]}pictshare/96x96${split[1]}`;
376 export function showAvatars(): boolean {
378 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
379 !UserService.Instance.user
383 /// Converts to image thumbnail (only supports pictshare currently)
384 export function imageThumbnailer(url: string): string {
385 let split = url.split('pictshare');
386 if (split.length > 1) {
387 let out = `${split[0]}pictshare/192x192${split[1]}`;
394 export function isCommentType(item: Comment | PrivateMessage): item is Comment {
395 return (item as Comment).community_id !== undefined;
398 export function toast(text: string, background: string = 'success') {
399 let backgroundColor = `var(--${background})`;
402 backgroundColor: backgroundColor,
408 export function setupTribute(): Tribute {
414 menuItemTemplate: (item: any) => {
415 let emoji = `:${item.original.key}:`;
416 return `${item.original.val} ${emoji}`;
418 selectTemplate: (item: any) => {
419 return `:${item.original.key}:`;
421 values: Object.entries(emojiShortName).map(e => {
422 return { key: e[1], val: e[0] };
425 autocompleteMode: true,
426 menuItemLimit: mentionDropdownFetchLimit,
431 selectTemplate: (item: any) => {
432 return `[/u/${item.original.key}](/u/${item.original.key})`;
434 values: (text: string, cb: any) => {
435 userSearch(text, (users: any) => cb(users));
438 autocompleteMode: true,
439 menuItemLimit: mentionDropdownFetchLimit,
445 selectTemplate: (item: any) => {
446 return `[/c/${item.original.key}](/c/${item.original.key})`;
448 values: (text: string, cb: any) => {
449 communitySearch(text, (communities: any) => cb(communities));
452 autocompleteMode: true,
453 menuItemLimit: mentionDropdownFetchLimit,
459 function userSearch(text: string, cb: any) {
461 let form: SearchForm = {
463 type_: SearchType[SearchType.Users],
464 sort: SortType[SortType.TopAll],
466 limit: mentionDropdownFetchLimit,
469 WebSocketService.Instance.search(form);
471 this.userSub = WebSocketService.Instance.subject.subscribe(
473 let res = wsJsonToRes(msg);
474 if (res.op == UserOperation.Search) {
475 let data = res.data as SearchResponse;
476 let users = data.users.map(u => {
477 return { key: u.name };
480 this.userSub.unsubscribe();
483 err => console.error(err),
484 () => console.log('complete')
491 function communitySearch(text: string, cb: any) {
493 let form: SearchForm = {
495 type_: SearchType[SearchType.Communities],
496 sort: SortType[SortType.TopAll],
498 limit: mentionDropdownFetchLimit,
501 WebSocketService.Instance.search(form);
503 this.communitySub = WebSocketService.Instance.subject.subscribe(
505 let res = wsJsonToRes(msg);
506 if (res.op == UserOperation.Search) {
507 let data = res.data as SearchResponse;
508 let communities = data.communities.map(u => {
509 return { key: u.name };
512 this.communitySub.unsubscribe();
515 err => console.error(err),
516 () => console.log('complete')