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 = [
332 export function setTheme(theme: string = 'darkly') {
333 // unload all the other themes
334 for (var i = 0; i < themes.length; i++) {
335 let styleSheet = document.getElementById(themes[i]);
337 styleSheet.setAttribute('disabled', 'disabled');
341 // Load the theme dynamically
342 if (!document.getElementById(theme)) {
343 var head = document.getElementsByTagName('head')[0];
344 var link = document.createElement('link');
346 link.rel = 'stylesheet';
347 link.type = 'text/css';
348 link.href = `/static/assets/css/themes/${theme}.min.css`;
350 head.appendChild(link);
352 document.getElementById(theme).removeAttribute('disabled');
355 export function objectFlip(obj: any) {
357 Object.keys(obj).forEach(key => {
363 export function pictshareAvatarThumbnail(src: string): string {
364 // sample url: http://localhost:8535/pictshare/gs7xuu.jpg
365 let split = src.split('pictshare');
366 let out = `${split[0]}pictshare/96x96${split[1]}`;
370 export function showAvatars(): boolean {
372 (UserService.Instance.user && UserService.Instance.user.show_avatars) ||
373 !UserService.Instance.user
377 /// Converts to image thumbnail (only supports pictshare currently)
378 export function imageThumbnailer(url: string): string {
379 let split = url.split('pictshare');
380 if (split.length > 1) {
381 let out = `${split[0]}pictshare/140x140${split[1]}`;
388 export function isCommentType(item: Comment | PrivateMessage): item is Comment {
389 return (item as Comment).community_id !== undefined;
392 export function toast(text: string, background: string = 'success') {
393 let backgroundColor = `var(--${background})`;
396 backgroundColor: backgroundColor,
402 export function setupTribute(): Tribute {
408 menuItemTemplate: (item: any) => {
409 let emoji = `:${item.original.key}:`;
410 return `${item.original.val} ${emoji}`;
412 selectTemplate: (item: any) => {
413 return `:${item.original.key}:`;
415 values: Object.entries(emojiShortName).map(e => {
416 return { key: e[1], val: e[0] };
419 autocompleteMode: true,
420 menuItemLimit: mentionDropdownFetchLimit,
425 selectTemplate: (item: any) => {
426 return `[/u/${item.original.key}](/u/${item.original.key})`;
428 values: (text: string, cb: any) => {
429 userSearch(text, (users: any) => cb(users));
432 autocompleteMode: true,
433 menuItemLimit: mentionDropdownFetchLimit,
439 selectTemplate: (item: any) => {
440 return `[/c/${item.original.key}](/c/${item.original.key})`;
442 values: (text: string, cb: any) => {
443 communitySearch(text, (communities: any) => cb(communities));
446 autocompleteMode: true,
447 menuItemLimit: mentionDropdownFetchLimit,
453 function userSearch(text: string, cb: any) {
455 let form: SearchForm = {
457 type_: SearchType[SearchType.Users],
458 sort: SortType[SortType.TopAll],
460 limit: mentionDropdownFetchLimit,
463 WebSocketService.Instance.search(form);
465 this.userSub = WebSocketService.Instance.subject.subscribe(
467 let res = wsJsonToRes(msg);
468 if (res.op == UserOperation.Search) {
469 let data = res.data as SearchResponse;
470 let users = data.users.map(u => {
471 return { key: u.name };
474 this.userSub.unsubscribe();
477 err => console.error(err),
478 () => console.log('complete')
485 function communitySearch(text: string, cb: any) {
487 let form: SearchForm = {
489 type_: SearchType[SearchType.Communities],
490 sort: SortType[SortType.TopAll],
492 limit: mentionDropdownFetchLimit,
495 WebSocketService.Instance.search(form);
497 this.communitySub = WebSocketService.Instance.subject.subscribe(
499 let res = wsJsonToRes(msg);
500 if (res.op == UserOperation.Search) {
501 let data = res.data as SearchResponse;
502 let communities = data.communities.map(u => {
503 return { key: u.name };
506 this.communitySub.unsubscribe();
509 err => console.error(err),
510 () => console.log('complete')