Skip to content
This repository has been archived by the owner on Sep 11, 2024. It is now read-only.

Commit

Permalink
Make more code conform to strict null checks (#10219
Browse files Browse the repository at this point in the history
* Make more code conform to strict null checks

* Fix types

* Fix tests

* Fix remaining test assertions

* Iterate PR
  • Loading branch information
t3chguy authored Feb 24, 2023
1 parent 4c79ecf commit 76b82b4
Show file tree
Hide file tree
Showing 130 changed files with 603 additions and 603 deletions.
10 changes: 5 additions & 5 deletions src/AddThreepid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export type Binding = {
*/
export default class AddThreepid {
private sessionId: string;
private submitUrl: string;
private submitUrl?: string;
private clientSecret: string;
private bind: boolean;

Expand Down Expand Up @@ -93,7 +93,7 @@ export default class AddThreepid {
if (await MatrixClientPeg.get().doesServerSupportSeparateAddAndBind()) {
// For separate bind, request a token directly from the IS.
const authClient = new IdentityAuthClient();
const identityAccessToken = await authClient.getAccessToken();
const identityAccessToken = (await authClient.getAccessToken()) ?? undefined;
return MatrixClientPeg.get()
.requestEmailToken(emailAddress, this.clientSecret, 1, undefined, identityAccessToken)
.then(
Expand Down Expand Up @@ -155,7 +155,7 @@ export default class AddThreepid {
if (await MatrixClientPeg.get().doesServerSupportSeparateAddAndBind()) {
// For separate bind, request a token directly from the IS.
const authClient = new IdentityAuthClient();
const identityAccessToken = await authClient.getAccessToken();
const identityAccessToken = (await authClient.getAccessToken()) ?? undefined;
return MatrixClientPeg.get()
.requestMsisdnToken(phoneCountry, phoneNumber, this.clientSecret, 1, undefined, identityAccessToken)
.then(
Expand Down Expand Up @@ -184,7 +184,7 @@ export default class AddThreepid {
* with a "message" property which contains a human-readable message detailing why
* the request failed.
*/
public async checkEmailLinkClicked(): Promise<[boolean, IAuthData | Error | null]> {
public async checkEmailLinkClicked(): Promise<[boolean, IAuthData | Error | null] | undefined> {
try {
if (await MatrixClientPeg.get().doesServerSupportSeparateAddAndBind()) {
if (this.bind) {
Expand Down Expand Up @@ -282,7 +282,7 @@ export default class AddThreepid {
* with a "message" property which contains a human-readable message detailing why
* the request failed.
*/
public async haveMsisdnToken(msisdnToken: string): Promise<any[]> {
public async haveMsisdnToken(msisdnToken: string): Promise<any[] | undefined> {
const authClient = new IdentityAuthClient();
const supportsSeparateAddAndBind = await MatrixClientPeg.get().doesServerSupportSeparateAddAndBind();

Expand Down
2 changes: 1 addition & 1 deletion src/ContentMessages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -546,7 +546,7 @@ export default class ContentMessages {
if (upload.cancelled) throw new UploadCanceledError();
const threadId = relation?.rel_type === THREAD_RELATION_TYPE.name ? relation.event_id : null;

const response = await matrixClient.sendMessage(roomId, threadId, content);
const response = await matrixClient.sendMessage(roomId, threadId ?? null, content);

if (SettingsStore.getValue("Performance.addSendMessageTimingMetadata")) {
sendRoundTripMetric(matrixClient, roomId, response.event_id);
Expand Down
7 changes: 3 additions & 4 deletions src/LegacyCallHandler.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1024,13 +1024,12 @@ export default class LegacyCallHandler extends EventEmitter {
}

public answerCall(roomId: string): void {
const call = this.calls.get(roomId);

this.stopRingingIfPossible(call.callId);

// no call to answer
if (!this.calls.has(roomId)) return;

const call = this.calls.get(roomId)!;
this.stopRingingIfPossible(call.callId);

if (this.getAllActiveCalls().length > 1) {
Modal.createDialog(ErrorDialog, {
title: _t("Too Many Calls"),
Expand Down
4 changes: 2 additions & 2 deletions src/Lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ export function handleInvalidStoreError(e: InvalidStoreError): Promise<void> {
return MatrixClientPeg.get().store.deleteAllData();
})
.then(() => {
PlatformPeg.get().reload();
PlatformPeg.get()?.reload();
});
}
}
Expand Down Expand Up @@ -519,7 +519,7 @@ export async function setLoggedIn(credentials: IMatrixClientCreds): Promise<Matr
stopMatrixClient();
const pickleKey =
credentials.userId && credentials.deviceId
? await PlatformPeg.get().createPickleKey(credentials.userId, credentials.deviceId)
? await PlatformPeg.get()?.createPickleKey(credentials.userId, credentials.deviceId)
: null;

if (pickleKey) {
Expand Down
6 changes: 3 additions & 3 deletions src/MatrixClientPeg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ class MatrixClientPegClass implements IMatrixClientPeg {
}

try {
const registrationTime = parseInt(window.localStorage.getItem("mx_registration_time"), 10);
const registrationTime = parseInt(window.localStorage.getItem("mx_registration_time")!, 10);
const diff = Date.now() - registrationTime;
return diff / 36e5 <= hours;
} catch (e) {
Expand All @@ -176,7 +176,7 @@ class MatrixClientPegClass implements IMatrixClientPeg {

public userRegisteredAfter(timestamp: Date): boolean {
try {
const registrationTime = parseInt(window.localStorage.getItem("mx_registration_time"), 10);
const registrationTime = parseInt(window.localStorage.getItem("mx_registration_time")!, 10);
return timestamp.getTime() <= registrationTime;
} catch (e) {
return false;
Expand Down Expand Up @@ -292,7 +292,7 @@ class MatrixClientPegClass implements IMatrixClientPeg {
}

public getCredentials(): IMatrixClientCreds {
let copiedCredentials = this.currentClientCreds;
let copiedCredentials: IMatrixClientCreds | null = this.currentClientCreds;
if (this.currentClientCreds?.userId !== this.matrixClient?.credentials?.userId) {
// cached credentials belong to a different user - don't use them
copiedCredentials = null;
Expand Down
2 changes: 1 addition & 1 deletion src/MediaDeviceHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export default class MediaDeviceHandler extends EventEmitter {
*
* @return Promise<IMediaDevices> The available media devices
*/
public static async getDevices(): Promise<IMediaDevices> {
public static async getDevices(): Promise<IMediaDevices | undefined> {
try {
const devices = await navigator.mediaDevices.enumerateDevices();
const output: Record<MediaDeviceKindEnum, MediaDeviceInfo[]> = {
Expand Down
8 changes: 4 additions & 4 deletions src/PosthogTrackers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ export default class PosthogTrackers {
}

private view: Views = Views.LOADING;
private pageType?: PageType = null;
private override?: ScreenName = null;
private pageType?: PageType;
private override?: ScreenName;

public trackPageChange(view: Views, pageType: PageType | undefined, durationMs: number): void {
this.view = view;
Expand All @@ -66,7 +66,7 @@ export default class PosthogTrackers {

private trackPage(durationMs?: number): void {
const screenName =
this.view === Views.LOGGED_IN ? loggedInPageTypeMap[this.pageType] : notLoggedInMap[this.view];
this.view === Views.LOGGED_IN ? loggedInPageTypeMap[this.pageType!] : notLoggedInMap[this.view];
PosthogAnalytics.instance.trackEvent<ScreenEvent>({
eventName: "$pageview",
$current_url: screenName,
Expand All @@ -85,7 +85,7 @@ export default class PosthogTrackers {

public clearOverride(screenName: ScreenName): void {
if (screenName !== this.override) return;
this.override = null;
this.override = undefined;
this.trackPage();
}

Expand Down
1 change: 0 additions & 1 deletion src/SdkConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ export const DEFAULTS: IConfigOptions = {
brand: "Element",
integrations_ui_url: "https://scalar.vector.im/",
integrations_rest_url: "https://scalar.vector.im/api",
bug_report_endpoint_url: null,
uisi_autorageshake_app: "element-auto-uisi",

jitsi: {
Expand Down
8 changes: 4 additions & 4 deletions src/SlashCommands.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ function reject(error?: any): RunResult {
return { error };
}

function success(promise?: Promise<any>): RunResult {
function success(promise: Promise<any> = Promise.resolve()): RunResult {
return { promise };
}

Expand All @@ -221,7 +221,7 @@ export const Commands = [
command: "spoiler",
args: "<message>",
description: _td("Sends the given message as a spoiler"),
runFn: function (roomId, message) {
runFn: function (roomId, message = "") {
return successSync(ContentHelpers.makeHtmlMessage(message, `<span data-mx-spoiler>${message}</span>`));
},
category: CommandCategories.messages,
Expand Down Expand Up @@ -282,7 +282,7 @@ export const Commands = [
command: "plain",
args: "<message>",
description: _td("Sends a message as plain text, without interpreting it as markdown"),
runFn: function (roomId, messages) {
runFn: function (roomId, messages = "") {
return successSync(ContentHelpers.makeTextMessage(messages));
},
category: CommandCategories.messages,
Expand All @@ -291,7 +291,7 @@ export const Commands = [
command: "html",
args: "<message>",
description: _td("Sends a message as html, without interpreting it as markdown"),
runFn: function (roomId, messages) {
runFn: function (roomId, messages = "") {
return successSync(ContentHelpers.makeHtmlMessage(messages, messages));
},
category: CommandCategories.messages,
Expand Down
11 changes: 6 additions & 5 deletions src/autocomplete/Autocompleter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { timeout } from "../utils/promise";
import AutocompleteProvider, { ICommand } from "./AutocompleteProvider";
import SpaceProvider from "./SpaceProvider";
import { TimelineRenderingType } from "../contexts/RoomContext";
import { filterBoolean } from "../utils/arrays";

export interface ISelectionRange {
beginning?: boolean; // whether the selection is in the first block of the editor or not
Expand Down Expand Up @@ -55,7 +56,7 @@ const PROVIDER_COMPLETION_TIMEOUT = 3000;
export interface IProviderCompletions {
completions: ICompletion[];
provider: AutocompleteProvider;
command: ICommand;
command: Partial<ICommand>;
}

export default class Autocompleter {
Expand Down Expand Up @@ -98,8 +99,8 @@ export default class Autocompleter {
);

// map then filter to maintain the index for the map-operation, for this.providers to line up
return completionsList
.map((completions, i) => {
return filterBoolean(
completionsList.map((completions, i) => {
if (!completions || !completions.length) return;

return {
Expand All @@ -112,7 +113,7 @@ export default class Autocompleter {
*/
command: this.providers[i].getCurrentCommand(query, selection, force),
};
})
.filter(Boolean) as IProviderCompletions[];
}),
);
}
}
3 changes: 2 additions & 1 deletion src/autocomplete/EmojiProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import SettingsStore from "../settings/SettingsStore";
import { EMOJI, IEmoji, getEmojiFromUnicode } from "../emoji";
import { TimelineRenderingType } from "../contexts/RoomContext";
import * as recent from "../emojipicker/recent";
import { filterBoolean } from "../utils/arrays";

const LIMIT = 20;

Expand Down Expand Up @@ -94,7 +95,7 @@ export default class EmojiProvider extends AutocompleteProvider {
shouldMatchWordsOnly: true,
});

this.recentlyUsed = Array.from(new Set(recent.get().map(getEmojiFromUnicode).filter(Boolean))) as IEmoji[];
this.recentlyUsed = Array.from(new Set(filterBoolean(recent.get().map(getEmojiFromUnicode))));
}

public async getCompletions(
Expand Down
9 changes: 4 additions & 5 deletions src/components/structures/EmbeddedPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ interface IState {
export default class EmbeddedPage extends React.PureComponent<IProps, IState> {
public static contextType = MatrixClientContext;
private unmounted = false;
private dispatcherRef: string = null;
private dispatcherRef: string | null = null;

public constructor(props: IProps, context: typeof MatrixClientContext) {
super(props, context);
Expand All @@ -64,7 +64,7 @@ export default class EmbeddedPage extends React.PureComponent<IProps, IState> {
let res: Response;

try {
res = await fetch(this.props.url, { method: "GET" });
res = await fetch(this.props.url!, { method: "GET" });
} catch (err) {
if (this.unmounted) return;
logger.warn(`Error loading page: ${err}`);
Expand All @@ -84,7 +84,7 @@ export default class EmbeddedPage extends React.PureComponent<IProps, IState> {

if (this.props.replaceMap) {
Object.keys(this.props.replaceMap).forEach((key) => {
body = body.split(key).join(this.props.replaceMap[key]);
body = body.split(key).join(this.props.replaceMap![key]);
});
}

Expand Down Expand Up @@ -123,8 +123,7 @@ export default class EmbeddedPage extends React.PureComponent<IProps, IState> {
const client = this.context || MatrixClientPeg.get();
const isGuest = client ? client.isGuest() : true;
const className = this.props.className;
const classes = classnames({
[className]: true,
const classes = classnames(className, {
[`${className}_guest`]: isGuest,
[`${className}_loggedIn`]: !!client,
});
Expand Down
6 changes: 5 additions & 1 deletion src/components/structures/FileDropTarget.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ const FileDropTarget: React.FC<IProps> = ({ parent, onFileDrop }) => {
const onDragEnter = (ev: DragEvent): void => {
ev.stopPropagation();
ev.preventDefault();
if (!ev.dataTransfer) return;

setState((state) => ({
// We always increment the counter no matter the types, because dragging is
Expand All @@ -49,7 +50,8 @@ const FileDropTarget: React.FC<IProps> = ({ parent, onFileDrop }) => {
// https://docs.w3cub.com/dom/datatransfer/types
// https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types#file
dragging:
ev.dataTransfer.types.includes("Files") || ev.dataTransfer.types.includes("application/x-moz-file")
ev.dataTransfer!.types.includes("Files") ||
ev.dataTransfer!.types.includes("application/x-moz-file")
? true
: state.dragging,
}));
Expand All @@ -68,6 +70,7 @@ const FileDropTarget: React.FC<IProps> = ({ parent, onFileDrop }) => {
const onDragOver = (ev: DragEvent): void => {
ev.stopPropagation();
ev.preventDefault();
if (!ev.dataTransfer) return;

ev.dataTransfer.dropEffect = "none";

Expand All @@ -82,6 +85,7 @@ const FileDropTarget: React.FC<IProps> = ({ parent, onFileDrop }) => {
const onDrop = (ev: DragEvent): void => {
ev.stopPropagation();
ev.preventDefault();
if (!ev.dataTransfer) return;
onFileDrop(ev.dataTransfer);

setState((state) => ({
Expand Down
8 changes: 4 additions & 4 deletions src/components/structures/FilePanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ class FilePanel extends React.Component<IProps, IState> {

private onRoomTimeline = (
ev: MatrixEvent,
room: Room | null,
room: Room | undefined,
toStartOfTimeline: boolean,
removed: boolean,
data: IRoomTimelineData,
Expand All @@ -78,15 +78,15 @@ class FilePanel extends React.Component<IProps, IState> {
client.decryptEventIfNeeded(ev);

if (ev.isBeingDecrypted()) {
this.decryptingEvents.add(ev.getId());
this.decryptingEvents.add(ev.getId()!);
} else {
this.addEncryptedLiveEvent(ev);
}
};

private onEventDecrypted = (ev: MatrixEvent, err?: any): void => {
if (ev.getRoomId() !== this.props.roomId) return;
const eventId = ev.getId();
const eventId = ev.getId()!;

if (!this.decryptingEvents.delete(eventId)) return;
if (err) return;
Expand All @@ -103,7 +103,7 @@ class FilePanel extends React.Component<IProps, IState> {
return;
}

if (!this.state.timelineSet.eventIdToTimeline(ev.getId())) {
if (!this.state.timelineSet.eventIdToTimeline(ev.getId()!)) {
this.state.timelineSet.addEventToTimeline(ev, timeline, false);
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/components/structures/HomePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,15 +56,15 @@ const getOwnProfile = (
userId: string,
): {
displayName: string;
avatarUrl: string;
avatarUrl?: string;
} => ({
displayName: OwnProfileStore.instance.displayName || userId,
avatarUrl: OwnProfileStore.instance.getHttpAvatarUrl(AVATAR_SIZE),
avatarUrl: OwnProfileStore.instance.getHttpAvatarUrl(AVATAR_SIZE) ?? undefined,
});

const UserWelcomeTop: React.FC = () => {
const cli = useContext(MatrixClientContext);
const userId = cli.getUserId();
const userId = cli.getUserId()!;
const [ownProfile, setOwnProfile] = useState(getOwnProfile(userId));
useEventEmitter(OwnProfileStore.instance, UPDATE_EVENT, () => {
setOwnProfile(getOwnProfile(userId));
Expand Down
Loading

0 comments on commit 76b82b4

Please sign in to comment.