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

Commit

Permalink
Conform more of the code base to strict null checking (#10147)
Browse files Browse the repository at this point in the history
* Conform more of the code base to strict null checking

* More strict fixes

* More strict work

* Fix missing optional type

* Iterate
  • Loading branch information
t3chguy authored Feb 13, 2023
1 parent fa036a5 commit da7aa40
Show file tree
Hide file tree
Showing 380 changed files with 682 additions and 694 deletions.
2 changes: 1 addition & 1 deletion src/AsyncWrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export default class AsyncWrapper extends React.Component<IProps, IState> {
this.props.onFinished(false);
};

public render(): JSX.Element {
public render(): React.ReactNode {
if (this.state.component) {
const Component = this.state.component;
return <Component {...this.props} />;
Expand Down
2 changes: 1 addition & 1 deletion src/Avatar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ export function getInitialLetter(name: string): string | undefined {
}

export function avatarUrlForRoom(
room: Room,
room: Room | null,
width: number,
height: number,
resizeMethod?: ResizeMethod,
Expand Down
30 changes: 14 additions & 16 deletions src/HtmlUtils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ const transformTags: IExtendedSanitizeOptions["transformTags"] = {
attribs.style += "height: 100%;";
}

attribs.src = mediaFromMxc(src).getThumbnailOfSourceHttp(width, height);
attribs.src = mediaFromMxc(src).getThumbnailOfSourceHttp(width, height)!;
return { tagName, attribs };
},
"code": function (tagName: string, attribs: sanitizeHtml.Attributes) {
Expand Down Expand Up @@ -352,7 +352,7 @@ const topicSanitizeHtmlParams: IExtendedSanitizeOptions = {
};

abstract class BaseHighlighter<T extends React.ReactNode> {
public constructor(public highlightClass: string, public highlightLink: string) {}
public constructor(public highlightClass: string, public highlightLink?: string) {}

/**
* apply the highlights to a section of text
Expand Down Expand Up @@ -504,7 +504,7 @@ function formatEmojis(message: string, isHtmlMessage: boolean): (JSX.Element | s
export function bodyToHtml(content: IContent, highlights: Optional<string[]>, opts: IOptsReturnString): string;
export function bodyToHtml(content: IContent, highlights: Optional<string[]>, opts: IOptsReturnNode): ReactNode;
export function bodyToHtml(content: IContent, highlights: Optional<string[]>, opts: IOpts = {}): ReactNode | string {
const isFormattedBody = content.format === "org.matrix.custom.html" && !!content.formatted_body;
const isFormattedBody = content.format === "org.matrix.custom.html" && typeof content.formatted_body === "string";
let bodyHasEmoji = false;
let isHtmlMessage = false;

Expand All @@ -514,7 +514,7 @@ export function bodyToHtml(content: IContent, highlights: Optional<string[]>, op
}

let strippedBody: string;
let safeBody: string; // safe, sanitised HTML, preferred over `strippedBody` which is fully plaintext
let safeBody: string | undefined; // safe, sanitised HTML, preferred over `strippedBody` which is fully plaintext

try {
// sanitizeHtml can hang if an unclosed HTML tag is thrown at it
Expand All @@ -529,7 +529,7 @@ export function bodyToHtml(content: IContent, highlights: Optional<string[]>, op

if (opts.stripReplyFallback && formattedBody) formattedBody = stripHTMLReply(formattedBody);
strippedBody = opts.stripReplyFallback ? stripPlainReply(plainBody) : plainBody;
bodyHasEmoji = mightContainEmoji(isFormattedBody ? formattedBody : plainBody);
bodyHasEmoji = mightContainEmoji(isFormattedBody ? formattedBody! : plainBody);

const highlighter = safeHighlights?.length
? new HtmlHighlighter("mx_EventTile_searchHighlight", opts.highlightLink)
Expand All @@ -543,11 +543,11 @@ export function bodyToHtml(content: IContent, highlights: Optional<string[]>, op
// by an attempt to search for 'foobar'. Then again, the search query probably wouldn't work either
// XXX: hacky bodge to temporarily apply a textFilter to the sanitizeParams structure.
sanitizeParams.textFilter = function (safeText) {
return highlighter.applyHighlights(safeText, safeHighlights).join("");
return highlighter.applyHighlights(safeText, safeHighlights!).join("");
};
}

safeBody = sanitizeHtml(formattedBody, sanitizeParams);
safeBody = sanitizeHtml(formattedBody!, sanitizeParams);
const phtml = cheerio.load(safeBody, {
// @ts-ignore: The `_useHtmlParser2` internal option is the
// simplest way to both parse and render using `htmlparser2`.
Expand All @@ -574,7 +574,7 @@ export function bodyToHtml(content: IContent, highlights: Optional<string[]>, op
safeBody = formatEmojis(safeBody, true).join("");
}
} else if (highlighter) {
safeBody = highlighter.applyHighlights(plainBody, safeHighlights).join("");
safeBody = highlighter.applyHighlights(plainBody, safeHighlights!).join("");
}
} finally {
delete sanitizeParams.textFilter;
Expand All @@ -597,9 +597,7 @@ export function bodyToHtml(content: IContent, highlights: Optional<string[]>, op

const match = BIGEMOJI_REGEX.exec(contentBodyTrimmed);
emojiBody =
match &&
match[0] &&
match[0].length === contentBodyTrimmed.length &&
match?.[0]?.length === contentBodyTrimmed.length &&
// Prevent user pills expanding for users with only emoji in
// their username. Permalinks (links in pills) can be any URL
// now, so we just check for an HTTP-looking thing.
Expand All @@ -614,7 +612,7 @@ export function bodyToHtml(content: IContent, highlights: Optional<string[]>, op
"markdown-body": isHtmlMessage && !emojiBody,
});

let emojiBodyElements: JSX.Element[];
let emojiBodyElements: JSX.Element[] | undefined;
if (!safeBody && bodyHasEmoji) {
emojiBodyElements = formatEmojis(strippedBody, false) as JSX.Element[];
}
Expand Down Expand Up @@ -649,18 +647,18 @@ export function topicToHtml(
allowExtendedHtml = false,
): ReactNode {
if (!SettingsStore.getValue("feature_html_topic")) {
htmlTopic = null;
htmlTopic = undefined;
}

let isFormattedTopic = !!htmlTopic;
let topicHasEmoji = false;
let safeTopic = "";

try {
topicHasEmoji = mightContainEmoji(isFormattedTopic ? htmlTopic : topic);
topicHasEmoji = mightContainEmoji(isFormattedTopic ? htmlTopic! : topic);

if (isFormattedTopic) {
safeTopic = sanitizeHtml(htmlTopic, allowExtendedHtml ? sanitizeHtmlParams : topicSanitizeHtmlParams);
safeTopic = sanitizeHtml(htmlTopic!, allowExtendedHtml ? sanitizeHtmlParams : topicSanitizeHtmlParams);
if (topicHasEmoji) {
safeTopic = formatEmojis(safeTopic, true).join("");
}
Expand All @@ -669,7 +667,7 @@ export function topicToHtml(
isFormattedTopic = false; // Fall back to plain-text topic
}

let emojiBodyElements: ReturnType<typeof formatEmojis>;
let emojiBodyElements: ReturnType<typeof formatEmojis> | undefined;
if (!isFormattedTopic && topicHasEmoji) {
emojiBodyElements = formatEmojis(topic, false);
}
Expand Down
4 changes: 2 additions & 2 deletions src/Markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ export default class Markdown {
*/
private repairLinks(parsed: commonmark.Node): commonmark.Node {
const walker = parsed.walker();
let event: commonmark.NodeWalkingStep = null;
let event: commonmark.NodeWalkingStep | null = null;
let text = "";
let isInPara = false;
let previousNode: commonmark.Node | null = null;
Expand Down Expand Up @@ -287,7 +287,7 @@ export default class Markdown {
// However, if it's a blockquote, adds a p tag anyway
// in order to avoid deviation to commonmark and unexpected
// results when parsing the formatted HTML.
if (node.parent.type === "block_quote" || isMultiLine(node)) {
if (node.parent?.type === "block_quote" || isMultiLine(node)) {
realParagraph.call(this, node, entering);
}
};
Expand Down
2 changes: 1 addition & 1 deletion src/NodeAnimator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ export default class NodeAnimator extends React.Component<IProps> {
this.nodes[k] = node;
}

public render(): JSX.Element {
public render(): React.ReactNode {
return <>{Object.values(this.children)}</>;
}
}
2 changes: 1 addition & 1 deletion src/PosthogTrackers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ export class PosthogScreenTracker extends PureComponent<{ screenName: ScreenName
PosthogTrackers.instance.clearOverride(this.props.screenName);
}

public render(): JSX.Element {
public render(): React.ReactNode {
return null; // no need to render anything, we just need to hook into the React lifecycle
}
}
10 changes: 5 additions & 5 deletions src/Presence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ enum State {
}

class Presence {
private unavailableTimer: Timer = null;
private dispatcherRef: string = null;
private state: State = null;
private unavailableTimer: Timer | null = null;
private dispatcherRef: string | null = null;
private state: State | null = null;

/**
* Start listening the user activity to evaluate his presence state.
Expand Down Expand Up @@ -73,14 +73,14 @@ class Presence {
* Get the current presence state.
* @returns {string} the presence state (see PRESENCE enum)
*/
public getState(): State {
public getState(): State | null {
return this.state;
}

private onAction = (payload: ActionPayload): void => {
if (payload.action === "user_activity") {
this.setState(State.Online);
this.unavailableTimer.restart();
this.unavailableTimer?.restart();
}
};

Expand Down
2 changes: 1 addition & 1 deletion src/Resend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export default class Resend {
}

public static resend(event: MatrixEvent): Promise<void> {
const room = MatrixClientPeg.get().getRoom(event.getRoomId());
const room = MatrixClientPeg.get().getRoom(event.getRoomId())!;
return MatrixClientPeg.get()
.resendEvent(event, room)
.then(
Expand Down
2 changes: 1 addition & 1 deletion src/RoomAliasCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,6 @@ export function storeRoomAliasInCache(alias: string, id: string): void {
aliasToIDMap.set(alias, id);
}

export function getCachedRoomIDForAlias(alias: string): string {
export function getCachedRoomIDForAlias(alias: string): string | undefined {
return aliasToIDMap.get(alias);
}
6 changes: 3 additions & 3 deletions src/RoomInvite.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ export function inviteUsersToRoom(
): Promise<void> {
return inviteMultipleToRoom(roomId, userIds, sendSharedHistoryKeys, progressCallback)
.then((result) => {
const room = MatrixClientPeg.get().getRoom(roomId);
const room = MatrixClientPeg.get().getRoom(roomId)!;
showAnyInviteErrors(result.states, room, result.inviter);
})
.catch((err) => {
Expand Down Expand Up @@ -175,14 +175,14 @@ export function showAnyInviteErrors(
<BaseAvatar
url={avatarUrl ? mediaFromMxc(avatarUrl).getSquareThumbnailHttp(24) : null}
name={name}
idName={user.userId}
idName={user?.userId}
width={36}
height={36}
/>
</div>
<div className="mx_InviteDialog_tile_nameStack">
<span className="mx_InviteDialog_tile_nameStack_name">{name}</span>
<span className="mx_InviteDialog_tile_nameStack_userId">{user.userId}</span>
<span className="mx_InviteDialog_tile_nameStack_userId">{user?.userId}</span>
</div>
<div className="mx_InviteDialog_tile--inviterError_errorText">
{inviter.getErrorText(addr)}
Expand Down
6 changes: 3 additions & 3 deletions src/RoomNotifs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export function getRoomNotifsState(client: MatrixClient, roomId: string): RoomNo
}

// for everything else, look at the room rule.
let roomRule = null;
let roomRule: IPushRule | undefined;
try {
roomRule = client.getRoomPushRule("global", roomId);
} catch (err) {
Expand Down Expand Up @@ -106,7 +106,7 @@ export function getUnreadNotificationCount(room: Room, type: NotificationCountTy

function setRoomNotifsStateMuted(roomId: string): Promise<any> {
const cli = MatrixClientPeg.get();
const promises = [];
const promises: Promise<unknown>[] = [];

// delete the room rule
const roomRule = cli.getRoomPushRule("global", roomId);
Expand Down Expand Up @@ -137,7 +137,7 @@ function setRoomNotifsStateMuted(roomId: string): Promise<any> {

function setRoomNotifsStateUnmuted(roomId: string, newState: RoomNotifState): Promise<any> {
const cli = MatrixClientPeg.get();
const promises = [];
const promises: Promise<unknown>[] = [];

const overrideMuteRule = findOverrideMuteRule(roomId);
if (overrideMuteRule) {
Expand Down
10 changes: 5 additions & 5 deletions src/Rooms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,13 @@ import AliasCustomisations from "./customisations/Alias";
* @param {Object} room The room object
* @returns {string} A display alias for the given room
*/
export function getDisplayAliasForRoom(room: Room): string | undefined {
export function getDisplayAliasForRoom(room: Room): string | null {
return getDisplayAliasForAliasSet(room.getCanonicalAlias(), room.getAltAliases());
}

// The various display alias getters should all feed through this one path so
// there's a single place to change the logic.
export function getDisplayAliasForAliasSet(canonicalAlias: string, altAliases: string[]): string {
export function getDisplayAliasForAliasSet(canonicalAlias: string | null, altAliases: string[]): string | null {
if (AliasCustomisations.getDisplayAliasForAliasSet) {
return AliasCustomisations.getDisplayAliasForAliasSet(canonicalAlias, altAliases);
}
Expand All @@ -45,7 +45,7 @@ export function getDisplayAliasForAliasSet(canonicalAlias: string, altAliases: s
export function guessAndSetDMRoom(room: Room, isDirect: boolean): Promise<void> {
let newTarget;
if (isDirect) {
const guessedUserId = guessDMRoomTargetId(room, MatrixClientPeg.get().getUserId());
const guessedUserId = guessDMRoomTargetId(room, MatrixClientPeg.get().getUserId()!);
newTarget = guessedUserId;
} else {
newTarget = null;
Expand Down Expand Up @@ -118,7 +118,7 @@ function guessDMRoomTargetId(room: Room, myUserId: string): string {

if (oldestTs === undefined || (user.events.member && user.events.member.getTs() < oldestTs)) {
oldestUser = user;
oldestTs = user.events.member.getTs();
oldestTs = user.events.member?.getTs();
}
}
if (oldestUser) return oldestUser.userId;
Expand All @@ -129,7 +129,7 @@ function guessDMRoomTargetId(room: Room, myUserId: string): string {

if (oldestTs === undefined || (user.events.member && user.events.member.getTs() < oldestTs)) {
oldestUser = user;
oldestTs = user.events.member.getTs();
oldestTs = user.events.member?.getTs();
}
}

Expand Down
12 changes: 6 additions & 6 deletions src/VoipUserMapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,9 @@ export default class VoipUserMapper {
* Gets the ID of the virtual room for a room, or null if the room has no
* virtual room
*/
public async getVirtualRoomForRoom(roomId: string): Promise<Room | null> {
public async getVirtualRoomForRoom(roomId: string): Promise<Room | undefined> {
const virtualUser = await this.getVirtualUserForRoom(roomId);
if (!virtualUser) return null;
if (!virtualUser) return undefined;

return findDMForUser(MatrixClientPeg.get(), virtualUser);
}
Expand Down Expand Up @@ -145,11 +145,11 @@ export default class VoipUserMapper {
// (possibly we should only join if we've also joined the native room, then we'd also have
// to make sure we joined virtual rooms on joining a native one)
MatrixClientPeg.get().joinRoom(invitedRoom.roomId);
}

// also put this room in the virtual room ID cache so isVirtualRoom return the right answer
// in however long it takes for the echo of setAccountData to come down the sync
this.virtualToNativeRoomIdCache.set(invitedRoom.roomId, nativeRoom.roomId);
// also put this room in the virtual room ID cache so isVirtualRoom return the right answer
// in however long it takes for the echo of setAccountData to come down the sync
this.virtualToNativeRoomIdCache.set(invitedRoom.roomId, nativeRoom.roomId);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ export default class ManageEventIndexDialog extends React.Component<IProps, ISta
SettingsStore.setValue("crawlerSleepTime", null, SettingLevel.DEVICE, e.target.value);
};

public render(): JSX.Element {
public render(): React.ReactNode {
const brand = SdkConfig.get().brand;

let crawlerState;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -459,7 +459,7 @@ export default class CreateKeyBackupDialog extends React.PureComponent<IProps, I
}
}

public render(): JSX.Element {
public render(): React.ReactNode {
let content;
if (this.state.error) {
content = (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -842,7 +842,7 @@ export default class CreateSecretStorageDialog extends React.PureComponent<IProp
}
}

public render(): JSX.Element {
public render(): React.ReactNode {
let content;
if (this.state.error) {
content = (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ export default class ExportE2eKeysDialog extends React.Component<IProps, IState>
} as Pick<IState, AnyPassphrase>);
};

public render(): JSX.Element {
public render(): React.ReactNode {
const disableForm = this.state.phase === Phase.Exporting;

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ export default class ImportE2eKeysDialog extends React.Component<IProps, IState>
return false;
};

public render(): JSX.Element {
public render(): React.ReactNode {
const disableForm = this.state.phase !== Phase.Edit;

return (
Expand Down
Loading

0 comments on commit da7aa40

Please sign in to comment.