Use new eslint package- fix lint issues in ts and js

This commit is contained in:
Jorik Schellekens 2020-06-23 16:41:36 +01:00
parent de227c0650
commit 7699aafcaf
31 changed files with 387 additions and 347 deletions

View file

@ -29,10 +29,10 @@ declare global {
init: () => Promise<void>;
};
mx_ContentMessages: ContentMessages;
mx_ToastStore: ToastStore;
mx_DeviceListener: DeviceListener;
mx_RoomListStore2: RoomListStore2;
mxContentMessages: ContentMessages;
mxToastStore: ToastStore;
mxDeviceListener: DeviceListener;
mxRoomListStore2: RoomListStore2;
}
// workaround for https://github.com/microsoft/TypeScript/issues/30933

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

@ -107,7 +107,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, {
@ -127,7 +127,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

@ -118,7 +118,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

@ -32,4 +32,4 @@ export interface ViewTooltipPayload extends ActionPayload {
* the parent type.
*/
parent: null | Element;
}
}

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

@ -22,7 +22,7 @@ import {Dispatcher} from "flux";
// Hook to simplify listening to flux dispatches
export const useDispatcher = (dispatcher: Dispatcher<ActionPayload>, handler: (payload: ActionPayload) => void) => {
// Create a ref that stores handler
const savedHandler = useRef((payload: ActionPayload) => {});
const savedHandler = useRef((_: ActionPayload) => {});
// Update ref.current value if handler changes.
useEffect(() => {

View file

@ -18,14 +18,14 @@ export interface MatrixEvent {
type: string;
sender: string;
content: {};
event_id: string;
origin_server_ts: number;
eventId: string;
originServerTs: number;
unsigned?: {};
room_id: string;
roomId: string;
}
export interface MatrixProfile {
avatar_url: string;
avatarUrl: string;
displayname: string;
}
@ -37,9 +37,9 @@ export interface CrawlerCheckpoint {
}
export interface ResultContext {
events_before: [MatrixEvent];
events_after: [MatrixEvent];
profile_info: Map<string, MatrixProfile>;
eventsBefore: [MatrixEvent];
eventsAfter: [MatrixEvent];
profileInfo: Map<string, MatrixProfile>;
}
export interface ResultsElement {
@ -55,11 +55,11 @@ export interface SearchResult {
}
export interface SearchArgs {
search_term: string;
before_limit: number;
after_limit: number;
order_by_recency: boolean;
room_id?: string;
searchTerm: string;
beforeLimit: number;
afterLimit: number;
orderByRecency: boolean;
roomId?: string;
}
export interface EventAndProfile {
@ -76,8 +76,8 @@ export interface LoadArgs {
export interface IndexStats {
size: number;
event_count: number;
room_count: number;
eventCount: number;
roomCount: number;
}
/**

View file

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

View file

@ -162,5 +162,4 @@ export class BreadcrumbsStore extends AsyncStoreWithClient<IState> {
await SettingsStore.setValue("breadcrumb_rooms", null, SettingLevel.ACCOUNT, roomIds);
}
}
}

View file

@ -20,7 +20,8 @@ import { throttle } from "lodash";
import SettingsStore from "../settings/SettingsStore";
import {RoomListStoreTempProxy} from "./room-list/RoomListStoreTempProxy";
const STANDARD_TAGS_REGEX = /^(m\.(favourite|lowpriority|server_notice)|im\.vector\.fake\.(invite|recent|direct|archived))$/;
const STANDARD_TAGS_REGEX =
/^(m\.(favourite|lowpriority|server_notice)|im\.vector\.fake\.(invite|recent|direct|archived))$/;
function commonPrefix(a, b) {
const len = Math.min(a.length, b.length);

View file

@ -61,7 +61,7 @@ export class MessagePreviewStore extends AsyncStoreWithClient<IState> {
/**
* Gets the pre-translated preview for a given room
* @param room The room to get the preview for.
* @returns The preview, or null if none present.
* @returns {string} The preview, or null if none present.
*/
public getPreviewForRoom(room: Room): string {
if (!room) return null; // invalid room, just return nothing

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

@ -180,7 +180,9 @@ export class RoomListStore2 extends AsyncStore<ActionPayload> {
const roomId = eventPayload.event.getRoomId();
const room = this.matrixClient.getRoom(roomId);
const tryUpdate = async (updatedRoom: Room) => {
console.log(`[RoomListDebug] Live timeline event ${eventPayload.event.getId()} in ${updatedRoom.roomId}`);
console.log(
`[RoomListDebug] Live timeline event ${eventPayload.event.getId()} in ${updatedRoom.roomId}`,
);
if (eventPayload.event.getType() === 'm.room.tombstone' && eventPayload.event.getStateKey() === '') {
console.log(`[RoomListDebug] Got tombstone event - regenerating room list`);
// TODO: We could probably be smarter about this
@ -380,4 +382,4 @@ export default class RoomListStore {
}
}
window.mx_RoomListStore2 = RoomListStore.instance;
window.mxRoomListStore2 = 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, splitRoomsByMembership } from "../membership";
@ -305,7 +305,7 @@ export class Algorithm extends EventEmitter {
if (!this._stickyRoom) {
// If there's no sticky room, just do nothing useful.
if (!!this._cachedStickyRooms) {
if (this._cachedStickyRooms) {
// Clear the cache if we won't be needing it
this._cachedStickyRooms = null;
this.emit(LIST_UPDATED_EVENT);
@ -518,13 +518,12 @@ export class Algorithm extends EventEmitter {
}
}
let tags = this.roomIdsToTags[room.roomId];
const tags = this.roomIdsToTags[room.roomId];
if (!tags) {
console.warn(`No tags known for "${room.name}" (${room.roomId})`);
return false;
}
let changed = false;
for (const tag of tags) {
const algorithm: OrderingAlgorithm = this.algorithms[tag];
if (!algorithm) throw new Error(`No algorithm for ${tag}`);
@ -535,7 +534,6 @@ export class Algorithm extends EventEmitter {
// Flag that we've done something
this.recalculateFilteredRoomsForTag(tag); // update filter to re-sort the list
this.recalculateStickyRoom(tag); // update sticky room to make sure it appears if needed
changed = true;
}
return true;

View file

@ -290,6 +290,7 @@ export class ImportanceAlgorithm extends OrderingAlgorithm {
if (indices[lastCat] > indices[thisCat]) {
// "should never happen" disclaimer goes here
// eslint-disable-next-line max-len
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

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);
console.log(`[RoomListDebug] Constructed a NaturalAlgorithm for ${tagId}`);
@ -51,7 +50,11 @@ export class NaturalAlgorithm extends OrderingAlgorithm {
// TODO: Optimize this to avoid useless operations
// 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;
}

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

@ -17,8 +17,6 @@ limitations under the License.
import { Room } from "matrix-js-sdk/src/models/room";
import { TagID } from "../../models";
import { IAlgorithm } from "./IAlgorithm";
import { MatrixClientPeg } from "../../../../MatrixClientPeg";
import * as Unread from "../../../../Unread";
/**
* Sorts rooms according to the browser's determination of alphabetic.

View file

@ -25,7 +25,7 @@ import * as Unread from "../../../../Unread";
* useful to the user.
*/
export class RecentAlgorithm implements IAlgorithm {
public async sortRooms(rooms: Room[], tagId: TagID): Promise<Room[]> {
public async sortRooms(rooms: Room[], _: TagID): Promise<Room[]> {
// We cache the timestamp lookup to avoid iterating forever on the timeline
// of events. This cache only survives a single sort though.
// We wouldn't need this if `.sort()` didn't constantly try and compare all

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

@ -112,7 +112,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(() => {