Merge pull request #4815 from matrix-org/joriks/eslint-config

Use new eslint dependency and remove tslint
pull/21833/head
Jorik Schellekens 2020-07-21 16:29:55 +01:00 committed by GitHub
commit 8ac2c7219f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
36 changed files with 763 additions and 319 deletions

View File

@ -11,111 +11,36 @@ const path = require('path');
const matrixJsSdkPath = path.join(path.dirname(require.resolve('matrix-js-sdk')), '..');
module.exports = {
extends: ["matrix-org", "matrix-org/react-legacy"],
parser: "babel-eslint",
extends: [matrixJsSdkPath + "/.eslintrc.js"],
plugins: [
"react",
"react-hooks",
"flowtype",
"babel"
],
env: {
browser: true,
node: true,
},
globals: {
LANGUAGES_FILE: "readonly",
},
env: {
es6: true,
},
parserOptions: {
ecmaFeatures: {
jsx: true,
legacyDecorators: true,
}
},
rules: {
// eslint's built in no-invalid-this rule breaks with class properties
"no-invalid-this": "off",
// so we replace it with a version that is class property aware
"babel/no-invalid-this": "error",
// We appear to follow this most of the time, so let's enforce it instead
// of occasionally following it (or catching it in review)
"keyword-spacing": "error",
/** react **/
// This just uses the react plugin to help eslint known when
// variables have been used in JSX
"react/jsx-uses-vars": "error",
// Don't mark React as unused if we're using JSX
"react/jsx-uses-react": "error",
// bind or arrow function in props causes performance issues
// (but we currently use them in some places)
// It's disabled here, but we should using it sparingly.
"react/jsx-no-bind": "off",
"react/jsx-key": ["error"],
// Components in JSX should always be defined.
"react/jsx-no-undef": "error",
// Assert no spacing in JSX curly brackets
// <Element prop={ consideredError} prop={notConsideredError} />
//
// https://github.com/yannickcr/eslint-plugin-react/blob/HEAD/docs/rules/jsx-curly-spacing.md
//
// Disabled for now - if anything we'd like to *enforce* spacing in JSX
// curly brackets for legibility, but in practice it's not clear that the
// consistency particularly improves legibility here. --Matthew
//
// "react/jsx-curly-spacing": ["error", {"when": "never", "children": {"when": "always"}}],
// Assert spacing before self-closing JSX tags, and no spacing before or
// after the closing slash, and no spacing after the opening bracket of
// the opening tag or closing tag.
//
// https://github.com/yannickcr/eslint-plugin-react/blob/HEAD/docs/rules/jsx-tag-spacing.md
"react/jsx-tag-spacing": ["error"],
/** flowtype **/
"flowtype/require-parameter-type": ["warn", {
"excludeArrowFunctions": true,
}],
"flowtype/define-flow-type": "warn",
"flowtype/require-return-type": ["warn",
"always",
{
"annotateUndefined": "never",
"excludeArrowFunctions": true,
}
],
"flowtype/space-after-type-colon": ["warn", "always"],
"flowtype/space-before-type-colon": ["warn", "never"],
/*
* things that are errors in the js-sdk config that the current
* code does not adhere to, turned down to warn
*/
"max-len": ["warn", {
// apparently people believe the length limit shouldn't apply
// to JSX.
ignorePattern: '^\\s*<',
ignoreComments: true,
ignoreRegExpLiterals: true,
code: 120,
}],
"valid-jsdoc": ["warn"],
"new-cap": ["warn"],
"key-spacing": ["warn"],
"prefer-const": ["warn"],
// crashes currently: https://github.com/eslint/eslint/issues/6274
"generator-star-spacing": "off",
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn",
},
settings: {
flowtype: {
onlyFilesWithFlowAnnotation: true
},
// Things we do that break the ideal style
"no-constant-condition": "off",
"prefer-promise-reject-errors": "off",
"no-async-promise-executor": "off",
"quotes": "off",
"indent": "off",
},
overrides: [{
files: ["src/**/*.{ts, tsx}"],
"extends": ["matrix-org/ts"],
"rules": {
// We disable this while we're transitioning
"@typescript-eslint/no-explicit-any": "off",
// We'd rather not do this but we do
"@typescript-eslint/ban-ts-comment": "off",
"quotes": "off",
"no-extra-boolean-cast": "off",
}
}],
};

View File

@ -45,9 +45,8 @@
"start": "echo THIS IS FOR LEGACY PURPOSES ONLY. && yarn start:all",
"start:all": "concurrently --kill-others-on-fail --prefix \"{time} [{name}]\" -n build,reskindex \"yarn start:build\" \"yarn reskindex:watch\"",
"start:build": "babel src -w -s -d lib --verbose --extensions \".ts,.js\"",
"lint": "yarn lint:types && yarn lint:ts && yarn lint:js && yarn lint:style",
"lint": "yarn lint:types && yarn lint:js && yarn lint:style",
"lint:js": "eslint --max-warnings 0 --ignore-path .eslintignore.errorfiles src test",
"lint:ts": "tslint --project ./tsconfig.json -t stylish",
"lint:types": "tsc --noEmit --jsx react",
"lint:style": "stylelint 'res/css/**/*.scss'",
"test": "jest",
@ -132,14 +131,17 @@
"@types/react-transition-group": "^4.4.0",
"@types/sanitize-html": "^1.23.3",
"@types/zxcvbn": "^4.4.0",
"@typescript-eslint/eslint-plugin": "^3.4.0",
"@typescript-eslint/parser": "^3.4.0",
"babel-eslint": "^10.0.3",
"babel-jest": "^24.9.0",
"chokidar": "^3.3.1",
"concurrently": "^4.0.1",
"enzyme": "^3.10.0",
"enzyme-adapter-react-16": "^1.15.1",
"eslint": "^5.12.0",
"eslint": "7.3.1",
"eslint-config-google": "^0.7.1",
"eslint-config-matrix-org": "^0.1.2",
"eslint-plugin-babel": "^5.2.1",
"eslint-plugin-flowtype": "^2.30.0",
"eslint-plugin-jest": "^23.0.4",
@ -160,7 +162,6 @@
"stylelint": "^9.10.1",
"stylelint-config-standard": "^18.2.0",
"stylelint-scss": "^3.9.0",
"tslint": "^5.20.1",
"typescript": "^3.7.3",
"walk": "^2.3.9",
"webpack": "^4.20.2",

View File

@ -33,12 +33,12 @@ declare global {
init: () => Promise<void>;
};
mx_ContentMessages: ContentMessages;
mx_ToastStore: ToastStore;
mx_DeviceListener: DeviceListener;
mx_RebrandListener: RebrandListener;
mx_RoomListStore: RoomListStoreClass;
mx_RoomListLayoutStore: RoomListLayoutStore;
mxContentMessages: ContentMessages;
mxToastStore: ToastStore;
mxDeviceListener: DeviceListener;
mxRebrandListener: RebrandListener;
mxRoomListStore: RoomListStoreClass;
mxRoomListLayoutStore: RoomListLayoutStore;
mxPlatformPeg: PlatformPeg;
mxIntegrationManagers: typeof IntegrationManagers;
}

View File

@ -621,9 +621,9 @@ export default class ContentMessages {
}
static sharedInstance() {
if (window.mx_ContentMessages === undefined) {
window.mx_ContentMessages = new ContentMessages();
if (window.mxContentMessages === undefined) {
window.mxContentMessages = new ContentMessages();
}
return window.mx_ContentMessages;
return window.mxContentMessages;
}
}

View File

@ -17,16 +17,16 @@ limitations under the License.
import {MatrixClientPeg} from './MatrixClientPeg';
import {
hideToast as hideBulkUnverifiedSessionsToast,
showToast as showBulkUnverifiedSessionsToast
showToast as showBulkUnverifiedSessionsToast,
} from "./toasts/BulkUnverifiedSessionsToast";
import {
hideToast as hideSetupEncryptionToast,
Kind as SetupKind,
showToast as showSetupEncryptionToast
showToast as showSetupEncryptionToast,
} from "./toasts/SetupEncryptionToast";
import {
hideToast as hideUnverifiedSessionsToast,
showToast as showUnverifiedSessionsToast
showToast as showUnverifiedSessionsToast,
} from "./toasts/UnverifiedSessionToast";
import {privateShouldBeEncrypted} from "./createRoom";
@ -48,8 +48,8 @@ export default class DeviceListener {
private displayingToastsForDeviceIds = new Set<string>();
static sharedInstance() {
if (!window.mx_DeviceListener) window.mx_DeviceListener = new DeviceListener();
return window.mx_DeviceListener;
if (!window.mxDeviceListener) window.mxDeviceListener = new DeviceListener();
return window.mxDeviceListener;
}
start() {

View File

@ -67,8 +67,8 @@ export default class RebrandListener {
private nagAgainAt?: number = null;
static sharedInstance() {
if (!window.mx_RebrandListener) window.mx_RebrandListener = new RebrandListener();
return window.mx_RebrandListener;
if (!window.mxRebrandListener) window.mxRebrandListener = new RebrandListener();
return window.mxRebrandListener;
}
constructor() {

View File

@ -108,7 +108,7 @@ export default class RoomListActions {
) {
const promiseToDelete = matrixClient.deleteRoomTag(
roomId, oldTag,
).catch(function (err) {
).catch(function(err) {
const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
console.error("Failed to remove tag " + oldTag + " from room: " + err);
Modal.createTrackedDialog('Failed to remove tag from room', '', ErrorDialog, {
@ -128,7 +128,7 @@ export default class RoomListActions {
// at least be an empty object.
metaData = metaData || {};
const promiseToAdd = matrixClient.setRoomTag(roomId, newTag, metaData).catch(function (err) {
const promiseToAdd = matrixClient.setRoomTag(roomId, newTag, metaData).catch(function(err) {
const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
console.error("Failed to add tag " + newTag + " to room: " + err);
Modal.createTrackedDialog('Failed to add tag to room', '', ErrorDialog, {

View File

@ -22,7 +22,6 @@ import { AsyncActionPayload } from "../dispatcher/payloads";
import { MatrixClient } from "matrix-js-sdk/src/client";
export default class TagOrderActions {
/**
* Creates an action thunk that will do an asynchronous request to
* move a tag in TagOrderStore to destinationIx.

View File

@ -115,7 +115,7 @@ export default class QueryMatcher<T extends Object> {
const index = resultKey.indexOf(query);
if (index !== -1 && (!this._options.shouldMatchPrefix || index === 0)) {
matches.push(
...candidates.map((candidate) => ({index, ...candidate}))
...candidates.map((candidate) => ({index, ...candidate})),
);
}
}

View File

@ -704,6 +704,7 @@ export default class AppTile extends React.Component {
_onReloadWidgetClick() {
// Reload iframe in this way to avoid cross-origin restrictions
// eslint-disable-next-line no-self-assign
this._appFrame.current.src = this._appFrame.current.src;
}

View File

@ -21,7 +21,7 @@ import { _t } from '../../../languageHandler';
import {formatFullDateNoTime} from '../../../DateUtils';
function getdaysArray() {
return [
return [
_t('Sunday'),
_t('Monday'),
_t('Tuesday'),

View File

@ -58,7 +58,7 @@ export default createReactClass({
'a': (sub)=><a onClick={this._onClickUserSettings} href=''>{ sub }</a>,
})
);
} else if (accountEnabled) {
} else {
previewsForAccount = (
_t("You have <a>disabled</a> URL previews by default.", {}, {
'a': (sub)=><a onClick={this._onClickUserSettings} href=''>{ sub }</a>,

View File

@ -29,6 +29,9 @@ import {getAddressType} from "./UserAddress";
const E2EE_WK_KEY = "im.vector.riot.e2ee";
// we define a number of interfaces which take their names from the js-sdk
/* eslint-disable camelcase */
// TODO move these interfaces over to js-sdk once it has been typescripted enough to accept them
enum Visibility {
Public = "public",

View File

@ -17,7 +17,6 @@ limitations under the License.
import {CARET_NODE_CHAR, isCaretNode} from "./render";
import DocumentOffset from "./offset";
import EditorModel from "./model";
type Predicate = (node: Node) => boolean;
type Callback = (node: Node) => void;

View File

@ -30,7 +30,7 @@ import {Caret} from "./caret";
* @param {object?} diff an object with `removed` and `added` strings
*/
/**
/**
* @callback TransformCallback
* @param {DocumentPosition?} caretPosition the position where the caret should be position
* @param {string?} inputType the inputType of the DOM input event

View File

@ -22,7 +22,7 @@ import {Room} from "matrix-js-sdk/src/models/room";
import AutocompleteWrapperModel, {
GetAutocompleterComponent,
UpdateCallback,
UpdateQuery
UpdateQuery,
} from "./autocomplete";
import * as Avatar from "../Avatar";

View File

@ -31,7 +31,8 @@ export function mdSerialize(model: EditorModel) {
return html + part.text;
case "room-pill":
case "user-pill":
return html + `[${part.text.replace(/[[\\\]]/g, c => "\\" + c)}](${makeGenericPermalink(part.resourceId)})`;
return html +
`[${part.text.replace(/[[\\\]]/g, c => "\\" + c)}](${makeGenericPermalink(part.resourceId)})`;
}
}, "");
}

View File

@ -30,7 +30,7 @@ export const useAccountData = <T extends {}>(cli: MatrixClient, eventType: strin
const handler = useCallback((event) => {
if (event.getType() !== eventType) return;
setValue(event.getContent());
}, [cli, eventType]);
}, [eventType]);
useEventEmitter(cli, "accountData", handler);
return value || {} as T;
@ -43,7 +43,7 @@ export const useRoomAccountData = <T extends {}>(room: Room, eventType: string)
const handler = useCallback((event) => {
if (event.getType() !== eventType) return;
setValue(event.getContent());
}, [room, eventType]);
}, [eventType]);
useEventEmitter(room, "Room.accountData", handler);
return value || {} as T;

View File

@ -14,6 +14,9 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
// The following interfaces take their names and member names from seshat and the spec
/* eslint-disable camelcase */
export interface MatrixEvent {
type: string;
sender: string;
@ -21,7 +24,7 @@ export interface MatrixEvent {
event_id: string;
origin_server_ts: number;
unsigned?: {};
room_id: string;
roomId: string;
}
export interface MatrixProfile {

View File

@ -123,7 +123,12 @@ export class IntegrationManagers {
const apiUrl = data['api_url'];
if (!apiUrl || !uiUrl) return;
const manager = new IntegrationManagerInstance(Kind.Account, apiUrl, uiUrl, w['id'] || w['state_key'] || '');
const manager = new IntegrationManagerInstance(
Kind.Account,
apiUrl,
uiUrl,
w['id'] || w['state_key'] || '',
);
this.managers.push(manager);
});
this.primaryManager = null; // reset primary

View File

@ -16,7 +16,7 @@ limitations under the License.
*/
import {PushRuleVectorState, State} from "./PushRuleVectorState";
import {IExtendedPushRule, IPushRuleSet, IRuleSets} from "./types";
import {IExtendedPushRule, IRuleSets} from "./types";
export interface IContentRules {
vectorState: State;

View File

@ -22,10 +22,12 @@ export enum NotificationSetting {
}
export interface ISoundTweak {
// eslint-disable-next-line camelcase
set_tweak: "sound";
value: string;
}
export interface IHighlightTweak {
// eslint-disable-next-line camelcase
set_tweak: "highlight";
value?: boolean;
}
@ -86,6 +88,7 @@ export enum RuleIds {
export interface IPushRule {
enabled: boolean;
// eslint-disable-next-line camelcase
rule_id: RuleIds | string;
actions: Action[];
default: boolean;

View File

@ -19,7 +19,6 @@ import SettingsStore, {SettingLevel} from '../SettingsStore';
import IWatcher from "./Watcher";
import { toPx } from '../../utils/units';
import { Action } from '../../dispatcher/actions';
import { UpdateSystemFontPayload } from '../../dispatcher/payloads/UpdateSystemFontPayload';
export class FontWatcher implements IWatcher {
public static readonly MIN_SIZE = 8;

View File

@ -17,4 +17,4 @@ limitations under the License.
export default interface IWatcher {
start(): void;
stop(): void;
}
}

View File

@ -171,5 +171,4 @@ export class BreadcrumbsStore extends AsyncStoreWithClient<IState> {
}
}
}
}

View File

@ -37,8 +37,8 @@ export default class ToastStore extends EventEmitter {
private countSeen = 0;
static sharedInstance() {
if (!window.mx_ToastStore) window.mx_ToastStore = new ToastStore();
return window.mx_ToastStore;
if (!window.mxToastStore) window.mxToastStore = new ToastStore();
return window.mxToastStore;
}
reset() {

View File

@ -70,4 +70,4 @@ export default class RoomListLayoutStore extends AsyncStoreWithClient<IState> {
}
}
window.mx_RoomListLayoutStore = RoomListLayoutStore.instance;
window.mxRoomListLayoutStore = RoomListLayoutStore.instance;

View File

@ -18,7 +18,6 @@ limitations under the License.
import { MatrixClient } from "matrix-js-sdk/src/client";
import SettingsStore from "../../settings/SettingsStore";
import { DefaultTagID, isCustomTag, OrderedDefaultTagIDs, RoomUpdateCause, TagID } from "./models";
import TagOrderStore from "../TagOrderStore";
import { Room } from "matrix-js-sdk/src/models/room";
import { IListOrderingMap, ITagMap, ITagSortingMap, ListAlgorithm, SortAlgorithm } from "./algorithms/models";
import { ActionPayload } from "../../dispatcher/payloads";
@ -33,7 +32,6 @@ import { isNullOrUndefined } from "matrix-js-sdk/src/utils";
import RoomListLayoutStore from "./RoomListLayoutStore";
import { MarkedExecution } from "../../utils/MarkedExecution";
import { AsyncStoreWithClient } from "../AsyncStoreWithClient";
import { isEnumValue } from "../../utils/enums";
interface IState {
tagsEnabled?: boolean;
@ -610,4 +608,4 @@ export default class RoomListStore {
}
}
window.mx_RoomListStore = RoomListStore.instance;
window.mxRoomListStore = RoomListStore.instance;

View File

@ -27,7 +27,7 @@ import {
ITagMap,
ITagSortingMap,
ListAlgorithm,
SortAlgorithm
SortAlgorithm,
} from "./models";
import { FILTER_CHANGED, FilterPriority, IFilterCondition } from "../filters/IFilterCondition";
import { EffectiveMembership, getEffectiveMembership, splitRoomsByMembership } from "../../../utils/membership";
@ -419,7 +419,9 @@ export class Algorithm extends EventEmitter {
if (!updatedTag || updatedTag === sticky.tag) {
if (SettingsStore.getValue("advancedRoomListLogging")) {
// TODO: Remove debug: https://github.com/vector-im/riot-web/issues/14602
console.log(`Inserting sticky room ${sticky.room.roomId} at position ${sticky.position} in ${sticky.tag}`);
console.log(
`Inserting sticky room ${sticky.room.roomId} at position ${sticky.position} in ${sticky.tag}`,
);
}
this._cachedStickyRooms[sticky.tag].splice(sticky.position, 0, sticky.room);
}

View File

@ -218,7 +218,12 @@ export class ImportanceAlgorithm extends OrderingAlgorithm {
}
// noinspection JSMethodCanBeStatic
private moveRoomIndexes(nRooms: number, fromCategory: NotificationColor, toCategory: NotificationColor, indices: ICategoryIndex) {
private moveRoomIndexes(
nRooms: number,
fromCategory: NotificationColor,
toCategory: NotificationColor,
indices: ICategoryIndex,
) {
// We have to update the index of the category *after* the from/toCategory variables
// in order to update the indices correctly. Because the room is moving from/to those
// categories, the next category's index will change - not the category we're modifying.
@ -257,7 +262,9 @@ export class ImportanceAlgorithm extends OrderingAlgorithm {
if (indices[lastCat] > indices[thisCat]) {
// "should never happen" disclaimer goes here
console.warn(`!! Room list index corruption: ${lastCat} (i:${indices[lastCat]}) is greater than ${thisCat} (i:${indices[thisCat]}) - category indices are likely desynced from reality`);
console.warn(
`!! Room list index corruption: ${lastCat} (i:${indices[lastCat]}) is greater ` +
`than ${thisCat} (i:${indices[thisCat]}) - category indices are likely desynced from reality`);
// TODO: Regenerate index when this happens: https://github.com/vector-im/riot-web/issues/14234
}

View File

@ -25,7 +25,6 @@ import { Room } from "matrix-js-sdk/src/models/room";
* additional behavioural changes are present.
*/
export class NaturalAlgorithm extends OrderingAlgorithm {
public constructor(tagId: TagID, initialSortingAlgorithm: SortAlgorithm) {
super(tagId, initialSortingAlgorithm);
}
@ -57,7 +56,11 @@ export class NaturalAlgorithm extends OrderingAlgorithm {
// TODO: Optimize this to avoid useless operations: https://github.com/vector-im/riot-web/issues/14457
// For example, we can skip updates to alphabetic (sometimes) and manually ordered tags
this.cachedOrderedRooms = await sortRoomsWithAlgorithm(this.cachedOrderedRooms, this.tagId, this.sortingAlgorithm);
this.cachedOrderedRooms = await sortRoomsWithAlgorithm(
this.cachedOrderedRooms,
this.tagId,
this.sortingAlgorithm,
);
return true;
} finally {

View File

@ -36,7 +36,11 @@ const ALGORITHM_FACTORIES: { [algorithm in ListAlgorithm]: AlgorithmFactory } =
* @param {SortAlgorithm} initSort The initial sorting algorithm for the ordering algorithm.
* @returns {Algorithm} The algorithm instance.
*/
export function getListAlgorithmInstance(algorithm: ListAlgorithm, tagId: TagID, initSort: SortAlgorithm): OrderingAlgorithm {
export function getListAlgorithmInstance(
algorithm: ListAlgorithm,
tagId: TagID,
initSort: SortAlgorithm,
): OrderingAlgorithm {
if (!ALGORITHM_FACTORIES[algorithm]) {
throw new Error(`${algorithm} is not a known algorithm`);
}

View File

@ -22,12 +22,12 @@ import { _t } from '../languageHandler';
* e.g: 999, 9.9K, 99K, 0.9M, 9.9M, 99M, 0.9B, 9.9B
*/
export function formatCount(count: number): string {
if (count < 1000) return count.toString();
if (count < 10000) return (count / 1000).toFixed(1) + "K";
if (count < 100000) return (count / 1000).toFixed(0) + "K";
if (count < 10000000) return (count / 1000000).toFixed(1) + "M";
if (count < 100000000) return (count / 1000000).toFixed(0) + "M";
return (count / 1000000000).toFixed(1) + "B"; // 10B is enough for anyone, right? :S
if (count < 1000) return count.toString();
if (count < 10000) return (count / 1000).toFixed(1) + "K";
if (count < 100000) return (count / 1000).toFixed(0) + "K";
if (count < 10000000) return (count / 1000000).toFixed(1) + "M";
if (count < 100000000) return (count / 1000000).toFixed(0) + "M";
return (count / 1000000000).toFixed(1) + "B"; // 10B is enough for anyone, right? :S
}
/**

View File

@ -27,7 +27,7 @@ export async function shieldStatusForRoom(client: Client, room: Room): Promise<s
members.filter((userId) => userId !== client.getUserId())
.forEach((userId) => {
(client.checkUserTrust(userId).isCrossSigningVerified() ?
verified : unverified).push(userId);
verified : unverified).push(userId);
});
/* Alarm if any unverified users were verified before. */

View File

@ -113,7 +113,7 @@ export class WidgetApi extends EventEmitter {
// Finalization needs to be async, so postpone with a promise
let finalizePromise = Promise.resolve();
const wait = (promise) => {
finalizePromise = finalizePromise.then(value => promise);
finalizePromise = finalizePromise.then(() => promise);
};
this.emit('terminate', wait);
Promise.resolve(finalizePromise).then(() => {

810
yarn.lock

File diff suppressed because it is too large Load Diff