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,
23 } from './interfaces';
24 import { UserService, WebSocketService } from './services';
26 import Tribute from 'tributejs/src/Tribute.js';
27 import markdown_it from 'markdown-it';
28 import markdownitEmoji from 'markdown-it-emoji/light';
29 import markdown_it_container from 'markdown-it-container';
30 import twemoji from 'twemoji';
31 import emojiShortName from 'emoji-short-name';
32 import Toastify from 'toastify-js';
34 export const repoUrl = 'https://github.com/dessalines/lemmy';
35 export const markdownHelpUrl = 'https://commonmark.org/help/';
36 export const archiveUrl = 'https://archive.is';
38 export const postRefetchSeconds: number = 60 * 1000;
39 export const fetchLimit: number = 20;
40 export const mentionDropdownFetchLimit = 10;
42 export function randomStr() {
45 .replace(/[^a-z]+/g, '')
49 export function wsJsonToRes(msg: WebSocketJsonResponse): WebSocketResponse {
50 let opStr: string = msg.op;
52 op: UserOperation[opStr],
57 export const md = new markdown_it({
62 .use(markdown_it_container, 'spoiler', {
63 validate: function(params: any) {
64 return params.trim().match(/^spoiler\s+(.*)$/);
67 render: function(tokens: any, idx: any) {
68 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
70 if (tokens[idx].nesting === 1) {
72 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
75 return '</details>\n';
79 .use(markdownitEmoji, {
80 defs: objectFlip(emojiShortName),
83 md.renderer.rules.emoji = function(token, idx) {
84 return twemoji.parse(token[idx].content);
87 export function hotRank(comment: Comment): number {
88 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
90 let date: Date = new Date(comment.published + 'Z'); // Add Z to convert from UTC date
91 let now: Date = new Date();
92 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
95 (10000 * Math.log10(Math.max(1, 3 + comment.score))) /
96 Math.pow(hoursElapsed + 2, 1.8);
98 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
103 export function mdToHtml(text: string) {
104 return { __html: md.render(text) };
107 export function getUnixTime(text: string): number {
108 return text ? new Date(text).getTime() / 1000 : undefined;
111 export function addTypeInfo<T>(
114 ): Array<{ type_: string; data: T }> {
115 return arr.map(e => {
116 return { type_: name, data: e };
120 export function canMod(
122 modIds: Array<number>,
124 onSelf: boolean = false
126 // You can do moderator actions only on the mods added after you.
128 let yourIndex = modIds.findIndex(id => id == user.id);
129 if (yourIndex == -1) {
132 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
133 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
134 return !modIds.includes(creator_id);
141 export function isMod(modIds: Array<number>, creator_id: number): boolean {
142 return modIds.includes(creator_id);
145 var imageRegex = new RegExp(
146 `(http)?s?:?(\/\/[^"']*\.(?:png|jpg|jpeg|gif|png|svg))`
148 var videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
150 export function isImage(url: string) {
151 return imageRegex.test(url);
154 export function isVideo(url: string) {
155 return videoRegex.test(url);
158 export function validURL(str: string) {
160 return !!new URL(str);
166 export function validEmail(email: string) {
167 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,}))$/;
168 return re.test(String(email).toLowerCase());
171 export function capitalizeFirstLetter(str: string): string {
172 return str.charAt(0).toUpperCase() + str.slice(1);
175 export function routeSortTypeToEnum(sort: string): SortType {
178 } else if (sort == 'hot') {
180 } else if (sort == 'topday') {
181 return SortType.TopDay;
182 } else if (sort == 'topweek') {
183 return SortType.TopWeek;
184 } else if (sort == 'topmonth') {
185 return SortType.TopMonth;
186 } else if (sort == 'topyear') {
187 return SortType.TopYear;
188 } else if (sort == 'topall') {
189 return SortType.TopAll;
193 export function routeListingTypeToEnum(type: string): ListingType {
194 return ListingType[capitalizeFirstLetter(type)];
197 export function routeSearchTypeToEnum(type: string): SearchType {
198 return SearchType[capitalizeFirstLetter(type)];
201 export async function getPageTitle(url: string) {
202 let res = await fetch(`https://textance.herokuapp.com/title/${url}`);
203 let data = await res.text();
207 export function debounce(
210 immediate: boolean = false
212 // 'private' variable for instance
213 // The returned function will be able to reference this due to closure.
214 // Each call to the returned function will share this common timer.
217 // Calling debounce returns a new anonymous function
219 // reference the context and args for the setTimeout function
223 // Should the function be called now? If immediate is true
224 // and not already in a timeout then the answer is: Yes
225 var callNow = immediate && !timeout;
227 // This is the basic debounce behaviour where you can call this
228 // function several times, but it will only execute once
229 // [before or after imposing a delay].
230 // Each time the returned function is called, the timer starts over.
231 clearTimeout(timeout);
233 // Set the new timeout
234 timeout = setTimeout(function() {
235 // Inside the timeout function, clear the timeout variable
236 // which will let the next execution run when in 'immediate' mode
239 // Check if the function already ran with the immediate flag
241 // Call the original function with apply
242 // apply lets you define the 'this' object as well as the arguments
243 // (both captured before setTimeout)
244 func.apply(context, args);
248 // Immediate mode and no wait timer? Execute the function..
249 if (callNow) func.apply(context, args);
253 export const languages = [
254 { code: 'en', name: 'English' },
255 { code: 'eo', name: 'Esperanto' },
256 { code: 'es', name: 'Español' },
257 { code: 'de', name: 'Deutsch' },
258 { code: 'zh', name: '中文' },
259 { code: 'fr', name: 'Français' },
260 { code: 'sv', name: 'Svenska' },
261 { code: 'ru', name: 'Русский' },
262 { code: 'nl', name: 'Nederlands' },
263 { code: 'it', name: 'Italiano' },
266 export function getLanguage(): string {
267 let user = UserService.Instance.user;
268 let lang = user && user.lang ? user.lang : 'browser';
270 if (lang == 'browser') {
271 return getBrowserLanguage();
277 export function getBrowserLanguage(): string {
278 return navigator.language;
281 export function getMomentLanguage(): string {
282 let lang = getLanguage();
283 if (lang.startsWith('zh')) {
285 } else if (lang.startsWith('sv')) {
287 } else if (lang.startsWith('fr')) {
289 } else if (lang.startsWith('de')) {
291 } else if (lang.startsWith('ru')) {
293 } else if (lang.startsWith('es')) {
295 } else if (lang.startsWith('eo')) {
297 } else if (lang.startsWith('nl')) {
299 } else if (lang.startsWith('it')) {
307 export const themes = [
320 export function setTheme(theme: string = 'darkly') {
321 // unload all the other themes
322 for (var i = 0; i < themes.length; i++) {
323 let styleSheet = document.getElementById(themes[i]);
325 styleSheet.setAttribute('disabled', 'disabled');
329 // Load the theme dynamically
330 if (!document.getElementById(theme)) {
331 var head = document.getElementsByTagName('head')[0];
332 var link = document.createElement('link');
334 link.rel = 'stylesheet';
335 link.type = 'text/css';
336 link.href = `/static/assets/css/themes/${theme}.min.css`;
338 head.appendChild(link);
340 document.getElementById(theme).removeAttribute('disabled');
343 export function objectFlip(obj: any) {
345 Object.keys(obj).forEach(key => {
351 export function pictshareAvatarThumbnail(src: string): string {
352 // sample url: http://localhost:8535/pictshare/gs7xuu.jpg
353 let split = src.split('pictshare');
354 let out = `${split[0]}pictshare/96x96${split[1]}`;
358 export function showAvatars(): boolean {
360 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
361 !UserService.Instance.user
365 /// Converts to image thumbnail (only supports pictshare currently)
366 export function imageThumbnailer(url: string): string {
367 let split = url.split('pictshare');
368 if (split.length > 1) {
369 let out = `${split[0]}pictshare/140x140${split[1]}`;
376 export function isCommentType(item: Comment | PrivateMessage): item is Comment {
377 return (item as Comment).community_id !== undefined;
380 export function toast(text: string, background: string = 'success') {
381 let backgroundColor = `var(--${background})`;
384 backgroundColor: backgroundColor,
390 export function setupTribute(): Tribute {
396 menuItemTemplate: (item: any) => {
397 let emoji = `:${item.original.key}:`;
398 return `${item.original.val} ${emoji}`;
400 selectTemplate: (item: any) => {
401 return `:${item.original.key}:`;
403 values: Object.entries(emojiShortName).map(e => {
404 return { key: e[1], val: e[0] };
407 autocompleteMode: true,
408 menuItemLimit: mentionDropdownFetchLimit,
413 selectTemplate: (item: any) => {
414 return `[/u/${item.original.key}](/u/${item.original.key})`;
416 values: (text: string, cb: any) => {
417 userSearch(text, (users: any) => cb(users));
420 autocompleteMode: true,
421 menuItemLimit: mentionDropdownFetchLimit,
427 selectTemplate: (item: any) => {
428 return `[/c/${item.original.key}](/c/${item.original.key})`;
430 values: (text: string, cb: any) => {
431 communitySearch(text, (communities: any) => cb(communities));
434 autocompleteMode: true,
435 menuItemLimit: mentionDropdownFetchLimit,
441 function userSearch(text: string, cb: any) {
443 let form: SearchForm = {
445 type_: SearchType[SearchType.Users],
446 sort: SortType[SortType.TopAll],
448 limit: mentionDropdownFetchLimit,
451 WebSocketService.Instance.search(form);
453 this.userSub = WebSocketService.Instance.subject.subscribe(
455 let res = wsJsonToRes(msg);
456 if (res.op == UserOperation.Search) {
457 let data = res.data as SearchResponse;
458 let users = data.users.map(u => {
459 return { key: u.name };
462 this.userSub.unsubscribe();
465 err => console.error(err),
466 () => console.log('complete')
473 function communitySearch(text: string, cb: any) {
475 let form: SearchForm = {
477 type_: SearchType[SearchType.Communities],
478 sort: SortType[SortType.TopAll],
480 limit: mentionDropdownFetchLimit,
483 WebSocketService.Instance.search(form);
485 this.communitySub = WebSocketService.Instance.subject.subscribe(
487 let res = wsJsonToRes(msg);
488 if (res.op == UserOperation.Search) {
489 let data = res.data as SearchResponse;
490 let communities = data.communities.map(u => {
491 return { key: u.name };
494 this.communitySub.unsubscribe();
497 err => console.error(err),
498 () => console.log('complete')