Skip to content

Commit e5a3146

Browse files
authored
Conform more of the codebase to strictNullChecks (matrix-org#10505
* Conform more of the codebase to `strictNullChecks` * Iterate * Conform more of the codebase to `strictNullChecks` * Iterate * Iterate * Iterate * Iterate
1 parent 7503bf6 commit e5a3146

21 files changed

+76
-83
lines changed

src/MatrixClientPeg.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -332,15 +332,15 @@ class MatrixClientPegClass implements IMatrixClientPeg {
332332

333333
homeserverUrl: this.matrixClient.baseUrl,
334334
identityServerUrl: this.matrixClient.idBaseUrl,
335-
userId: this.matrixClient.credentials.userId,
335+
userId: this.matrixClient.getSafeUserId(),
336336
deviceId: this.matrixClient.getDeviceId() ?? undefined,
337337
accessToken: this.matrixClient.getAccessToken(),
338338
guest: this.matrixClient.isGuest(),
339339
};
340340
}
341341

342342
public getHomeserverName(): string {
343-
const matches = /^@[^:]+:(.+)$/.exec(this.matrixClient.credentials.userId);
343+
const matches = /^@[^:]+:(.+)$/.exec(this.matrixClient.getSafeUserId());
344344
if (matches === null || matches.length < 1) {
345345
throw new Error("Failed to derive homeserver name from user ID!");
346346
}

src/components/structures/SpaceHierarchy.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ const Tile: React.FC<ITileProps> = ({
102102
}) => {
103103
const cli = useContext(MatrixClientContext);
104104
const [joinedRoom, setJoinedRoom] = useState<Room | undefined>(() => {
105-
const cliRoom = cli.getRoom(room.room_id);
105+
const cliRoom = cli?.getRoom(room.room_id);
106106
return cliRoom?.getMyMembership() === "join" ? cliRoom : undefined;
107107
});
108108
const joinedRoomName = useTypedEventEmitterState(joinedRoom, RoomEvent.Name, (room) => room?.name);

src/components/structures/TimelinePanel.tsx

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,6 @@ import { ClientEvent } from "matrix-js-sdk/src/client";
3030
import { Thread, ThreadEvent } from "matrix-js-sdk/src/models/thread";
3131
import { ReceiptType } from "matrix-js-sdk/src/@types/read_receipts";
3232
import { MatrixError } from "matrix-js-sdk/src/http-api";
33-
import { ReadReceipt } from "matrix-js-sdk/src/models/read-receipt";
3433
import { Relations } from "matrix-js-sdk/src/models/relations";
3534

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

516515
if (count > 0) {
517516
debuglog("Unpaginating", count, "in direction", dir);
518-
this.timelineWindow.unpaginate(count, backwards);
517+
this.timelineWindow?.unpaginate(count, backwards);
519518

520519
const { events, liveEvents, firstVisibleEventIndex } = this.getEvents();
521520
this.buildLegacyCallEventGroupers(events);
522-
const newState: Partial<IState> = {
521+
this.setState({
523522
events,
524523
liveEvents,
525524
firstVisibleEventIndex,
526-
};
525+
});
527526

528527
// We can now paginate in the unpaginated direction
529528
if (backwards) {
530-
newState.canBackPaginate = true;
529+
this.setState({ canBackPaginate: true });
531530
} else {
532-
newState.canForwardPaginate = true;
531+
this.setState({ canForwardPaginate: true });
533532
}
534-
this.setState<null>(newState);
535533
}
536534
};
537535

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

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

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

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

11731172
const ev = events[i];
1174-
this.setReadMarker(ev.getId(), ev.getTs());
1173+
this.setReadMarker(ev.getId()!, ev.getTs());
11751174
}
11761175

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

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

1632-
const userId = cli.credentials.userId;
1632+
const userId = cli.getSafeUserId();
16331633

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

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

1772-
const node = messagePanel.getNodeForEventId(ev.getId());
1772+
const node = messagePanel.getNodeForEventId(ev.getId()!);
17731773
const isInView = isNodeInView(node);
17741774

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

18311831
const myUserId = client.getSafeUserId();
1832-
const receiptStore: ReadReceipt<any, any> = this.props.timelineSet.thread ?? this.props.timelineSet.room;
1833-
return receiptStore?.getEventReadUpTo(myUserId, ignoreSynthesized);
1832+
const receiptStore = this.props.timelineSet.thread ?? this.props.timelineSet.room;
1833+
return receiptStore?.getEventReadUpTo(myUserId, ignoreSynthesized) ?? null;
18341834
}
18351835

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

19911991
return timelineMap;

src/components/views/context_menus/RoomGeneralContextMenu.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ export const RoomGeneralContextMenu: React.FC<RoomGeneralContextMenuProps> = ({
8989
};
9090

9191
const onTagRoom = (ev: ButtonEvent, tagId: TagID): void => {
92+
if (!cli) return;
9293
if (tagId === DefaultTagID.Favourite || tagId === DefaultTagID.LowPriority) {
9394
const inverseTag = tagId === DefaultTagID.Favourite ? DefaultTagID.LowPriority : DefaultTagID.Favourite;
9495
const isApplied = RoomListStore.instance.getTagsForRoom(room).includes(tagId);

src/components/views/dialogs/ConfirmAndWaitRedactDialog.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ export default class ConfirmAndWaitRedactDialog extends React.PureComponent<IPro
5353
};
5454
}
5555

56-
public onParentFinished = async (proceed: boolean): Promise<void> => {
56+
public onParentFinished = async (proceed?: boolean): Promise<void> => {
5757
if (proceed) {
5858
this.setState({ isRedacting: true });
5959
try {

src/components/views/dialogs/ConfirmRedactDialog.tsx

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@ import ErrorDialog from "./ErrorDialog";
2626
import TextInputDialog from "./TextInputDialog";
2727

2828
interface IProps {
29-
onFinished: (success: boolean) => void;
29+
onFinished(success?: false, reason?: void): void;
30+
onFinished(success: true, reason?: string): void;
3031
}
3132

3233
/*
@@ -67,7 +68,7 @@ export function createRedactEventDialog({
6768
Modal.createDialog(
6869
ConfirmRedactDialog,
6970
{
70-
onFinished: async (proceed: boolean, reason?: string): Promise<void> => {
71+
onFinished: async (proceed, reason): Promise<void> => {
7172
if (!proceed) return;
7273

7374
const cli = MatrixClientPeg.get();

src/components/views/dialogs/KeySignatureUploadFailedDialog.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ const KeySignatureUploadFailedDialog: React.FC<IProps> = ({ failures, source, co
7272
}, [continuation, onFinished]);
7373

7474
let body;
75-
if (!success && !cancelled && continuation && retry > 0) {
75+
if (!success && !cancelled && retry > 0) {
7676
const reason = causes.get(source) || defaultCause;
7777
const brand = SdkConfig.get().brand;
7878

src/components/views/dialogs/MessageEditHistoryDialog.tsx

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import { EventType, RelationType } from "matrix-js-sdk/src/@types/event";
2020
import { defer } from "matrix-js-sdk/src/utils";
2121
import { logger } from "matrix-js-sdk/src/logger";
2222
import { MatrixClient } from "matrix-js-sdk/src/client";
23+
import { MatrixError } from "matrix-js-sdk/src/http-api";
2324

2425
import { MatrixClientPeg } from "../../../MatrixClientPeg";
2526
import { _t } from "../../../languageHandler";
@@ -37,12 +38,10 @@ interface IProps {
3738
}
3839

3940
interface IState {
40-
originalEvent: MatrixEvent;
41-
error: {
42-
errcode: string;
43-
};
41+
originalEvent: MatrixEvent | null;
42+
error: MatrixError | null;
4443
events: MatrixEvent[];
45-
nextBatch: string;
44+
nextBatch: string | null;
4645
isLoading: boolean;
4746
isTwelveHour: boolean;
4847
}
@@ -65,9 +64,9 @@ export default class MessageEditHistoryDialog extends React.PureComponent<IProps
6564
// bail out on backwards as we only paginate in one direction
6665
return false;
6766
}
68-
const opts = { from: this.state.nextBatch };
69-
const roomId = this.props.mxEvent.getRoomId();
70-
const eventId = this.props.mxEvent.getId();
67+
const opts = { from: this.state.nextBatch ?? undefined };
68+
const roomId = this.props.mxEvent.getRoomId()!;
69+
const eventId = this.props.mxEvent.getId()!;
7170
const client = MatrixClientPeg.get();
7271

7372
const { resolve, reject, promise } = defer<boolean>();
@@ -80,17 +79,17 @@ export default class MessageEditHistoryDialog extends React.PureComponent<IProps
8079
if (error.errcode) {
8180
logger.error("fetching /relations failed with error", error);
8281
}
83-
this.setState({ error }, () => reject(error));
82+
this.setState({ error: error as MatrixError }, () => reject(error));
8483
return promise;
8584
}
8685

8786
const newEvents = result.events;
8887
this.locallyRedactEventsIfNeeded(newEvents);
8988
this.setState(
9089
{
91-
originalEvent: this.state.originalEvent || result.originalEvent,
90+
originalEvent: this.state.originalEvent ?? result.originalEvent ?? null,
9291
events: this.state.events.concat(newEvents),
93-
nextBatch: result.nextBatch,
92+
nextBatch: result.nextBatch ?? null,
9493
isLoading: false,
9594
},
9695
() => {
@@ -105,6 +104,7 @@ export default class MessageEditHistoryDialog extends React.PureComponent<IProps
105104
const roomId = this.props.mxEvent.getRoomId();
106105
const client = MatrixClientPeg.get();
107106
const room = client.getRoom(roomId);
107+
if (!room) return;
108108
const pendingEvents = room.getPendingEvents();
109109
for (const e of newEvents) {
110110
const pendingRedaction = pendingEvents.find((pe) => {
@@ -133,15 +133,15 @@ export default class MessageEditHistoryDialog extends React.PureComponent<IProps
133133
if (!lastEvent || wantsDateSeparator(lastEvent.getDate() || undefined, e.getDate() || undefined)) {
134134
nodes.push(
135135
<li key={e.getTs() + "~"}>
136-
<DateSeparator roomId={e.getRoomId()} ts={e.getTs()} />
136+
<DateSeparator roomId={e.getRoomId()!} ts={e.getTs()} />
137137
</li>,
138138
);
139139
}
140140
const isBaseEvent = e.getId() === baseEventId;
141141
nodes.push(
142142
<EditHistoryMessage
143143
key={e.getId()}
144-
previousEdit={!isBaseEvent ? allEvents[i + 1] : null}
144+
previousEdit={!isBaseEvent ? allEvents[i + 1] : undefined}
145145
isBaseEvent={isBaseEvent}
146146
mxEvent={e}
147147
isTwelveHour={this.state.isTwelveHour}

src/components/views/dialogs/ServerOfflineDialog.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
1414
limitations under the License.
1515
*/
1616

17-
import * as React from "react";
17+
import React, { ReactNode } from "react";
1818

1919
import BaseDialog from "./BaseDialog";
2020
import { _t } from "../../../languageHandler";
@@ -46,7 +46,7 @@ export default class ServerOfflineDialog extends React.PureComponent<IProps> {
4646
this.forceUpdate(); // no state to worry about
4747
};
4848

49-
private renderTimeline(): React.ReactElement[] {
49+
private renderTimeline(): ReactNode[] {
5050
return EchoStore.instance.contexts.map((c, i) => {
5151
if (!c.firstFailedTime) return null; // not useful
5252
if (!(c instanceof RoomEchoContext))

src/components/views/dialogs/SlidingSyncOptionsDialog.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ export const SlidingSyncOptionsDialog: React.FC<{ onFinished(enabled: boolean):
124124
value={currentProxy}
125125
button={_t("Enable")}
126126
validator={validProxy}
127-
onFinished={(enable: boolean, proxyUrl: string) => {
127+
onFinished={(enable, proxyUrl) => {
128128
if (enable) {
129129
SettingsStore.setValue("feature_sliding_sync_proxy_url", null, SettingLevel.DEVICE, proxyUrl);
130130
onFinished(true);

0 commit comments

Comments
 (0)