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';
23 WebSocketJsonResponse,
26 } from './interfaces';
27 import { UserService, WebSocketService } from './services';
29 import Tribute from 'tributejs/src/Tribute.js';
30 import markdown_it from 'markdown-it';
31 import markdownitEmoji from 'markdown-it-emoji/light';
32 import markdown_it_container from 'markdown-it-container';
33 import twemoji from 'twemoji';
34 import emojiShortName from 'emoji-short-name';
35 import Toastify from 'toastify-js';
37 export const repoUrl = 'https://github.com/dessalines/lemmy';
38 export const markdownHelpUrl = 'https://commonmark.org/help/';
39 export const archiveUrl = 'https://archive.is';
41 export const postRefetchSeconds: number = 60 * 1000;
42 export const fetchLimit: number = 20;
43 export const mentionDropdownFetchLimit = 10;
45 export function randomStr() {
48 .replace(/[^a-z]+/g, '')
52 export function wsJsonToRes(msg: WebSocketJsonResponse): WebSocketResponse {
53 let opStr: string = msg.op;
55 op: UserOperation[opStr],
60 export const md = new markdown_it({
65 .use(markdown_it_container, 'spoiler', {
66 validate: function(params: any) {
67 return params.trim().match(/^spoiler\s+(.*)$/);
70 render: function(tokens: any, idx: any) {
71 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
73 if (tokens[idx].nesting === 1) {
75 return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
78 return '</details>\n';
82 .use(markdownitEmoji, {
83 defs: objectFlip(emojiShortName),
86 md.renderer.rules.emoji = function(token, idx) {
87 return twemoji.parse(token[idx].content);
90 export function hotRank(comment: Comment): number {
91 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
93 let date: Date = new Date(comment.published + 'Z'); // Add Z to convert from UTC date
94 let now: Date = new Date();
95 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
98 (10000 * Math.log10(Math.max(1, 3 + comment.score))) /
99 Math.pow(hoursElapsed + 2, 1.8);
101 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
106 export function mdToHtml(text: string) {
107 return { __html: md.render(text) };
110 export function getUnixTime(text: string): number {
111 return text ? new Date(text).getTime() / 1000 : undefined;
114 export function addTypeInfo<T>(
117 ): Array<{ type_: string; data: T }> {
118 return arr.map(e => {
119 return { type_: name, data: e };
123 export function canMod(
125 modIds: Array<number>,
127 onSelf: boolean = false
129 // You can do moderator actions only on the mods added after you.
131 let yourIndex = modIds.findIndex(id => id == user.id);
132 if (yourIndex == -1) {
135 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
136 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
137 return !modIds.includes(creator_id);
144 export function isMod(modIds: Array<number>, creator_id: number): boolean {
145 return modIds.includes(creator_id);
148 var imageRegex = new RegExp(
149 `(http)?s?:?(\/\/[^"']*\.(?:png|jpg|jpeg|gif|png|svg))`
151 var videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
153 export function isImage(url: string) {
154 return imageRegex.test(url);
157 export function isVideo(url: string) {
158 return videoRegex.test(url);
161 export function validURL(str: string) {
163 return !!new URL(str);
169 export function validEmail(email: string) {
170 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,}))$/;
171 return re.test(String(email).toLowerCase());
174 export function capitalizeFirstLetter(str: string): string {
175 return str.charAt(0).toUpperCase() + str.slice(1);
178 export function routeSortTypeToEnum(sort: string): SortType {
181 } else if (sort == 'hot') {
183 } else if (sort == 'topday') {
184 return SortType.TopDay;
185 } else if (sort == 'topweek') {
186 return SortType.TopWeek;
187 } else if (sort == 'topmonth') {
188 return SortType.TopMonth;
189 } else if (sort == 'topyear') {
190 return SortType.TopYear;
191 } else if (sort == 'topall') {
192 return SortType.TopAll;
196 export function routeListingTypeToEnum(type: string): ListingType {
197 return ListingType[capitalizeFirstLetter(type)];
200 export function routeSearchTypeToEnum(type: string): SearchType {
201 return SearchType[capitalizeFirstLetter(type)];
204 export async function getPageTitle(url: string) {
205 let res = await fetch(`https://textance.herokuapp.com/title/${url}`);
206 let data = await res.text();
210 export function debounce(
213 immediate: boolean = false
215 // 'private' variable for instance
216 // The returned function will be able to reference this due to closure.
217 // Each call to the returned function will share this common timer.
220 // Calling debounce returns a new anonymous function
222 // reference the context and args for the setTimeout function
226 // Should the function be called now? If immediate is true
227 // and not already in a timeout then the answer is: Yes
228 var callNow = immediate && !timeout;
230 // This is the basic debounce behaviour where you can call this
231 // function several times, but it will only execute once
232 // [before or after imposing a delay].
233 // Each time the returned function is called, the timer starts over.
234 clearTimeout(timeout);
236 // Set the new timeout
237 timeout = setTimeout(function() {
238 // Inside the timeout function, clear the timeout variable
239 // which will let the next execution run when in 'immediate' mode
242 // Check if the function already ran with the immediate flag
244 // Call the original function with apply
245 // apply lets you define the 'this' object as well as the arguments
246 // (both captured before setTimeout)
247 func.apply(context, args);
251 // Immediate mode and no wait timer? Execute the function..
252 if (callNow) func.apply(context, args);
256 export const languages = [
257 { code: 'ca', name: 'Català' },
258 { code: 'en', name: 'English' },
259 { code: 'eo', name: 'Esperanto' },
260 { code: 'es', name: 'Español' },
261 { code: 'de', name: 'Deutsch' },
262 { code: 'fa', name: 'فارسی' },
263 { code: 'zh', name: '中文' },
264 { code: 'fi', name: 'Suomi' },
265 { code: 'fr', name: 'Français' },
266 { code: 'sv', name: 'Svenska' },
267 { code: 'ru', name: 'Русский' },
268 { code: 'nl', name: 'Nederlands' },
269 { code: 'it', name: 'Italiano' },
272 export function getLanguage(): string {
273 let user = UserService.Instance.user;
274 let lang = user && user.lang ? user.lang : 'browser';
276 if (lang == 'browser') {
277 return getBrowserLanguage();
283 export function getBrowserLanguage(): string {
284 return navigator.language;
287 export function getMomentLanguage(): string {
288 let lang = getLanguage();
289 if (lang.startsWith('zh')) {
291 } else if (lang.startsWith('sv')) {
293 } else if (lang.startsWith('fr')) {
295 } else if (lang.startsWith('de')) {
297 } else if (lang.startsWith('ru')) {
299 } else if (lang.startsWith('es')) {
301 } else if (lang.startsWith('eo')) {
303 } else if (lang.startsWith('nl')) {
305 } else if (lang.startsWith('it')) {
307 } else if (lang.startsWith('fi')) {
309 } else if (lang.startsWith('ca')) {
311 } else if (lang.startsWith('fa')) {
319 export const themes = [
334 export function setTheme(theme: string = 'darkly') {
335 // unload all the other themes
336 for (var i = 0; i < themes.length; i++) {
337 let styleSheet = document.getElementById(themes[i]);
339 styleSheet.setAttribute('disabled', 'disabled');
343 // Load the theme dynamically
344 if (!document.getElementById(theme)) {
345 var head = document.getElementsByTagName('head')[0];
346 var link = document.createElement('link');
348 link.rel = 'stylesheet';
349 link.type = 'text/css';
350 link.href = `/static/assets/css/themes/${theme}.min.css`;
352 head.appendChild(link);
354 document.getElementById(theme).removeAttribute('disabled');
357 export function objectFlip(obj: any) {
359 Object.keys(obj).forEach(key => {
365 export function pictshareAvatarThumbnail(src: string): string {
366 // sample url: http://localhost:8535/pictshare/gs7xuu.jpg
367 let split = src.split('pictshare');
368 let out = `${split[0]}pictshare/96x96${split[1]}`;
372 export function showAvatars(): boolean {
374 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
375 !UserService.Instance.user
379 /// Converts to image thumbnail (only supports pictshare currently)
380 export function imageThumbnailer(url: string): string {
381 let split = url.split('pictshare');
382 if (split.length > 1) {
383 let out = `${split[0]}pictshare/140x140${split[1]}`;
390 export function isCommentType(item: Comment | PrivateMessage): item is Comment {
391 return (item as Comment).community_id !== undefined;
394 export function toast(text: string, background: string = 'success') {
395 let backgroundColor = `var(--${background})`;
398 backgroundColor: backgroundColor,
404 export function setupTribute(): Tribute {
410 menuItemTemplate: (item: any) => {
411 let emoji = `:${item.original.key}:`;
412 return `${item.original.val} ${emoji}`;
414 selectTemplate: (item: any) => {
415 return `:${item.original.key}:`;
417 values: Object.entries(emojiShortName).map(e => {
418 return { key: e[1], val: e[0] };
421 autocompleteMode: true,
422 menuItemLimit: mentionDropdownFetchLimit,
427 selectTemplate: (item: any) => {
428 return `[/u/${item.original.key}](/u/${item.original.key})`;
430 values: (text: string, cb: any) => {
431 userSearch(text, (users: any) => cb(users));
434 autocompleteMode: true,
435 menuItemLimit: mentionDropdownFetchLimit,
441 selectTemplate: (item: any) => {
442 return `[/c/${item.original.key}](/c/${item.original.key})`;
444 values: (text: string, cb: any) => {
445 communitySearch(text, (communities: any) => cb(communities));
448 autocompleteMode: true,
449 menuItemLimit: mentionDropdownFetchLimit,
455 function userSearch(text: string, cb: any) {
457 let form: SearchForm = {
459 type_: SearchType[SearchType.Users],
460 sort: SortType[SortType.TopAll],
462 limit: mentionDropdownFetchLimit,
465 WebSocketService.Instance.search(form);
467 this.userSub = WebSocketService.Instance.subject.subscribe(
469 let res = wsJsonToRes(msg);
470 if (res.op == UserOperation.Search) {
471 let data = res.data as SearchResponse;
472 let users = data.users.map(u => {
473 return { key: u.name };
476 this.userSub.unsubscribe();
479 err => console.error(err),
480 () => console.log('complete')
487 function communitySearch(text: string, cb: any) {
489 let form: SearchForm = {
491 type_: SearchType[SearchType.Communities],
492 sort: SortType[SortType.TopAll],
494 limit: mentionDropdownFetchLimit,
497 WebSocketService.Instance.search(form);
499 this.communitySub = WebSocketService.Instance.subject.subscribe(
501 let res = wsJsonToRes(msg);
502 if (res.op == UserOperation.Search) {
503 let data = res.data as SearchResponse;
504 let communities = data.communities.map(u => {
505 return { key: u.name };
508 this.communitySub.unsubscribe();
511 err => console.error(err),
512 () => console.log('complete')