Extra lints (#192)

* Updating deps, fixing lints.

* Downgrading broken husky.

* Trying to upgrade husky to v5

* Trying a bad lint.

* Trying a bad lint 2.

* Trying a bad lint 3.

* Adding prettier.
This commit is contained in:
Dessalines 2021-02-21 21:24:09 -05:00 committed by GitHub
parent 220bf9e669
commit ee77f700b3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
19 changed files with 588 additions and 1343 deletions

View file

@ -4,11 +4,11 @@
"browser": true "browser": true
}, },
"plugins": [ "plugins": [
"jane" "@typescript-eslint"
], ],
"extends": [ "extends": [
"plugin:jane/recommended", "eslint:recommended",
"plugin:jane/typescript" "plugin:@typescript-eslint/recommended"
], ],
"parser": "@typescript-eslint/parser", "parser": "@typescript-eslint/parser",
"parserOptions": { "parserOptions": {
@ -16,14 +16,8 @@
"warnOnUnsupportedTypeScriptVersion": false "warnOnUnsupportedTypeScriptVersion": false
}, },
"rules": { "rules": {
"@typescript-eslint/camelcase": 0,
"@typescript-eslint/member-delimiter-style": 0,
"@typescript-eslint/no-empty-interface": 0,
"@typescript-eslint/no-explicit-any": 0, "@typescript-eslint/no-explicit-any": 0,
"@typescript-eslint/no-this-alias": 0, "@typescript-eslint/explicit-module-boundary-types": 0,
"@typescript-eslint/no-unused-vars": 0,
"@typescript-eslint/no-use-before-define": 0,
"@typescript-eslint/no-useless-constructor": 0,
"arrow-body-style": 0, "arrow-body-style": 0,
"curly": 0, "curly": 0,
"eol-last": 0, "eol-last": 0,

1
.husky/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
_

4
.husky/pre-commit Executable file
View file

@ -0,0 +1,4 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
yarn lint-staged

View file

@ -1,4 +1,4 @@
module.exports = Object.assign(require('eslint-plugin-jane/prettier-ts'), { module.exports = Object.assign(require("eslint-plugin-prettier"), {
arrowParens: 'avoid', arrowParens: "avoid",
semi: true, semi: true,
}); });

View file

@ -15,19 +15,19 @@
}, },
"repository": "https://github.com/LemmyNet/lemmy-ui", "repository": "https://github.com/LemmyNet/lemmy-ui",
"dependencies": { "dependencies": {
"@typescript-eslint/parser": "^4.14.2", "@typescript-eslint/parser": "^4.15.1",
"autosize": "^4.0.2", "autosize": "^4.0.2",
"choices.js": "^9.0.1", "choices.js": "^9.0.1",
"emoji-short-name": "^1.0.0", "emoji-short-name": "^1.0.0",
"express": "~4.17.1", "express": "~4.17.1",
"i18next": "^19.8.7", "i18next": "^19.8.9",
"inferno": "^7.4.7", "inferno": "^7.4.8",
"inferno-create-element": "^7.4.7", "inferno-create-element": "^7.4.8",
"inferno-helmet": "^5.2.1", "inferno-helmet": "^5.2.1",
"inferno-hydrate": "^7.4.7", "inferno-hydrate": "^7.4.8",
"inferno-i18next": "github:nimbusec-oss/inferno-i18next#semver:^7.4.2", "inferno-i18next": "github:nimbusec-oss/inferno-i18next#semver:^7.4.2",
"inferno-router": "^7.4.7", "inferno-router": "^7.4.8",
"inferno-server": "^7.4.7", "inferno-server": "^7.4.8",
"isomorphic-cookie": "^1.2.4", "isomorphic-cookie": "^1.2.4",
"jwt-decode": "^3.1.2", "jwt-decode": "^3.1.2",
"markdown-it": "^12.0.4", "markdown-it": "^12.0.4",
@ -45,17 +45,18 @@
"ws": "^7.4.3" "ws": "^7.4.3"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.12.13", "@babel/core": "^7.12.17",
"@babel/plugin-transform-runtime": "^7.12.15", "@babel/plugin-transform-runtime": "^7.12.17",
"@babel/plugin-transform-typescript": "^7.12.13", "@babel/plugin-transform-typescript": "^7.12.17",
"@babel/preset-env": "7.12.13", "@babel/preset-env": "7.12.17",
"@babel/preset-typescript": "^7.12.13", "@babel/preset-typescript": "^7.12.17",
"@babel/runtime": "^7.12.13", "@babel/runtime": "^7.12.18",
"@types/autosize": "^3.0.6", "@types/autosize": "^3.0.6",
"@types/express": "^4.17.11", "@types/express": "^4.17.11",
"@types/node": "^14.14.25", "@types/node": "^14.14.31",
"@types/node-fetch": "^2.5.8", "@types/node-fetch": "^2.5.8",
"@types/serialize-javascript": "^5.0.0", "@types/serialize-javascript": "^5.0.0",
"@typescript-eslint/eslint-plugin": "^4.15.1",
"babel-loader": "^8.2.2", "babel-loader": "^8.2.2",
"babel-plugin-inferno": "^6", "babel-plugin-inferno": "^6",
"bootstrap": "^4.6.0", "bootstrap": "^4.6.0",
@ -63,23 +64,23 @@
"clean-webpack-plugin": "^3.0.0", "clean-webpack-plugin": "^3.0.0",
"copy-webpack-plugin": "^7.0.0", "copy-webpack-plugin": "^7.0.0",
"css-loader": "^5.0.2", "css-loader": "^5.0.2",
"eslint": "^7.19.0", "eslint": "^7.20.0",
"eslint-plugin-jane": "^9.0.6", "eslint-plugin-prettier": "^3.3.1",
"husky": "^4.3.8", "husky": "^5.1.0",
"lemmy-js-client": "0.9.9", "lemmy-js-client": "0.9.9",
"lint-staged": "^10.5.4", "lint-staged": "^10.5.4",
"mini-css-extract-plugin": "^1.3.6", "mini-css-extract-plugin": "^1.3.8",
"node-fetch": "^2.6.1", "node-fetch": "^2.6.1",
"node-sass": "^5.0.0", "node-sass": "^5.0.0",
"prettier": "^2.2.1", "prettier": "^2.2.1",
"rimraf": "^3.0.2", "rimraf": "^3.0.2",
"run-node-webpack-plugin": "^1.3.0", "run-node-webpack-plugin": "^1.3.0",
"sass-loader": "^11.0.0", "sass-loader": "^11.0.1",
"sortpack": "^2.2.0", "sortpack": "^2.2.0",
"style-loader": "^2.0.0", "style-loader": "^2.0.0",
"terser": "^5.6.0-beta", "terser": "^5.6.0",
"typescript": "^4.1.3", "typescript": "^4.1.5",
"webpack": "5.21.2", "webpack": "5.23.0",
"webpack-cli": "^4.5.0", "webpack-cli": "^4.5.0",
"webpack-dev-server": "3.11.2", "webpack-dev-server": "3.11.2",
"webpack-node-externals": "^2.5.2" "webpack-node-externals": "^2.5.2"
@ -88,11 +89,6 @@
"node": ">=8.9.0" "node": ">=8.9.0"
}, },
"engineStrict": true, "engineStrict": true,
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": { "lint-staged": {
"*.{ts,tsx,js}": [ "*.{ts,tsx,js}": [
"prettier --write", "prettier --write",

View file

@ -66,7 +66,7 @@ server.get('/*', async (req, res) => {
let acceptLang = req.headers['accept-language'] let acceptLang = req.headers['accept-language']
? req.headers['accept-language'].split(',')[0] ? req.headers['accept-language'].split(',')[0]
: 'en'; : 'en';
let lang = !!site.my_user let lang = site.my_user
? site.my_user.lang == 'browser' ? site.my_user.lang == 'browser'
? acceptLang ? acceptLang
: 'en' : 'en'

View file

@ -2,19 +2,19 @@ import { register } from 'register-service-worker';
register('/service-worker.js', { register('/service-worker.js', {
registrationOptions: { scope: './' }, registrationOptions: { scope: './' },
ready(_registration) { ready() {
console.log('Service worker is active.'); console.log('Service worker is active.');
}, },
registered(_registration) { registered() {
console.log('Service worker has been registered.'); console.log('Service worker has been registered.');
}, },
cached(_registration) { cached() {
console.log('Content has been cached for offline use.'); console.log('Content has been cached for offline use.');
}, },
updatefound(_registration) { updatefound() {
console.log('New content is downloading.'); console.log('New content is downloading.');
}, },
updated(_registration) { updated() {
console.log('New content is available; please refresh.'); console.log('New content is available; please refresh.');
}, },
offline() { offline() {

View file

@ -218,7 +218,6 @@ export class AdminSettings extends Component<any, AdminSettingsState> {
this.state.loading = false; this.state.loading = false;
this.setState(this.state); this.setState(this.state);
return; return;
} else if (msg.reconnect) {
} else if (op == UserOperation.EditSite) { } else if (op == UserOperation.EditSite) {
let data = wsJsonToRes<SiteResponse>(msg).data; let data = wsJsonToRes<SiteResponse>(msg).data;
this.state.siteRes.site_view = data.site_view; this.state.siteRes.site_view = data.site_view;

View file

@ -3,8 +3,6 @@ import { CommentNode as CommentNodeI } from '../interfaces';
import { CommunityModeratorView, UserViewSafe } from 'lemmy-js-client'; import { CommunityModeratorView, UserViewSafe } from 'lemmy-js-client';
import { CommentNode } from './comment-node'; import { CommentNode } from './comment-node';
interface CommentNodesState {}
interface CommentNodesProps { interface CommentNodesProps {
nodes: CommentNodeI[]; nodes: CommentNodeI[];
moderators?: CommunityModeratorView[]; moderators?: CommunityModeratorView[];
@ -22,7 +20,7 @@ interface CommentNodesProps {
export class CommentNodes extends Component< export class CommentNodes extends Component<
CommentNodesProps, CommentNodesProps,
CommentNodesState any
> { > {
constructor(props: any, context: any) { constructor(props: any, context: any) {
super(props, context); super(props, context);

View file

@ -26,8 +26,6 @@ import {
import { i18n } from '../i18next'; import { i18n } from '../i18next';
import { InitialFetchRequest } from 'shared/interfaces'; import { InitialFetchRequest } from 'shared/interfaces';
interface CreatePrivateMessageProps {}
interface CreatePrivateMessageState { interface CreatePrivateMessageState {
site_view: SiteView; site_view: SiteView;
recipient: UserViewSafe; recipient: UserViewSafe;
@ -36,7 +34,7 @@ interface CreatePrivateMessageState {
} }
export class CreatePrivateMessage extends Component< export class CreatePrivateMessage extends Component<
CreatePrivateMessageProps, any,
CreatePrivateMessageState CreatePrivateMessageState
> { > {
private isoData = setIsoData(this.context); private isoData = setIsoData(this.context);

View file

@ -8,9 +8,7 @@ interface FooterProps {
site: GetSiteResponse; site: GetSiteResponse;
} }
interface FooterState {} export class Footer extends Component<FooterProps, any> {
export class Footer extends Component<FooterProps, FooterState> {
constructor(props: any, context: any) { constructor(props: any, context: any) {
super(props, context); super(props, context);
} }

View file

@ -426,7 +426,7 @@ export class MarkdownTextArea extends Component<
simpleSurroundBeforeAfter( simpleSurroundBeforeAfter(
beforeChars: string, beforeChars: string,
afterChars: string, afterChars: string,
emptyChars: string = '___' emptyChars = '___'
) { ) {
if (!this.state.content) { if (!this.state.content) {
this.state.content = ''; this.state.content = '';

View file

@ -211,7 +211,7 @@ export class Modlog extends Component<any, ModlogState> {
renderModlogType(i: ModlogType) { renderModlogType(i: ModlogType) {
switch (i.type_) { switch (i.type_) {
case ModlogEnum.ModRemovePost: case ModlogEnum.ModRemovePost: {
let mrpv = i.view as ModRemovePostView; let mrpv = i.view as ModRemovePostView;
return [ return [
mrpv.mod_remove_post.removed ? 'Removed ' : 'Restored ', mrpv.mod_remove_post.removed ? 'Removed ' : 'Restored ',
@ -221,7 +221,8 @@ export class Modlog extends Component<any, ModlogState> {
mrpv.mod_remove_post.reason && mrpv.mod_remove_post.reason &&
` reason: ${mrpv.mod_remove_post.reason}`, ` reason: ${mrpv.mod_remove_post.reason}`,
]; ];
case ModlogEnum.ModLockPost: }
case ModlogEnum.ModLockPost: {
let mlpv = i.view as ModLockPostView; let mlpv = i.view as ModLockPostView;
return [ return [
mlpv.mod_lock_post.locked ? 'Locked ' : 'Unlocked ', mlpv.mod_lock_post.locked ? 'Locked ' : 'Unlocked ',
@ -229,7 +230,8 @@ export class Modlog extends Component<any, ModlogState> {
Post <Link to={`/post/${mlpv.post.id}`}>{mlpv.post.name}</Link> Post <Link to={`/post/${mlpv.post.id}`}>{mlpv.post.name}</Link>
</span>, </span>,
]; ];
case ModlogEnum.ModStickyPost: }
case ModlogEnum.ModStickyPost: {
let mspv = i.view as ModStickyPostView; let mspv = i.view as ModStickyPostView;
return [ return [
mspv.mod_sticky_post.stickied ? 'Stickied ' : 'Unstickied ', mspv.mod_sticky_post.stickied ? 'Stickied ' : 'Unstickied ',
@ -237,7 +239,8 @@ export class Modlog extends Component<any, ModlogState> {
Post <Link to={`/post/${mspv.post.id}`}>{mspv.post.name}</Link> Post <Link to={`/post/${mspv.post.id}`}>{mspv.post.name}</Link>
</span>, </span>,
]; ];
case ModlogEnum.ModRemoveComment: }
case ModlogEnum.ModRemoveComment: {
let mrc = i.view as ModRemoveCommentView; let mrc = i.view as ModRemoveCommentView;
return [ return [
mrc.mod_remove_comment.removed ? 'Removed ' : 'Restored ', mrc.mod_remove_comment.removed ? 'Removed ' : 'Restored ',
@ -254,7 +257,8 @@ export class Modlog extends Component<any, ModlogState> {
mrc.mod_remove_comment.reason && mrc.mod_remove_comment.reason &&
` reason: ${mrc.mod_remove_comment.reason}`, ` reason: ${mrc.mod_remove_comment.reason}`,
]; ];
case ModlogEnum.ModRemoveCommunity: }
case ModlogEnum.ModRemoveCommunity: {
let mrco = i.view as ModRemoveCommunityView; let mrco = i.view as ModRemoveCommunityView;
return [ return [
mrco.mod_remove_community.removed ? 'Removed ' : 'Restored ', mrco.mod_remove_community.removed ? 'Removed ' : 'Restored ',
@ -268,7 +272,8 @@ export class Modlog extends Component<any, ModlogState> {
.utc(mrco.mod_remove_community.expires) .utc(mrco.mod_remove_community.expires)
.fromNow()}`, .fromNow()}`,
]; ];
case ModlogEnum.ModBanFromCommunity: }
case ModlogEnum.ModBanFromCommunity: {
let mbfc = i.view as ModBanFromCommunityView; let mbfc = i.view as ModBanFromCommunityView;
return [ return [
<span> <span>
@ -292,7 +297,8 @@ export class Modlog extends Component<any, ModlogState> {
.fromNow()}`} .fromNow()}`}
</div>, </div>,
]; ];
case ModlogEnum.ModAddCommunity: }
case ModlogEnum.ModAddCommunity: {
let mac = i.view as ModAddCommunityView; let mac = i.view as ModAddCommunityView;
return [ return [
<span> <span>
@ -306,7 +312,8 @@ export class Modlog extends Component<any, ModlogState> {
<CommunityLink community={mac.community} /> <CommunityLink community={mac.community} />
</span>, </span>,
]; ];
case ModlogEnum.ModBan: }
case ModlogEnum.ModBan: {
let mb = i.view as ModBanView; let mb = i.view as ModBanView;
return [ return [
<span>{mb.mod_ban.banned ? 'Banned ' : 'Unbanned '} </span>, <span>{mb.mod_ban.banned ? 'Banned ' : 'Unbanned '} </span>,
@ -319,7 +326,8 @@ export class Modlog extends Component<any, ModlogState> {
` expires: ${moment.utc(mb.mod_ban.expires).fromNow()}`} ` expires: ${moment.utc(mb.mod_ban.expires).fromNow()}`}
</div>, </div>,
]; ];
case ModlogEnum.ModAdd: }
case ModlogEnum.ModAdd: {
let ma = i.view as ModAddView; let ma = i.view as ModAddView;
return [ return [
<span>{ma.mod_add.removed ? 'Removed ' : 'Appointed '} </span>, <span>{ma.mod_add.removed ? 'Removed ' : 'Appointed '} </span>,
@ -328,6 +336,7 @@ export class Modlog extends Component<any, ModlogState> {
</span>, </span>,
<span> as an admin </span>, <span> as an admin </span>,
]; ];
}
default: default:
return <div />; return <div />;
} }

View file

@ -457,7 +457,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
); );
} }
commentsLine(mobile: boolean = false) { commentsLine(mobile = false) {
let post_view = this.props.post_view; let post_view = this.props.post_view;
return ( return (
<div class="d-flex justify-content-between justify-content-lg-start flex-wrap text-muted font-weight-bold mb-1"> <div class="d-flex justify-content-between justify-content-lg-start flex-wrap text-muted font-weight-bold mb-1">
@ -596,7 +596,7 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
); );
} }
postActions(mobile: boolean = false) { postActions(mobile = false) {
let post_view = this.props.post_view; let post_view = this.props.post_view;
return ( return (
UserService.Instance.user && ( UserService.Instance.user && (

View file

@ -176,7 +176,7 @@ export class Post extends Component<any, PostState> {
autosize(document.querySelectorAll('textarea')); autosize(document.querySelectorAll('textarea'));
} }
componentDidUpdate(_lastProps: any, lastState: PostState, _snapshot: any) { componentDidUpdate(_lastProps: any, lastState: PostState) {
if ( if (
this.state.commentId && this.state.commentId &&
!this.state.scrolled && !this.state.scrolled &&

View file

@ -24,8 +24,6 @@ interface UserDetailsProps {
onPageChange(page: number): number | any; onPageChange(page: number): number | any;
} }
interface UserDetailsState {}
enum ItemEnum { enum ItemEnum {
Comment, Comment,
Post, Post,
@ -38,7 +36,7 @@ type ItemType = {
score: number; score: number;
}; };
export class UserDetails extends Component<UserDetailsProps, UserDetailsState> { export class UserDetails extends Component<UserDetailsProps, any> {
constructor(props: any, context: any) { constructor(props: any, context: any) {
super(props, context); super(props, context);
} }
@ -81,7 +79,7 @@ export class UserDetails extends Component<UserDetailsProps, UserDetailsState> {
renderItemType(i: ItemType) { renderItemType(i: ItemType) {
switch (i.type_) { switch (i.type_) {
case ItemEnum.Comment: case ItemEnum.Comment: {
let c = i.view as CommentView; let c = i.view as CommentView;
return ( return (
<CommentNodes <CommentNodes
@ -95,7 +93,8 @@ export class UserDetails extends Component<UserDetailsProps, UserDetailsState> {
enableDownvotes={this.props.enableDownvotes} enableDownvotes={this.props.enableDownvotes}
/> />
); );
case ItemEnum.Post: }
case ItemEnum.Post: {
let p = i.view as PostView; let p = i.view as PostView;
return ( return (
<PostListing <PostListing
@ -107,6 +106,7 @@ export class UserDetails extends Component<UserDetailsProps, UserDetailsState> {
enableNsfw={this.props.enableNsfw} enableNsfw={this.props.enableNsfw}
/> />
); );
}
default: default:
return <div />; return <div />;
} }

View file

@ -247,7 +247,7 @@ export class User extends Component<any, UserState> {
}; };
} }
componentDidUpdate(lastProps: any, _lastState: UserState, _snapshot: any) { componentDidUpdate(lastProps: any) {
// Necessary if you are on a post and you click another post (same route) // Necessary if you are on a post and you click another post (same route)
if ( if (
lastProps.location.pathname.split('/')[2] !== lastProps.location.pathname.split('/')[2] !==

View file

@ -1,33 +1,33 @@
import 'moment/locale/es'; import "moment/locale/es";
import 'moment/locale/el'; import "moment/locale/el";
import 'moment/locale/eu'; import "moment/locale/eu";
import 'moment/locale/eo'; import "moment/locale/eo";
import 'moment/locale/de'; import "moment/locale/de";
import 'moment/locale/zh-cn'; import "moment/locale/zh-cn";
import 'moment/locale/fr'; import "moment/locale/fr";
import 'moment/locale/sv'; import "moment/locale/sv";
import 'moment/locale/ru'; import "moment/locale/ru";
import 'moment/locale/nl'; import "moment/locale/nl";
import 'moment/locale/it'; import "moment/locale/it";
import 'moment/locale/fi'; import "moment/locale/fi";
import 'moment/locale/ca'; import "moment/locale/ca";
import 'moment/locale/fa'; import "moment/locale/fa";
import 'moment/locale/pl'; import "moment/locale/pl";
import 'moment/locale/pt-br'; import "moment/locale/pt-br";
import 'moment/locale/ja'; import "moment/locale/ja";
import 'moment/locale/ka'; import "moment/locale/ka";
import 'moment/locale/hi'; import "moment/locale/hi";
import 'moment/locale/gl'; import "moment/locale/gl";
import 'moment/locale/tr'; import "moment/locale/tr";
import 'moment/locale/hu'; import "moment/locale/hu";
import 'moment/locale/uk'; import "moment/locale/uk";
import 'moment/locale/sq'; import "moment/locale/sq";
import 'moment/locale/km'; import "moment/locale/km";
import 'moment/locale/ga'; import "moment/locale/ga";
import 'moment/locale/sr'; import "moment/locale/sr";
import 'moment/locale/ko'; import "moment/locale/ko";
import 'moment/locale/da'; import "moment/locale/da";
import 'moment/locale/hr'; import "moment/locale/hr";
import { import {
UserOperation, UserOperation,
@ -45,111 +45,111 @@ import {
LemmyWebsocket, LemmyWebsocket,
UserViewSafe, UserViewSafe,
CommunityView, CommunityView,
} from 'lemmy-js-client'; } from "lemmy-js-client";
import { import {
CommentSortType, CommentSortType,
DataType, DataType,
IsoData, IsoData,
CommentNode as CommentNodeI, CommentNode as CommentNodeI,
} from './interfaces'; } from "./interfaces";
import { UserService, WebSocketService } from './services'; import { UserService, WebSocketService } from "./services";
var Tribute: any; var Tribute: any;
if (isBrowser()) { if (isBrowser()) {
Tribute = require('tributejs'); Tribute = require("tributejs");
} }
import markdown_it from 'markdown-it'; import markdown_it from "markdown-it";
import markdown_it_sub from 'markdown-it-sub'; import markdown_it_sub from "markdown-it-sub";
import markdown_it_sup from 'markdown-it-sup'; import markdown_it_sup from "markdown-it-sup";
import markdown_it_container from 'markdown-it-container'; import markdown_it_container from "markdown-it-container";
import emojiShortName from 'emoji-short-name'; import emojiShortName from "emoji-short-name";
import Toastify from 'toastify-js'; import Toastify from "toastify-js";
import tippy from 'tippy.js'; import tippy from "tippy.js";
import moment from 'moment'; import moment from "moment";
import { Subscription } from 'rxjs'; import { Subscription } from "rxjs";
import { retryWhen, delay, take } from 'rxjs/operators'; import { retryWhen, delay, take } from "rxjs/operators";
import { i18n } from './i18next'; import { i18n } from "./i18next";
export const wsClient = new LemmyWebsocket(); export const wsClient = new LemmyWebsocket();
export const favIconUrl = '/static/assets/favicon.svg'; export const favIconUrl = "/static/assets/favicon.svg";
export const favIconPngUrl = '/static/assets/apple-touch-icon.png'; export const favIconPngUrl = "/static/assets/apple-touch-icon.png";
// TODO // TODO
// export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`; // export const defaultFavIcon = `${window.location.protocol}//${window.location.host}${favIconPngUrl}`;
export const repoUrl = 'https://github.com/LemmyNet'; export const repoUrl = "https://github.com/LemmyNet";
export const joinLemmyUrl = 'https://join.lemmy.ml'; export const joinLemmyUrl = "https://join.lemmy.ml";
export const supportLemmyUrl = 'https://join.lemmy.ml/sponsors'; export const supportLemmyUrl = "https://join.lemmy.ml/sponsors";
export const docsUrl = 'https://join.lemmy.ml/docs/en/index.html'; export const docsUrl = "https://join.lemmy.ml/docs/en/index.html";
export const helpGuideUrl = 'https://join.lemmy.ml/docs/en/about/guide.html'; // TODO find a way to redirect to the non-en folder export const helpGuideUrl = "https://join.lemmy.ml/docs/en/about/guide.html"; // TODO find a way to redirect to the non-en folder
export const markdownHelpUrl = `${helpGuideUrl}#markdown-guide`; export const markdownHelpUrl = `${helpGuideUrl}#markdown-guide`;
export const sortingHelpUrl = `${helpGuideUrl}#sorting`; export const sortingHelpUrl = `${helpGuideUrl}#sorting`;
export const archiveUrl = 'https://archive.is'; export const archiveUrl = "https://archive.is";
export const elementUrl = 'https://element.io/'; export const elementUrl = "https://element.io/";
export const postRefetchSeconds: number = 60 * 1000; export const postRefetchSeconds: number = 60 * 1000;
export const fetchLimit: number = 20; export const fetchLimit = 20;
export const mentionDropdownFetchLimit = 10; export const mentionDropdownFetchLimit = 10;
export const languages = [ export const languages = [
{ code: 'ca', name: 'Català' }, { code: "ca", name: "Català" },
{ code: 'en', name: 'English' }, { code: "en", name: "English" },
{ code: 'el', name: 'Ελληνικά' }, { code: "el", name: "Ελληνικά" },
{ code: 'eu', name: 'Euskara' }, { code: "eu", name: "Euskara" },
{ code: 'eo', name: 'Esperanto' }, { code: "eo", name: "Esperanto" },
{ code: 'es', name: 'Español' }, { code: "es", name: "Español" },
{ code: 'da', name: 'Dansk' }, { code: "da", name: "Dansk" },
{ code: 'de', name: 'Deutsch' }, { code: "de", name: "Deutsch" },
{ code: 'ga', name: 'Gaeilge' }, { code: "ga", name: "Gaeilge" },
{ code: 'gl', name: 'Galego' }, { code: "gl", name: "Galego" },
{ code: 'hr', name: 'hrvatski' }, { code: "hr", name: "hrvatski" },
{ code: 'hu', name: 'Magyar Nyelv' }, { code: "hu", name: "Magyar Nyelv" },
{ code: 'ka', name: 'ქართული ენა' }, { code: "ka", name: "ქართული ენა" },
{ code: 'ko', name: '한국어' }, { code: "ko", name: "한국어" },
{ code: 'km', name: 'ភាសាខ្មែរ' }, { code: "km", name: "ភាសាខ្មែរ" },
{ code: 'hi', name: 'मानक हिन्दी' }, { code: "hi", name: "मानक हिन्दी" },
{ code: 'fa', name: 'فارسی' }, { code: "fa", name: "فارسی" },
{ code: 'ja', name: '日本語' }, { code: "ja", name: "日本語" },
{ code: 'oc', name: 'Occitan' }, { code: "oc", name: "Occitan" },
{ code: 'pl', name: 'Polski' }, { code: "pl", name: "Polski" },
{ code: 'pt_BR', name: 'Português Brasileiro' }, { code: "pt_BR", name: "Português Brasileiro" },
{ code: 'zh', name: '中文' }, { code: "zh", name: "中文" },
{ code: 'fi', name: 'Suomi' }, { code: "fi", name: "Suomi" },
{ code: 'fr', name: 'Français' }, { code: "fr", name: "Français" },
{ code: 'sv', name: 'Svenska' }, { code: "sv", name: "Svenska" },
{ code: 'sq', name: 'Shqip' }, { code: "sq", name: "Shqip" },
{ code: 'sr_Latn', name: 'srpski' }, { code: "sr_Latn", name: "srpski" },
{ code: 'tr', name: 'Türkçe' }, { code: "tr", name: "Türkçe" },
{ code: 'uk', name: 'Українська Mова' }, { code: "uk", name: "Українська Mова" },
{ code: 'ru', name: 'Русский' }, { code: "ru", name: "Русский" },
{ code: 'nl', name: 'Nederlands' }, { code: "nl", name: "Nederlands" },
{ code: 'it', name: 'Italiano' }, { code: "it", name: "Italiano" },
]; ];
export const themes = [ export const themes = [
'litera', "litera",
'materia', "materia",
'minty', "minty",
'solar', "solar",
'united', "united",
'cyborg', "cyborg",
'darkly', "darkly",
'journal', "journal",
'sketchy', "sketchy",
'vaporwave', "vaporwave",
'vaporwave-dark', "vaporwave-dark",
'i386', "i386",
'litely', "litely",
]; ];
const DEFAULT_ALPHABET = const DEFAULT_ALPHABET =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
function getRandomCharFromAlphabet(alphabet: string): string { function getRandomCharFromAlphabet(alphabet: string): string {
return alphabet.charAt(Math.floor(Math.random() * alphabet.length)); return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
} }
export function randomStr( export function randomStr(
idDesiredLength: number = 20, idDesiredLength = 20,
alphabet = DEFAULT_ALPHABET alphabet = DEFAULT_ALPHABET
): string { ): string {
/** /**
@ -160,7 +160,7 @@ export function randomStr(
.map(() => { .map(() => {
return getRandomCharFromAlphabet(alphabet); return getRandomCharFromAlphabet(alphabet);
}) })
.join(''); .join("");
} }
export function wsJsonToRes<ResponseType>( export function wsJsonToRes<ResponseType>(
@ -184,7 +184,7 @@ export const md = new markdown_it({
}) })
.use(markdown_it_sub) .use(markdown_it_sub)
.use(markdown_it_sup) .use(markdown_it_sup)
.use(markdown_it_container, 'spoiler', { .use(markdown_it_container, "spoiler", {
validate: function (params: any) { validate: function (params: any) {
return params.trim().match(/^spoiler\s+(.*)$/); return params.trim().match(/^spoiler\s+(.*)$/);
}, },
@ -197,7 +197,7 @@ export const md = new markdown_it({
return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`; return `<details><summary> ${md.utils.escapeHtml(m[1])} </summary>\n`;
} else { } else {
// closing tag // closing tag
return '</details>\n'; return "</details>\n";
} }
}, },
}); });
@ -216,7 +216,7 @@ export function hotRankPost(post_view: PostView): number {
export function hotRank(score: number, timeStr: string): number { export function hotRank(score: number, timeStr: string): number {
// Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity // Rank = ScaleFactor * sign(Score) * log(1 + abs(Score)) / (Time + 2)^Gravity
let date: Date = new Date(timeStr + 'Z'); // Add Z to convert from UTC date let date: Date = new Date(timeStr + "Z"); // Add Z to convert from UTC date
let now: Date = new Date(); let now: Date = new Date();
let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5; let hoursElapsed: number = (now.getTime() - date.getTime()) / 36e5;
@ -241,7 +241,7 @@ export function canMod(
user: UserSafeSettings, user: UserSafeSettings,
modIds: number[], modIds: number[],
creator_id: number, creator_id: number,
onSelf: boolean = false onSelf = false
): boolean { ): boolean {
// You can do moderator actions only on the mods added after you. // You can do moderator actions only on the mods added after you.
if (user) { if (user) {
@ -323,11 +323,7 @@ export async function getPageTitle(url: string) {
return title; return title;
} }
export function debounce( export function debounce(func: any, wait = 1000, immediate = false) {
func: any,
wait: number = 1000,
immediate: boolean = false
) {
// 'private' variable for instance // 'private' variable for instance
// The returned function will be able to reference this due to closure. // The returned function will be able to reference this due to closure.
// Each call to the returned function will share this common timer. // Each call to the returned function will share this common timer.
@ -336,8 +332,7 @@ export function debounce(
// Calling debounce returns a new anonymous function // Calling debounce returns a new anonymous function
return function () { return function () {
// reference the context and args for the setTimeout function // reference the context and args for the setTimeout function
var context = this, var args = arguments;
args = arguments;
// Should the function be called now? If immediate is true // Should the function be called now? If immediate is true
// and not already in a timeout then the answer is: Yes // and not already in a timeout then the answer is: Yes
@ -360,21 +355,21 @@ export function debounce(
// Call the original function with apply // Call the original function with apply
// apply lets you define the 'this' object as well as the arguments // apply lets you define the 'this' object as well as the arguments
// (both captured before setTimeout) // (both captured before setTimeout)
func.apply(context, args); func.apply(this, args);
} }
}, wait); }, wait);
// Immediate mode and no wait timer? Execute the function.. // Immediate mode and no wait timer? Execute the function..
if (callNow) func.apply(context, args); if (callNow) func.apply(this, args);
}; };
} }
// TODO // TODO
export function getLanguage(override?: string): string { export function getLanguage(override?: string): string {
let user = UserService.Instance.user; let user = UserService.Instance.user;
let lang = override || (user && user.lang ? user.lang : 'browser'); let lang = override || (user && user.lang ? user.lang : "browser");
if (lang == 'browser' && isBrowser()) { if (lang == "browser" && isBrowser()) {
return getBrowserLanguage(); return getBrowserLanguage();
} else { } else {
return lang; return lang;
@ -388,114 +383,114 @@ export function getBrowserLanguage(): string {
export function getMomentLanguage(): string { export function getMomentLanguage(): string {
let lang = getLanguage(); let lang = getLanguage();
if (lang.startsWith('zh')) { if (lang.startsWith("zh")) {
lang = 'zh-cn'; lang = "zh-cn";
} else if (lang.startsWith('sv')) { } else if (lang.startsWith("sv")) {
lang = 'sv'; lang = "sv";
} else if (lang.startsWith('fr')) { } else if (lang.startsWith("fr")) {
lang = 'fr'; lang = "fr";
} else if (lang.startsWith('de')) { } else if (lang.startsWith("de")) {
lang = 'de'; lang = "de";
} else if (lang.startsWith('ru')) { } else if (lang.startsWith("ru")) {
lang = 'ru'; lang = "ru";
} else if (lang.startsWith('es')) { } else if (lang.startsWith("es")) {
lang = 'es'; lang = "es";
} else if (lang.startsWith('eo')) { } else if (lang.startsWith("eo")) {
lang = 'eo'; lang = "eo";
} else if (lang.startsWith('nl')) { } else if (lang.startsWith("nl")) {
lang = 'nl'; lang = "nl";
} else if (lang.startsWith('it')) { } else if (lang.startsWith("it")) {
lang = 'it'; lang = "it";
} else if (lang.startsWith('fi')) { } else if (lang.startsWith("fi")) {
lang = 'fi'; lang = "fi";
} else if (lang.startsWith('ca')) { } else if (lang.startsWith("ca")) {
lang = 'ca'; lang = "ca";
} else if (lang.startsWith('fa')) { } else if (lang.startsWith("fa")) {
lang = 'fa'; lang = "fa";
} else if (lang.startsWith('pl')) { } else if (lang.startsWith("pl")) {
lang = 'pl'; lang = "pl";
} else if (lang.startsWith('pt')) { } else if (lang.startsWith("pt")) {
lang = 'pt-br'; lang = "pt-br";
} else if (lang.startsWith('ja')) { } else if (lang.startsWith("ja")) {
lang = 'ja'; lang = "ja";
} else if (lang.startsWith('ka')) { } else if (lang.startsWith("ka")) {
lang = 'ka'; lang = "ka";
} else if (lang.startsWith('hi')) { } else if (lang.startsWith("hi")) {
lang = 'hi'; lang = "hi";
} else if (lang.startsWith('el')) { } else if (lang.startsWith("el")) {
lang = 'el'; lang = "el";
} else if (lang.startsWith('eu')) { } else if (lang.startsWith("eu")) {
lang = 'eu'; lang = "eu";
} else if (lang.startsWith('gl')) { } else if (lang.startsWith("gl")) {
lang = 'gl'; lang = "gl";
} else if (lang.startsWith('tr')) { } else if (lang.startsWith("tr")) {
lang = 'tr'; lang = "tr";
} else if (lang.startsWith('hu')) { } else if (lang.startsWith("hu")) {
lang = 'hu'; lang = "hu";
} else if (lang.startsWith('uk')) { } else if (lang.startsWith("uk")) {
lang = 'uk'; lang = "uk";
} else if (lang.startsWith('sq')) { } else if (lang.startsWith("sq")) {
lang = 'sq'; lang = "sq";
} else if (lang.startsWith('km')) { } else if (lang.startsWith("km")) {
lang = 'km'; lang = "km";
} else if (lang.startsWith('ga')) { } else if (lang.startsWith("ga")) {
lang = 'ga'; lang = "ga";
} else if (lang.startsWith('sr')) { } else if (lang.startsWith("sr")) {
lang = 'sr'; lang = "sr";
} else if (lang.startsWith('ko')) { } else if (lang.startsWith("ko")) {
lang = 'ko'; lang = "ko";
} else if (lang.startsWith('da')) { } else if (lang.startsWith("da")) {
lang = 'da'; lang = "da";
} else if (lang.startsWith('oc')) { } else if (lang.startsWith("oc")) {
lang = 'oc'; lang = "oc";
} else if (lang.startsWith('hr')) { } else if (lang.startsWith("hr")) {
lang = 'hr'; lang = "hr";
} else { } else {
lang = 'en'; lang = "en";
} }
return lang; return lang;
} }
export function setTheme(theme: string, forceReload: boolean = false) { export function setTheme(theme: string, forceReload = false) {
if (!isBrowser()) { if (!isBrowser()) {
return; return;
} }
if (theme === 'browser' && !forceReload) { if (theme === "browser" && !forceReload) {
return; return;
} }
// This is only run on a force reload // This is only run on a force reload
if (theme == 'browser') { if (theme == "browser") {
theme = 'darkly'; theme = "darkly";
} }
// Unload all the other themes // Unload all the other themes
for (var i = 0; i < themes.length; i++) { for (var i = 0; i < themes.length; i++) {
let styleSheet = document.getElementById(themes[i]); let styleSheet = document.getElementById(themes[i]);
if (styleSheet) { if (styleSheet) {
styleSheet.setAttribute('disabled', 'disabled'); styleSheet.setAttribute("disabled", "disabled");
} }
} }
document document
.getElementById('default-light') .getElementById("default-light")
?.setAttribute('disabled', 'disabled'); ?.setAttribute("disabled", "disabled");
document.getElementById('default-dark')?.setAttribute('disabled', 'disabled'); document.getElementById("default-dark")?.setAttribute("disabled", "disabled");
// Load the theme dynamically // Load the theme dynamically
let cssLoc = `/static/assets/css/themes/${theme}.min.css`; let cssLoc = `/static/assets/css/themes/${theme}.min.css`;
loadCss(theme, cssLoc); loadCss(theme, cssLoc);
document.getElementById(theme).removeAttribute('disabled'); document.getElementById(theme).removeAttribute("disabled");
} }
export function loadCss(id: string, loc: string) { export function loadCss(id: string, loc: string) {
if (!document.getElementById(id)) { if (!document.getElementById(id)) {
var head = document.getElementsByTagName('head')[0]; var head = document.getElementsByTagName("head")[0];
var link = document.createElement('link'); var link = document.createElement("link");
link.id = id; link.id = id;
link.rel = 'stylesheet'; link.rel = "stylesheet";
link.type = 'text/css'; link.type = "text/css";
link.href = loc; link.href = loc;
link.media = 'all'; link.media = "all";
head.appendChild(link); head.appendChild(link);
} }
} }
@ -528,14 +523,14 @@ export function isCakeDay(published: string): boolean {
); );
} }
export function toast(text: string, background: string = 'success') { export function toast(text: string, background = "success") {
if (isBrowser()) { if (isBrowser()) {
let backgroundColor = `var(--${background})`; let backgroundColor = `var(--${background})`;
Toastify({ Toastify({
text: text, text: text,
backgroundColor: backgroundColor, backgroundColor: backgroundColor,
gravity: 'bottom', gravity: "bottom",
position: 'left', position: "left",
}).showToast(); }).showToast();
} }
} }
@ -550,8 +545,8 @@ export function pictrsDeleteToast(
let toast = Toastify({ let toast = Toastify({
text: clickToDeleteText, text: clickToDeleteText,
backgroundColor: backgroundColor, backgroundColor: backgroundColor,
gravity: 'top', gravity: "top",
position: 'right', position: "right",
duration: 10000, duration: 10000,
onClick: () => { onClick: () => {
if (toast) { if (toast) {
@ -574,17 +569,17 @@ interface NotifyInfo {
export function messageToastify(info: NotifyInfo, router: any) { export function messageToastify(info: NotifyInfo, router: any) {
if (isBrowser()) { if (isBrowser()) {
let htmlBody = info.body ? md.render(info.body) : ''; let htmlBody = info.body ? md.render(info.body) : "";
let backgroundColor = `var(--light)`; let backgroundColor = `var(--light)`;
let toast = Toastify({ let toast = Toastify({
text: `${htmlBody}<br />${info.name}`, text: `${htmlBody}<br />${info.name}`,
avatar: info.icon ? info.icon : null, avatar: info.icon ? info.icon : null,
backgroundColor: backgroundColor, backgroundColor: backgroundColor,
className: 'text-dark', className: "text-dark",
close: true, close: true,
gravity: 'top', gravity: "top",
position: 'right', position: "right",
duration: 5000, duration: 5000,
onClick: () => { onClick: () => {
if (toast) { if (toast) {
@ -629,7 +624,7 @@ export function notifyPrivateMessage(pmv: PrivateMessageView, router: any) {
function notify(info: NotifyInfo, router: any) { function notify(info: NotifyInfo, router: any) {
messageToastify(info, router); messageToastify(info, router);
if (Notification.permission !== 'granted') Notification.requestPermission(); if (Notification.permission !== "granted") Notification.requestPermission();
else { else {
var notification = new Notification(info.name, { var notification = new Notification(info.name, {
icon: info.icon, icon: info.icon,
@ -646,12 +641,12 @@ function notify(info: NotifyInfo, router: any) {
export function setupTribute() { export function setupTribute() {
return new Tribute({ return new Tribute({
noMatchTemplate: function () { noMatchTemplate: function () {
return ''; return "";
}, },
collection: [ collection: [
// Emojis // Emojis
{ {
trigger: ':', trigger: ":",
menuItemTemplate: (item: any) => { menuItemTemplate: (item: any) => {
let shortName = `:${item.original.key}:`; let shortName = `:${item.original.key}:`;
return `${item.original.val} ${shortName}`; return `${item.original.val} ${shortName}`;
@ -670,7 +665,7 @@ export function setupTribute() {
}, },
// Users // Users
{ {
trigger: '@', trigger: "@",
selectTemplate: (item: any) => { selectTemplate: (item: any) => {
let it: UserTribute = item.original; let it: UserTribute = item.original;
return `[${it.key}](${it.view.user.actor_id})`; return `[${it.key}](${it.view.user.actor_id})`;
@ -687,7 +682,7 @@ export function setupTribute() {
// Communities // Communities
{ {
trigger: '!', trigger: "!",
selectTemplate: (item: any) => { selectTemplate: (item: any) => {
let it: CommunityTribute = item.original; let it: CommunityTribute = item.original;
return `[${it.key}](${it.view.community.actor_id})`; return `[${it.key}](${it.view.community.actor_id})`;
@ -709,16 +704,16 @@ export function setupTribute() {
var tippyInstance: any; var tippyInstance: any;
if (isBrowser()) { if (isBrowser()) {
tippyInstance = tippy('[data-tippy-content]'); tippyInstance = tippy("[data-tippy-content]");
} }
export function setupTippy() { export function setupTippy() {
if (isBrowser()) { if (isBrowser()) {
tippyInstance.forEach((e: any) => e.destroy()); tippyInstance.forEach((e: any) => e.destroy());
tippyInstance = tippy('[data-tippy-content]', { tippyInstance = tippy("[data-tippy-content]", {
delay: [500, 0], delay: [500, 0],
// Display on "long press" // Display on "long press"
touch: ['hold', 500], touch: ["hold", 500],
}); });
} }
} }
@ -758,7 +753,7 @@ function userSearch(text: string, cb: (users: UserTribute[]) => any) {
} }
}, },
err => console.error(err), err => console.error(err),
() => console.log('complete') () => console.log("complete")
); );
} else { } else {
cb([]); cb([]);
@ -803,7 +798,7 @@ function communitySearch(
} }
}, },
err => console.error(err), err => console.error(err),
() => console.log('complete') () => console.log("complete")
); );
} else { } else {
cb([]); cb([]);
@ -1033,7 +1028,7 @@ export function buildCommentsTree(
return tree; return tree;
} }
function setDepth(node: CommentNodeI, i: number = 0) { function setDepth(node: CommentNodeI, i = 0) {
for (let child of node.children) { for (let child of node.children) {
child.depth = i; child.depth = i;
setDepth(child, i + 1); setDepth(child, i + 1);
@ -1094,16 +1089,16 @@ function hsl(num: number) {
export function previewLines( export function previewLines(
text: string, text: string,
maxChars: number = 300, maxChars = 300,
maxLines: number = 1 maxLines = 1
): string { ): string {
return ( return (
text text
.slice(0, maxChars) .slice(0, maxChars)
.split('\n') .split("\n")
// Use lines * 2 because markdown requires 2 lines // Use lines * 2 because markdown requires 2 lines
.slice(0, maxLines * 2) .slice(0, maxLines * 2)
.join('\n') + '...' .join("\n") + "..."
); );
} }
@ -1116,7 +1111,7 @@ export function validTitle(title?: string): boolean {
// Initial title is null, minimum length is taken care of by textarea's minLength={3} // Initial title is null, minimum length is taken care of by textarea's minLength={3}
if (title === null || title.length < 3) return true; if (title === null || title.length < 3) return true;
const regex = new RegExp(/.*\S.*/, 'g'); const regex = new RegExp(/.*\S.*/, "g");
return regex.test(title); return regex.test(title);
} }
@ -1135,7 +1130,7 @@ export function siteBannerCss(banner: string): string {
} }
export function isBrowser() { export function isBrowser() {
return typeof window !== 'undefined'; return typeof window !== "undefined";
} }
export function setIsoData(context: any): IsoData { export function setIsoData(context: any): IsoData {
@ -1152,7 +1147,7 @@ export function wsSubscribe(parseMessage: any): Subscription {
.subscribe( .subscribe(
msg => parseMessage(msg), msg => parseMessage(msg),
err => console.error(err), err => console.error(err),
() => console.log('complete') () => console.log("complete")
); );
} else { } else {
return null; return null;
@ -1166,35 +1161,35 @@ export function setOptionalAuth(obj: any, auth = UserService.Instance.auth) {
} }
export function authField( export function authField(
throwErr: boolean = true, throwErr = true,
auth = UserService.Instance.auth auth = UserService.Instance.auth
): string { ): string {
if (auth == null && throwErr) { if (auth == null && throwErr) {
toast(i18n.t('not_logged_in'), 'danger'); toast(i18n.t("not_logged_in"), "danger");
throw 'Not logged in'; throw "Not logged in";
} else { } else {
return auth; return auth;
} }
} }
moment.updateLocale('en', { moment.updateLocale("en", {
relativeTime: { relativeTime: {
future: 'in %s', future: "in %s",
past: '%s ago', past: "%s ago",
s: '<1m', s: "<1m",
ss: '%ds', ss: "%ds",
m: '1m', m: "1m",
mm: '%dm', mm: "%dm",
h: '1h', h: "1h",
hh: '%dh', hh: "%dh",
d: '1d', d: "1d",
dd: '%dd', dd: "%dd",
w: '1w', w: "1w",
ww: '%dw', ww: "%dw",
M: '1M', M: "1M",
MM: '%dM', MM: "%dM",
y: '1Y', y: "1Y",
yy: '%dY', yy: "%dY",
}, },
}); });

1307
yarn.lock

File diff suppressed because it is too large Load diff