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

Conform more of the codebase to strictNullChecks (#10505 #10505

Merged
merged 7 commits into from
Apr 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/LegacyCallHandler.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -905,7 +905,7 @@ export default class LegacyCallHandler extends EventEmitter {

const timeUntilTurnCresExpire = MatrixClientPeg.get().getTurnServersExpiry() - Date.now();
logger.log("Current turn creds expire in " + timeUntilTurnCresExpire + " ms");
const call = MatrixClientPeg.get().createCall(mappedRoomId);
const call = MatrixClientPeg.get().createCall(mappedRoomId)!;

try {
this.addCallForRoom(roomId, call);
Expand Down
4 changes: 2 additions & 2 deletions src/MatrixClientPeg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -332,15 +332,15 @@ class MatrixClientPegClass implements IMatrixClientPeg {

homeserverUrl: this.matrixClient.baseUrl,
identityServerUrl: this.matrixClient.idBaseUrl,
userId: this.matrixClient.credentials.userId,
userId: this.matrixClient.getSafeUserId(),
deviceId: this.matrixClient.getDeviceId() ?? undefined,
accessToken: this.matrixClient.getAccessToken(),
guest: this.matrixClient.isGuest(),
};
}

public getHomeserverName(): string {
const matches = /^@[^:]+:(.+)$/.exec(this.matrixClient.credentials.userId);
const matches = /^@[^:]+:(.+)$/.exec(this.matrixClient.getSafeUserId());
if (matches === null || matches.length < 1) {
throw new Error("Failed to derive homeserver name from user ID!");
}
Expand Down
2 changes: 1 addition & 1 deletion src/components/structures/SpaceHierarchy.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ const Tile: React.FC<ITileProps> = ({
}) => {
const cli = useContext(MatrixClientContext);
const [joinedRoom, setJoinedRoom] = useState<Room | undefined>(() => {
const cliRoom = cli.getRoom(room.room_id);
const cliRoom = cli?.getRoom(room.room_id);
return cliRoom?.getMyMembership() === "join" ? cliRoom : undefined;
});
const joinedRoomName = useTypedEventEmitterState(joinedRoom, RoomEvent.Name, (room) => room?.name);
Expand Down
34 changes: 17 additions & 17 deletions src/components/structures/TimelinePanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ import { ClientEvent } from "matrix-js-sdk/src/client";
import { Thread, ThreadEvent } from "matrix-js-sdk/src/models/thread";
import { ReceiptType } from "matrix-js-sdk/src/@types/read_receipts";
import { MatrixError } from "matrix-js-sdk/src/http-api";
import { ReadReceipt } from "matrix-js-sdk/src/models/read-receipt";
import { Relations } from "matrix-js-sdk/src/models/relations";

import SettingsStore from "../../settings/SettingsStore";
Expand Down Expand Up @@ -515,23 +514,22 @@ class TimelinePanel extends React.Component<IProps, IState> {

if (count > 0) {
debuglog("Unpaginating", count, "in direction", dir);
this.timelineWindow.unpaginate(count, backwards);
this.timelineWindow?.unpaginate(count, backwards);

const { events, liveEvents, firstVisibleEventIndex } = this.getEvents();
this.buildLegacyCallEventGroupers(events);
const newState: Partial<IState> = {
this.setState({
events,
liveEvents,
firstVisibleEventIndex,
};
});

// We can now paginate in the unpaginated direction
if (backwards) {
newState.canBackPaginate = true;
this.setState({ canBackPaginate: true });
} else {
newState.canForwardPaginate = true;
this.setState({ canForwardPaginate: true });
}
this.setState<null>(newState);
}
};

Expand Down Expand Up @@ -636,6 +634,7 @@ class TimelinePanel extends React.Component<IProps, IState> {
private doManageReadMarkers = debounce(
() => {
const rmPosition = this.getReadMarkerPosition();
if (rmPosition === null) return;
// we hide the read marker when it first comes onto the screen, but if
// it goes back off the top of the screen (presumably because the user
// clicks on the 'jump to bottom' button), we need to re-enable it.
Expand Down Expand Up @@ -1125,7 +1124,7 @@ class TimelinePanel extends React.Component<IProps, IState> {
return;
}
const lastDisplayedEvent = this.state.events[lastDisplayedIndex];
this.setReadMarker(lastDisplayedEvent.getId(), lastDisplayedEvent.getTs());
this.setReadMarker(lastDisplayedEvent.getId()!, lastDisplayedEvent.getTs());

// the read-marker should become invisible, so that if the user scrolls
// down, they don't see it.
Expand All @@ -1141,7 +1140,7 @@ class TimelinePanel extends React.Component<IProps, IState> {

// advance the read marker past any events we sent ourselves.
private advanceReadMarkerPastMyEvents(): void {
if (!this.props.manageReadMarkers) return;
if (!this.props.manageReadMarkers || !this.timelineWindow) return;

// we call `timelineWindow.getEvents()` rather than using
// `this.state.liveEvents`, because React batches the update to the
Expand Down Expand Up @@ -1171,7 +1170,7 @@ class TimelinePanel extends React.Component<IProps, IState> {
i--;

const ev = events[i];
this.setReadMarker(ev.getId(), ev.getTs());
this.setReadMarker(ev.getId()!, ev.getTs());
}

/* jump down to the bottom of this room, where new events are arriving
Expand Down Expand Up @@ -1280,6 +1279,7 @@ class TimelinePanel extends React.Component<IProps, IState> {
public getReadMarkerPosition = (): number | null => {
if (!this.props.manageReadMarkers) return null;
if (!this.messagePanel.current) return null;
if (!this.props.timelineSet.room) return null;

const ret = this.messagePanel.current.getReadMarkerPosition();
if (ret !== null) {
Expand Down Expand Up @@ -1629,7 +1629,7 @@ class TimelinePanel extends React.Component<IProps, IState> {
return 0;
}

const userId = cli.credentials.userId;
const userId = cli.getSafeUserId();

// get the user's membership at the last event by getting the timeline
// that the event belongs to, and traversing the timeline looking for
Expand All @@ -1648,7 +1648,7 @@ class TimelinePanel extends React.Component<IProps, IState> {
continue;
}

userMembership = timeline.getState(EventTimeline.FORWARDS).getMember(userId)?.membership ?? "leave";
userMembership = timeline.getState(EventTimeline.FORWARDS)?.getMember(userId)?.membership ?? "leave";
const timelineEvents = timeline.getEvents();
for (let j = timelineEvents.length - 1; j >= 0; j--) {
const event = timelineEvents[j];
Expand Down Expand Up @@ -1769,7 +1769,7 @@ class TimelinePanel extends React.Component<IProps, IState> {
for (let i = this.state.liveEvents.length - 1; i >= 0; --i) {
const ev = this.state.liveEvents[i];

const node = messagePanel.getNodeForEventId(ev.getId());
const node = messagePanel.getNodeForEventId(ev.getId()!);
const isInView = isNodeInView(node);

// when we've reached the first visible event, and the previous
Expand Down Expand Up @@ -1829,8 +1829,8 @@ class TimelinePanel extends React.Component<IProps, IState> {
}

const myUserId = client.getSafeUserId();
const receiptStore: ReadReceipt<any, any> = this.props.timelineSet.thread ?? this.props.timelineSet.room;
return receiptStore?.getEventReadUpTo(myUserId, ignoreSynthesized);
const receiptStore = this.props.timelineSet.thread ?? this.props.timelineSet.room;
return receiptStore?.getEventReadUpTo(myUserId, ignoreSynthesized) ?? null;
}

private setReadMarker(eventId: string | null, eventTs: number, inhibitSetState = false): void {
Expand Down Expand Up @@ -1924,7 +1924,7 @@ class TimelinePanel extends React.Component<IProps, IState> {
// If the state is PREPARED or CATCHUP, we're still waiting for the js-sdk to sync with
// the HS and fetch the latest events, so we are effectively forward paginating.
const forwardPaginating =
this.state.forwardPaginating || ["PREPARED", "CATCHUP"].includes(this.state.clientSyncState);
this.state.forwardPaginating || ["PREPARED", "CATCHUP"].includes(this.state.clientSyncState!);
const events = this.state.firstVisibleEventIndex
? this.state.events.slice(this.state.firstVisibleEventIndex)
: this.state.events;
Expand Down Expand Up @@ -1985,7 +1985,7 @@ function serializeEventIdsFromTimelineSets(timelineSets: EventTimelineSet[]): {
// Add a special label when it is the live timeline so we can tell
// it apart from the others
const isLiveTimeline = timeline === liveTimeline;
timelineMap[isLiveTimeline ? "liveTimeline" : `${index}`] = timeline.getEvents().map((ev) => ev.getId());
timelineMap[isLiveTimeline ? "liveTimeline" : `${index}`] = timeline.getEvents().map((ev) => ev.getId()!);
});

return timelineMap;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ export const RoomGeneralContextMenu: React.FC<RoomGeneralContextMenuProps> = ({
};

const onTagRoom = (ev: ButtonEvent, tagId: TagID): void => {
if (!cli) return;
if (tagId === DefaultTagID.Favourite || tagId === DefaultTagID.LowPriority) {
const inverseTag = tagId === DefaultTagID.Favourite ? DefaultTagID.LowPriority : DefaultTagID.Favourite;
const isApplied = RoomListStore.instance.getTagsForRoom(room).includes(tagId);
Expand Down
13 changes: 8 additions & 5 deletions src/components/views/dialogs/AddExistingToSpaceDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

import React, { ReactElement, ReactNode, useContext, useMemo, useRef, useState } from "react";
import React, { ReactElement, ReactNode, RefObject, useContext, useMemo, useRef, useState } from "react";
import classNames from "classnames";
import { Room } from "matrix-js-sdk/src/models/room";
import { sleep } from "matrix-js-sdk/src/utils";
Expand Down Expand Up @@ -140,11 +140,12 @@ export const AddExistingToSpace: React.FC<IAddExistingToSpaceProps> = ({
const cli = useContext(MatrixClientContext);
const msc3946ProcessDynamicPredecessor = useSettingValue<boolean>("feature_dynamic_room_predecessors");
const visibleRooms = useMemo(
() => cli.getVisibleRooms(msc3946ProcessDynamicPredecessor).filter((r) => r.getMyMembership() === "join"),
() =>
cli?.getVisibleRooms(msc3946ProcessDynamicPredecessor).filter((r) => r.getMyMembership() === "join") ?? [],
[cli, msc3946ProcessDynamicPredecessor],
);

const scrollRef = useRef<AutoHideScrollbar<"div">>();
const scrollRef = useRef() as RefObject<AutoHideScrollbar<"div">>;
const [scrollState, setScrollState] = useState<IScrollState>({
// these are estimates which update as soon as it mounts
scrollTop: 0,
Expand Down Expand Up @@ -212,7 +213,7 @@ export const AddExistingToSpace: React.FC<IAddExistingToSpaceProps> = ({

throw e;
});
setProgress((i) => i + 1);
setProgress((i) => (i ?? 0) + 1);
} catch (e) {
logger.error("Failed to add rooms to space", e);
error = e;
Expand Down Expand Up @@ -305,13 +306,15 @@ export const AddExistingToSpace: React.FC<IAddExistingToSpaceProps> = ({

const onScroll = (): void => {
const body = scrollRef.current?.containerRef.current;
if (!body) return;
setScrollState({
scrollTop: body.scrollTop,
height: body.clientHeight,
});
};

const wrappedRef = (body: HTMLDivElement): void => {
const wrappedRef = (body: HTMLDivElement | null): void => {
if (!body) return;
setScrollState({
scrollTop: body.scrollTop,
height: body.clientHeight,
Expand Down
4 changes: 2 additions & 2 deletions src/components/views/dialogs/ConfirmAndWaitRedactDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ interface IProps {

interface IState {
isRedacting: boolean;
redactionErrorCode: string | number;
redactionErrorCode: string | number | null;
}

/*
Expand All @@ -53,7 +53,7 @@ export default class ConfirmAndWaitRedactDialog extends React.PureComponent<IPro
};
}

public onParentFinished = async (proceed: boolean): Promise<void> => {
public onParentFinished = async (proceed?: boolean): Promise<void> => {
if (proceed) {
this.setState({ isRedacting: true });
try {
Expand Down
5 changes: 3 additions & 2 deletions src/components/views/dialogs/ConfirmRedactDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ import ErrorDialog from "./ErrorDialog";
import TextInputDialog from "./TextInputDialog";

interface IProps {
onFinished: (success: boolean) => void;
onFinished(success?: false, reason?: void): void;
onFinished(success: true, reason?: string): void;
}

/*
Expand Down Expand Up @@ -67,7 +68,7 @@ export function createRedactEventDialog({
Modal.createDialog(
ConfirmRedactDialog,
{
onFinished: async (proceed: boolean, reason?: string): Promise<void> => {
onFinished: async (proceed, reason): Promise<void> => {
if (!proceed) return;

const cli = MatrixClientPeg.get();
Expand Down
14 changes: 7 additions & 7 deletions src/components/views/dialogs/ExportDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

import React, { useRef, useState, Dispatch, SetStateAction } from "react";
import React, { useRef, useState, Dispatch, SetStateAction, RefObject } from "react";
import { Room } from "matrix-js-sdk/src/matrix";
import { logger } from "matrix-js-sdk/src/logger";

Expand Down Expand Up @@ -104,8 +104,8 @@ const ExportDialog: React.FC<IProps> = ({ room, onFinished }) => {
} = useExportFormState();

const [isExporting, setExporting] = useState(false);
const sizeLimitRef = useRef<Field>();
const messageCountRef = useRef<Field>();
const sizeLimitRef = useRef() as RefObject<Field>;
const messageCountRef = useRef() as RefObject<Field>;
const [exportProgressText, setExportProgressText] = useState(_t("Processing…"));
const [displayCancel, setCancelWarning] = useState(false);
const [exportCancelled, setExportCancelled] = useState(false);
Expand Down Expand Up @@ -144,18 +144,18 @@ const ExportDialog: React.FC<IProps> = ({ room, onFinished }) => {
const onExportClick = async (): Promise<void> => {
const isValidSize =
!setSizeLimit ||
(await sizeLimitRef.current.validate({
(await sizeLimitRef.current?.validate({
focused: false,
}));

if (!isValidSize) {
sizeLimitRef.current.validate({ focused: true });
sizeLimitRef.current?.validate({ focused: true });
return;
}
if (exportType === ExportType.LastNMessages) {
const isValidNumberOfMessages = await messageCountRef.current.validate({ focused: false });
const isValidNumberOfMessages = await messageCountRef.current?.validate({ focused: false });
if (!isValidNumberOfMessages) {
messageCountRef.current.validate({ focused: true });
messageCountRef.current?.validate({ focused: true });
return;
}
}
Expand Down
Loading