Conform more of the codebase to strictNullChecks (#10505

* Conform more of the codebase to `strictNullChecks`

* Iterate

* Conform more of the codebase to `strictNullChecks`

* Iterate

* Iterate

* Iterate

* Iterate
This commit is contained in:
Michael Telatynski 2023-04-05 09:02:40 +01:00 committed by GitHub
parent 7503bf6b96
commit e5a314617a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
21 changed files with 76 additions and 83 deletions

View file

@ -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);

View file

@ -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 {

View file

@ -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;
}
/*
@ -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();

View file

@ -72,7 +72,7 @@ const KeySignatureUploadFailedDialog: React.FC<IProps> = ({ failures, source, co
}, [continuation, onFinished]);
let body;
if (!success && !cancelled && continuation && retry > 0) {
if (!success && !cancelled && retry > 0) {
const reason = causes.get(source) || defaultCause;
const brand = SdkConfig.get().brand;

View file

@ -20,6 +20,7 @@ import { EventType, RelationType } from "matrix-js-sdk/src/@types/event";
import { defer } from "matrix-js-sdk/src/utils";
import { logger } from "matrix-js-sdk/src/logger";
import { MatrixClient } from "matrix-js-sdk/src/client";
import { MatrixError } from "matrix-js-sdk/src/http-api";
import { MatrixClientPeg } from "../../../MatrixClientPeg";
import { _t } from "../../../languageHandler";
@ -37,12 +38,10 @@ interface IProps {
}
interface IState {
originalEvent: MatrixEvent;
error: {
errcode: string;
};
originalEvent: MatrixEvent | null;
error: MatrixError | null;
events: MatrixEvent[];
nextBatch: string;
nextBatch: string | null;
isLoading: boolean;
isTwelveHour: boolean;
}
@ -65,9 +64,9 @@ export default class MessageEditHistoryDialog extends React.PureComponent<IProps
// bail out on backwards as we only paginate in one direction
return false;
}
const opts = { from: this.state.nextBatch };
const roomId = this.props.mxEvent.getRoomId();
const eventId = this.props.mxEvent.getId();
const opts = { from: this.state.nextBatch ?? undefined };
const roomId = this.props.mxEvent.getRoomId()!;
const eventId = this.props.mxEvent.getId()!;
const client = MatrixClientPeg.get();
const { resolve, reject, promise } = defer<boolean>();
@ -80,7 +79,7 @@ export default class MessageEditHistoryDialog extends React.PureComponent<IProps
if (error.errcode) {
logger.error("fetching /relations failed with error", error);
}
this.setState({ error }, () => reject(error));
this.setState({ error: error as MatrixError }, () => reject(error));
return promise;
}
@ -88,9 +87,9 @@ export default class MessageEditHistoryDialog extends React.PureComponent<IProps
this.locallyRedactEventsIfNeeded(newEvents);
this.setState(
{
originalEvent: this.state.originalEvent || result.originalEvent,
originalEvent: this.state.originalEvent ?? result.originalEvent ?? null,
events: this.state.events.concat(newEvents),
nextBatch: result.nextBatch,
nextBatch: result.nextBatch ?? null,
isLoading: false,
},
() => {
@ -105,6 +104,7 @@ export default class MessageEditHistoryDialog extends React.PureComponent<IProps
const roomId = this.props.mxEvent.getRoomId();
const client = MatrixClientPeg.get();
const room = client.getRoom(roomId);
if (!room) return;
const pendingEvents = room.getPendingEvents();
for (const e of newEvents) {
const pendingRedaction = pendingEvents.find((pe) => {
@ -133,7 +133,7 @@ export default class MessageEditHistoryDialog extends React.PureComponent<IProps
if (!lastEvent || wantsDateSeparator(lastEvent.getDate() || undefined, e.getDate() || undefined)) {
nodes.push(
<li key={e.getTs() + "~"}>
<DateSeparator roomId={e.getRoomId()} ts={e.getTs()} />
<DateSeparator roomId={e.getRoomId()!} ts={e.getTs()} />
</li>,
);
}
@ -141,7 +141,7 @@ export default class MessageEditHistoryDialog extends React.PureComponent<IProps
nodes.push(
<EditHistoryMessage
key={e.getId()}
previousEdit={!isBaseEvent ? allEvents[i + 1] : null}
previousEdit={!isBaseEvent ? allEvents[i + 1] : undefined}
isBaseEvent={isBaseEvent}
mxEvent={e}
isTwelveHour={this.state.isTwelveHour}

View file

@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import * as React from "react";
import React, { ReactNode } from "react";
import BaseDialog from "./BaseDialog";
import { _t } from "../../../languageHandler";
@ -46,7 +46,7 @@ export default class ServerOfflineDialog extends React.PureComponent<IProps> {
this.forceUpdate(); // no state to worry about
};
private renderTimeline(): React.ReactElement[] {
private renderTimeline(): ReactNode[] {
return EchoStore.instance.contexts.map((c, i) => {
if (!c.firstFailedTime) return null; // not useful
if (!(c instanceof RoomEchoContext))

View file

@ -124,7 +124,7 @@ export const SlidingSyncOptionsDialog: React.FC<{ onFinished(enabled: boolean):
value={currentProxy}
button={_t("Enable")}
validator={validProxy}
onFinished={(enable: boolean, proxyUrl: string) => {
onFinished={(enable, proxyUrl) => {
if (enable) {
SettingsStore.setValue("feature_sliding_sync_proxy_url", null, SettingLevel.DEVICE, proxyUrl);
onFinished(true);

View file

@ -33,7 +33,8 @@ interface IProps {
hasCancel: boolean;
validator?: (fieldState: IFieldState) => Promise<IValidationResult>; // result of withValidation
fixedWidth?: boolean;
onFinished(ok?: boolean, text?: string): void;
onFinished(ok?: false, text?: void): void;
onFinished(ok: true, text: string): void;
}
interface IState {

View file

@ -35,7 +35,6 @@ import React, {
import sanitizeHtml from "sanitize-html";
import { KeyBindingAction } from "../../../../accessibility/KeyboardShortcuts";
import { Ref } from "../../../../accessibility/roving/types";
import {
findSiblingElement,
RovingTabIndexContext,
@ -104,8 +103,8 @@ interface IProps {
onFinished(): void;
}
function refIsForRecentlyViewed(ref: RefObject<HTMLElement>): boolean {
return ref.current?.id?.startsWith("mx_SpotlightDialog_button_recentlyViewed_") === true;
function refIsForRecentlyViewed(ref?: RefObject<HTMLElement>): boolean {
return ref?.current?.id?.startsWith("mx_SpotlightDialog_button_recentlyViewed_") === true;
}
function getRoomTypes(showRooms: boolean, showSpaces: boolean): Set<RoomType | null> {
@ -366,7 +365,7 @@ const SpotlightDialog: React.FC<IProps> = ({ initialText = "", initialFilter = n
return [
...SpaceStore.instance.enabledMetaSpaces.map((spaceKey) => ({
section: Section.Spaces,
filter: [],
filter: [] as Filter[],
avatar: (
<div
className={classNames(
@ -456,6 +455,7 @@ const SpotlightDialog: React.FC<IProps> = ({ initialText = "", initialFilter = n
return memberComparator(a.member, b.member);
}
return 0;
});
}
@ -474,17 +474,16 @@ const SpotlightDialog: React.FC<IProps> = ({ initialText = "", initialFilter = n
};
useEffect(() => {
setImmediate(() => {
let ref: Ref | undefined;
if (rovingContext.state.refs) {
ref = rovingContext.state.refs[0];
const ref = rovingContext.state.refs[0];
if (ref) {
rovingContext.dispatch({
type: Type.SetFocus,
payload: { ref },
});
ref.current?.scrollIntoView?.({
block: "nearest",
});
}
rovingContext.dispatch({
type: Type.SetFocus,
payload: { ref },
});
ref?.current?.scrollIntoView?.({
block: "nearest",
});
});
// we intentionally ignore changes to the rovingContext for the purpose of this hook
// we only want to reset the focus whenever the results or filters change
@ -635,7 +634,7 @@ const SpotlightDialog: React.FC<IProps> = ({ initialText = "", initialFilter = n
roomId: publicRoom.room_id,
autoJoin: !result.publicRoom.world_readable && !cli.isGuest(),
shouldPeek: result.publicRoom.world_readable || cli.isGuest(),
viaServers: [config.roomServer],
viaServers: config ? [config.roomServer] : undefined,
},
true,
ev.type !== "click",

View file

@ -148,7 +148,7 @@ export const NetworkDropdown: React.FC<IProps> = ({ protocols, config, setConfig
const { allServers, homeServer, userDefinedServers, setUserDefinedServers } = useServers();
const options: GenericDropdownMenuItem<IPublicRoomDirectoryConfig | null>[] = allServers.map((roomServer) => ({
key: { roomServer, instanceId: null },
key: { roomServer, instanceId: undefined },
label: roomServer,
description: roomServer === homeServer ? _t("Your server") : null,
options: [

View file

@ -154,7 +154,7 @@ export default class MPollBody extends React.Component<IBodyProps, IState> {
}
public componentDidMount(): void {
const room = this.context.getRoom(this.props.mxEvent.getRoomId());
const room = this.context?.getRoom(this.props.mxEvent.getRoomId());
const poll = room?.polls.get(this.props.mxEvent.getId()!);
if (poll) {
this.setPollInstance(poll);
@ -291,8 +291,8 @@ export default class MPollBody extends React.Component<IBodyProps, IState> {
const votes = countVotes(userVotes, pollEvent);
const totalVotes = this.totalVotes(votes);
const winCount = Math.max(...votes.values());
const userId = this.context.getUserId();
const myVote = userVotes?.get(userId!)?.answers[0];
const userId = this.context.getSafeUserId();
const myVote = userVotes?.get(userId)?.answers[0];
const disclosed = M_POLL_KIND_DISCLOSED.matches(pollEvent.kind.name);
// Disclosed: votes are hidden until I vote or the poll ends

View file

@ -259,7 +259,7 @@ interface IFavouriteButtonProp {
const FavouriteButton: React.FC<IFavouriteButtonProp> = ({ mxEvent }) => {
const { isFavourite, toggleFavourite } = useFavouriteMessages();
const eventId = mxEvent.getId();
const eventId = mxEvent.getId()!;
const classes = classNames("mx_MessageActionBar_iconButton mx_MessageActionBar_favouriteButton", {
mx_MessageActionBar_favouriteButton_fillstar: isFavourite(eventId),
});

View file

@ -995,19 +995,8 @@ export const RoomAdminToolsContainer: React.FC<IBaseRoomProps> = ({
return <div />;
};
const useIsSynapseAdmin = (cli: MatrixClient): boolean => {
const [isAdmin, setIsAdmin] = useState(false);
useEffect(() => {
cli.isSynapseAdministrator().then(
(isAdmin) => {
setIsAdmin(isAdmin);
},
() => {
setIsAdmin(false);
},
);
}, [cli]);
return isAdmin;
const useIsSynapseAdmin = (cli?: MatrixClient): boolean => {
return useAsyncMemo(async () => (cli ? cli.isSynapseAdministrator().catch(() => false) : false), [cli], false);
};
const useHomeserverSupportsCrossSigning = (cli: MatrixClient): boolean => {

View file

@ -250,7 +250,7 @@ export class MessageComposer extends React.Component<IProps, IState> {
// The members should already be loading, and loadMembersIfNeeded
// will return the promise for the existing operation
this.props.room.loadMembersIfNeeded().then(() => {
const me = this.props.room.getMember(MatrixClientPeg.get().getUserId()!);
const me = this.props.room.getMember(MatrixClientPeg.get().getSafeUserId()) ?? undefined;
this.setState({ me });
});
}

View file

@ -64,7 +64,7 @@ type OverflowMenuCloser = () => void;
export const OverflowMenuContext = createContext<OverflowMenuCloser | null>(null);
const MessageComposerButtons: React.FC<IProps> = (props: IProps) => {
const matrixClient: MatrixClient = useContext(MatrixClientContext);
const matrixClient = useContext(MatrixClientContext);
const { room, roomId, narrow } = useContext(RoomContext);
const isWysiwygLabEnabled = useSettingValue<boolean>("feature_wysiwyg_composer");
@ -183,7 +183,7 @@ const UploadButtonContextProvider: React.FC<IUploadButtonProps> = ({ roomId, rel
const uploadInput = useRef<HTMLInputElement>();
const onUploadClick = (): void => {
if (cli.isGuest()) {
if (cli?.isGuest()) {
dis.dispatch({ action: "require_registration" });
return;
}

View file

@ -59,7 +59,7 @@ export default function EditWysiwygComposer({
const { editMessage, endEditing, onChange, isSaveDisabled } = useEditing(editorStateTransfer, initialContent);
if (!isReady) {
return null;
return <></>;
}
return (

View file

@ -439,9 +439,11 @@ export default class Notifications extends React.PureComponent<IProps, IState> {
append: true,
});
} else {
const pusher = this.state.pushers.find((p) => p.kind === "email" && p.pushkey === email);
pusher.kind = null; // flag for delete
await MatrixClientPeg.get().setPusher(pusher);
const pusher = this.state.pushers?.find((p) => p.kind === "email" && p.pushkey === email);
if (pusher) {
pusher.kind = null; // flag for delete
await MatrixClientPeg.get().setPusher(pusher);
}
}
await this.refreshFromServer();

View file

@ -129,8 +129,8 @@ const SessionManagerTab: React.FC = () => {
const scrollIntoViewTimeoutRef = useRef<number>();
const matrixClient = useContext(MatrixClientContext);
const userId = matrixClient.getUserId();
const currentUserMember = (userId && matrixClient.getUser(userId)) || undefined;
const userId = matrixClient?.getUserId();
const currentUserMember = (userId && matrixClient?.getUser(userId)) || undefined;
const clientVersions = useAsyncMemo(() => matrixClient.getVersions(), [matrixClient]);
const onDeviceExpandToggle = (deviceId: ExtendedDevice["device_id"]): void => {