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';
25 WebSocketJsonResponse,
28 } from './interfaces';
29 import { UserService, WebSocketService } from './services';
31 import Tribute from 'tributejs/src/Tribute.js';
32 import markdown_it from 'markdown-it';
33 import markdownitEmoji from 'markdown-it-emoji/light';
34 import markdown_it_container from 'markdown-it-container';
35 import twemoji from 'twemoji';
36 import emojiShortName from 'emoji-short-name';
37 import Toastify from 'toastify-js';
39 export const repoUrl = 'https://github.com/dessalines/lemmy';
40 export const markdownHelpUrl = 'https://commonmark.org/help/';
41 export const archiveUrl = 'https://archive.is';
43 export const postRefetchSeconds: number = 60 * 1000;
44 export const fetchLimit: number = 20;
45 export const mentionDropdownFetchLimit = 10;
47 export function randomStr() {
50 .replace(/[^a-z]+/g, '')
54 export function wsJsonToRes(msg: WebSocketJsonResponse): WebSocketResponse {
55 let opStr: string = msg.op;
57 op: UserOperation[opStr],
62 export const md = new markdown_it({
67 .use(markdown_it_container, 'spoiler', {
68 validate: function(params: any) {
69 return params.trim().match(/^spoiler\s+(.*)$/);
72 render: function(tokens: any, idx: any) {
73 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
75 if (tokens[idx].nesting === 1) {
77 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
80 return '</details>\n';
84 .use(markdownitEmoji, {
85 defs: objectFlip(emojiShortName),
88 md.renderer.rules.emoji = function(token, idx) {
89 return twemoji.parse(token[idx].content);
92 export function hotRank(comment: Comment): number {
93 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
95 let date: Date = new Date(comment.published + 'Z'); // Add Z to convert from UTC date
96 let now: Date = new Date();
97 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
100 (10000 * Math.log10(Math.max(1, 3 + comment.score))) /
101 Math.pow(hoursElapsed + 2, 1.8);
103 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
108 export function mdToHtml(text: string) {
109 return { __html: md.render(text) };
112 export function getUnixTime(text: string): number {
113 return text ? new Date(text).getTime() / 1000 : undefined;
116 export function addTypeInfo<T>(
119 ): Array<{ type_: string; data: T }> {
120 return arr.map(e => {
121 return { type_: name, data: e };
125 export function canMod(
127 modIds: Array<number>,
129 onSelf: boolean = false
131 // You can do moderator actions only on the mods added after you.
133 let yourIndex = modIds.findIndex(id => id == user.id);
134 if (yourIndex == -1) {
137 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
138 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
139 return !modIds.includes(creator_id);
146 export function isMod(modIds: Array<number>, creator_id: number): boolean {
147 return modIds.includes(creator_id);
150 var imageRegex = new RegExp(
151 `(http)?s?:?(\/\/[^"']*\.(?:png|jpg|jpeg|gif|png|svg))`
153 var videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
155 export function isImage(url: string) {
156 return imageRegex.test(url);
159 export function isVideo(url: string) {
160 return videoRegex.test(url);
163 export function validURL(str: string) {
165 return !!new URL(str);
171 export function validEmail(email: string) {
172 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,}))$/;
173 return re.test(String(email).toLowerCase());
176 export function capitalizeFirstLetter(str: string): string {
177 return str.charAt(0).toUpperCase() + str.slice(1);
180 export function routeSortTypeToEnum(sort: string): SortType {
183 } else if (sort == 'hot') {
185 } else if (sort == 'topday') {
186 return SortType.TopDay;
187 } else if (sort == 'topweek') {
188 return SortType.TopWeek;
189 } else if (sort == 'topmonth') {
190 return SortType.TopMonth;
191 } else if (sort == 'topyear') {
192 return SortType.TopYear;
193 } else if (sort == 'topall') {
194 return SortType.TopAll;
198 export function routeListingTypeToEnum(type: string): ListingType {
199 return ListingType[capitalizeFirstLetter(type)];
202 export function routeDataTypeToEnum(type: string): DataType {
203 return DataType[capitalizeFirstLetter(type)];
206 export function routeSearchTypeToEnum(type: string): SearchType {
207 return SearchType[capitalizeFirstLetter(type)];
210 export async function getPageTitle(url: string) {
211 let res = await fetch(`https://textance.herokuapp.com/title/${url}`);
212 let data = await res.text();
216 export function debounce(
219 immediate: boolean = false
221 // 'private' variable for instance
222 // The returned function will be able to reference this due to closure.
223 // Each call to the returned function will share this common timer.
226 // Calling debounce returns a new anonymous function
228 // reference the context and args for the setTimeout function
232 // Should the function be called now? If immediate is true
233 // and not already in a timeout then the answer is: Yes
234 var callNow = immediate && !timeout;
236 // This is the basic debounce behaviour where you can call this
237 // function several times, but it will only execute once
238 // [before or after imposing a delay].
239 // Each time the returned function is called, the timer starts over.
240 clearTimeout(timeout);
242 // Set the new timeout
243 timeout = setTimeout(function() {
244 // Inside the timeout function, clear the timeout variable
245 // which will let the next execution run when in 'immediate' mode
248 // Check if the function already ran with the immediate flag
250 // Call the original function with apply
251 // apply lets you define the 'this' object as well as the arguments
252 // (both captured before setTimeout)
253 func.apply(context, args);
257 // Immediate mode and no wait timer? Execute the function..
258 if (callNow) func.apply(context, args);
262 export const languages = [
263 { code: 'ca', name: 'Català' },
264 { code: 'en', name: 'English' },
265 { code: 'eo', name: 'Esperanto' },
266 { code: 'es', name: 'Español' },
267 { code: 'de', name: 'Deutsch' },
268 { code: 'fa', name: 'فارسی' },
269 { code: 'pt_BR', name: 'Português Brasileiro' },
270 { code: 'zh', name: '中文' },
271 { code: 'fi', name: 'Suomi' },
272 { code: 'fr', name: 'Français' },
273 { code: 'sv', name: 'Svenska' },
274 { code: 'ru', name: 'Русский' },
275 { code: 'nl', name: 'Nederlands' },
276 { code: 'it', name: 'Italiano' },
279 export function getLanguage(): string {
280 let user = UserService.Instance.user;
281 let lang = user && user.lang ? user.lang : 'browser';
283 if (lang == 'browser') {
284 return getBrowserLanguage();
290 export function getBrowserLanguage(): string {
291 return navigator.language;
294 export function getMomentLanguage(): string {
295 let lang = getLanguage();
296 if (lang.startsWith('zh')) {
298 } else if (lang.startsWith('sv')) {
300 } else if (lang.startsWith('fr')) {
302 } else if (lang.startsWith('de')) {
304 } else if (lang.startsWith('ru')) {
306 } else if (lang.startsWith('es')) {
308 } else if (lang.startsWith('eo')) {
310 } else if (lang.startsWith('nl')) {
312 } else if (lang.startsWith('it')) {
314 } else if (lang.startsWith('fi')) {
316 } else if (lang.startsWith('ca')) {
318 } else if (lang.startsWith('fa')) {
320 } else if (lang.startsWith('pt')) {
328 export const themes = [
343 export function setTheme(theme: string = 'darkly') {
344 // unload all the other themes
345 for (var i = 0; i < themes.length; i++) {
346 let styleSheet = document.getElementById(themes[i]);
348 styleSheet.setAttribute('disabled', 'disabled');
352 // Load the theme dynamically
353 if (!document.getElementById(theme)) {
354 var head = document.getElementsByTagName('head')[0];
355 var link = document.createElement('link');
357 link.rel = 'stylesheet';
358 link.type = 'text/css';
359 link.href = `/static/assets/css/themes/${theme}.min.css`;
361 head.appendChild(link);
363 document.getElementById(theme).removeAttribute('disabled');
366 export function objectFlip(obj: any) {
368 Object.keys(obj).forEach(key => {
374 export function pictshareAvatarThumbnail(src: string): string {
375 // sample url: http://localhost:8535/pictshare/gs7xuu.jpg
376 let split = src.split('pictshare');
377 let out = `${split[0]}pictshare/96x96${split[1]}`;
381 export function showAvatars(): boolean {
383 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
384 !UserService.Instance.user
388 /// Converts to image thumbnail (only supports pictshare currently)
389 export function imageThumbnailer(url: string): string {
390 let split = url.split('pictshare');
391 if (split.length > 1) {
392 let out = `${split[0]}pictshare/192x192${split[1]}`;
399 export function isCommentType(item: Comment | PrivateMessage): item is Comment {
400 return (item as Comment).community_id !== undefined;
403 export function toast(text: string, background: string = 'success') {
404 let backgroundColor = `var(--${background})`;
407 backgroundColor: backgroundColor,
413 export function setupTribute(): Tribute {
419 menuItemTemplate: (item: any) => {
420 let emoji = `:${item.original.key}:`;
421 return `${item.original.val} ${emoji}`;
423 selectTemplate: (item: any) => {
424 return `:${item.original.key}:`;
426 values: Object.entries(emojiShortName).map(e => {
427 return { key: e[1], val: e[0] };
430 autocompleteMode: true,
431 menuItemLimit: mentionDropdownFetchLimit,
436 selectTemplate: (item: any) => {
437 return `[/u/${item.original.key}](/u/${item.original.key})`;
439 values: (text: string, cb: any) => {
440 userSearch(text, (users: any) => cb(users));
443 autocompleteMode: true,
444 menuItemLimit: mentionDropdownFetchLimit,
450 selectTemplate: (item: any) => {
451 return `[/c/${item.original.key}](/c/${item.original.key})`;
453 values: (text: string, cb: any) => {
454 communitySearch(text, (communities: any) => cb(communities));
457 autocompleteMode: true,
458 menuItemLimit: mentionDropdownFetchLimit,
464 function userSearch(text: string, cb: any) {
466 let form: SearchForm = {
468 type_: SearchType[SearchType.Users],
469 sort: SortType[SortType.TopAll],
471 limit: mentionDropdownFetchLimit,
474 WebSocketService.Instance.search(form);
476 this.userSub = WebSocketService.Instance.subject.subscribe(
478 let res = wsJsonToRes(msg);
479 if (res.op == UserOperation.Search) {
480 let data = res.data as SearchResponse;
481 let users = data.users.map(u => {
482 return { key: u.name };
485 this.userSub.unsubscribe();
488 err => console.error(err),
489 () => console.log('complete')
496 function communitySearch(text: string, cb: any) {
498 let form: SearchForm = {
500 type_: SearchType[SearchType.Communities],
501 sort: SortType[SortType.TopAll],
503 limit: mentionDropdownFetchLimit,
506 WebSocketService.Instance.search(form);
508 this.communitySub = WebSocketService.Instance.subject.subscribe(
510 let res = wsJsonToRes(msg);
511 if (res.op == UserOperation.Search) {
512 let data = res.data as SearchResponse;
513 let communities = data.communities.map(u => {
514 return { key: u.name };
517 this.communitySub.unsubscribe();
520 err => console.error(err),
521 () => console.log('complete')
528 export function getListingTypeFromProps(props: any): ListingType {
529 return props.match.params.listing_type
530 ? routeListingTypeToEnum(props.match.params.listing_type)
531 : UserService.Instance.user
532 ? UserService.Instance.user.default_listing_type
536 // TODO might need to add a user setting for this too
537 export function getDataTypeFromProps(props: any): DataType {
538 return props.match.params.data_type
539 ? routeDataTypeToEnum(props.match.params.data_type)
543 export function getSortTypeFromProps(props: any): SortType {
544 return props.match.params.sort
545 ? routeSortTypeToEnum(props.match.params.sort)
546 : UserService.Instance.user
547 ? UserService.Instance.user.default_sort_type
551 export function getPageFromProps(props: any): number {
552 return props.match.params.page ? Number(props.match.params.page) : 1;