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';
18 } from './interfaces';
19 import * as markdown_it from 'markdown-it';
20 import * as markdownitEmoji from 'markdown-it-emoji/light';
21 import * as markdown_it_container from 'markdown-it-container';
22 import * as twemoji from 'twemoji';
23 import * as emojiShortName from 'emoji-short-name';
25 export const repoUrl = 'https://github.com/dessalines/lemmy';
26 export const markdownHelpUrl = 'https://commonmark.org/help/';
28 export const postRefetchSeconds: number = 60 * 1000;
29 export const fetchLimit: number = 20;
30 export const mentionDropdownFetchLimit = 6;
32 export function randomStr() {
35 .replace(/[^a-z]+/g, '')
39 export function msgOp(msg: any): UserOperation {
40 let opStr: string = msg.op;
41 return UserOperation[opStr];
44 export const md = new markdown_it({
49 .use(markdown_it_container, 'spoiler', {
50 validate: function(params: any) {
51 return params.trim().match(/^spoiler\s+(.*)$/);
54 render: function(tokens: any, idx: any) {
55 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);
57 if (tokens[idx].nesting === 1) {
60 '<details><summary>' + md.utils.escapeHtml(m[1]) + '</summary>\n'
64 return '</details>\n';
68 .use(markdownitEmoji, {
69 defs: objectFlip(emojiShortName),
72 md.renderer.rules.emoji = function(token, idx) {
73 return twemoji.parse(token[idx].content);
76 export function hotRank(comment: Comment): number {
77 // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
79 let date: Date = new Date(comment.published + 'Z'); // Add Z to convert from UTC date
80 let now: Date = new Date();
81 let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
84 (10000 * Math.log10(Math.max(1, 3 + comment.score))) /
85 Math.pow(hoursElapsed + 2, 1.8);
87 // console.log(`Comment: ${comment.content}\nRank: ${rank}\nScore: ${comment.score}\nHours: ${hoursElapsed}`);
92 export function mdToHtml(text: string) {
93 return { __html: md.render(text) };
96 export function getUnixTime(text: string): number {
97 return text ? new Date(text).getTime() / 1000 : undefined;
100 export function addTypeInfo<T>(
103 ): Array<{ type_: string; data: T }> {
104 return arr.map(e => {
105 return { type_: name, data: e };
109 export function canMod(
111 modIds: Array<number>,
113 onSelf: boolean = false
115 // You can do moderator actions only on the mods added after you.
117 let yourIndex = modIds.findIndex(id => id == user.id);
118 if (yourIndex == -1) {
121 // onSelf +1 on mod actions not for yourself, IE ban, remove, etc
122 modIds = modIds.slice(0, yourIndex + (onSelf ? 0 : 1));
123 return !modIds.includes(creator_id);
130 export function isMod(modIds: Array<number>, creator_id: number): boolean {
131 return modIds.includes(creator_id);
134 var imageRegex = new RegExp(
135 `(http)?s?:?(\/\/[^"']*\.(?:png|jpg|jpeg|gif|png|svg))`
137 var videoRegex = new RegExp(`(http)?s?:?(\/\/[^"']*\.(?:mp4))`);
139 export function isImage(url: string) {
140 return imageRegex.test(url);
143 export function isVideo(url: string) {
144 return videoRegex.test(url);
147 export function validURL(str: string) {
149 return !!new URL(str);
155 export function capitalizeFirstLetter(str: string): string {
156 return str.charAt(0).toUpperCase() + str.slice(1);
159 export function routeSortTypeToEnum(sort: string): SortType {
162 } else if (sort == 'hot') {
164 } else if (sort == 'topday') {
165 return SortType.TopDay;
166 } else if (sort == 'topweek') {
167 return SortType.TopWeek;
168 } else if (sort == 'topmonth') {
169 return SortType.TopMonth;
170 } else if (sort == 'topyear') {
171 return SortType.TopYear;
172 } else if (sort == 'topall') {
173 return SortType.TopAll;
177 export function routeListingTypeToEnum(type: string): ListingType {
178 return ListingType[capitalizeFirstLetter(type)];
181 export function routeSearchTypeToEnum(type: string): SearchType {
182 return SearchType[capitalizeFirstLetter(type)];
185 export async function getPageTitle(url: string) {
186 let res = await fetch(`https://textance.herokuapp.com/title/${url}`);
187 let data = await res.text();
191 export function debounce(
194 immediate: boolean = false
196 // 'private' variable for instance
197 // The returned function will be able to reference this due to closure.
198 // Each call to the returned function will share this common timer.
201 // Calling debounce returns a new anonymous function
203 // reference the context and args for the setTimeout function
207 // Should the function be called now? If immediate is true
208 // and not already in a timeout then the answer is: Yes
209 var callNow = immediate && !timeout;
211 // This is the basic debounce behaviour where you can call this
212 // function several times, but it will only execute once
213 // [before or after imposing a delay].
214 // Each time the returned function is called, the timer starts over.
215 clearTimeout(timeout);
217 // Set the new timeout
218 timeout = setTimeout(function() {
219 // Inside the timeout function, clear the timeout variable
220 // which will let the next execution run when in 'immediate' mode
223 // Check if the function already ran with the immediate flag
225 // Call the original function with apply
226 // apply lets you define the 'this' object as well as the arguments
227 // (both captured before setTimeout)
228 func.apply(context, args);
232 // Immediate mode and no wait timer? Execute the function..
233 if (callNow) func.apply(context, args);
237 export function getLanguage(): string {
238 return navigator.language || navigator.userLanguage;
241 export function objectFlip(obj: any) {
243 Object.keys(obj).forEach(key => {
249 export function getMomentLanguage(): string {
250 let lang = getLanguage();
251 if (lang.startsWith('zh')) {
253 } else if (lang.startsWith('sv')) {
255 } else if (lang.startsWith('fr')) {
257 } else if (lang.startsWith('de')) {
259 } else if (lang.startsWith('ru')) {
261 } else if (lang.startsWith('es')) {
263 } else if (lang.startsWith('eo')) {
265 } else if (lang.startsWith('nl')) {
267 } else if (lang.startsWith('it')) {
275 export const themes = [
287 export function setTheme(theme: string = 'darkly') {
288 for (var i = 0; i < themes.length; i++) {
289 let styleSheet = document.getElementById(themes[i]);
290 if (themes[i] == theme) {
291 styleSheet.removeAttribute('disabled');
293 styleSheet.setAttribute('disabled', 'disabled');