Move state update listeners from constructor to componentDidMount (#28341)

* Move state update listeners from constructor to componentDidMount

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>

* Iterate

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>

* Iterate

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>

---------

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>
This commit is contained in:
Michael Telatynski
2024-11-01 17:39:08 +00:00
committed by GitHub
parent 2d9982f9f0
commit 0899165d9e
72 changed files with 377 additions and 309 deletions

View File

@@ -41,7 +41,9 @@ export default abstract class AudioPlayerBase<T extends IProps = IProps> extends
this.state = {
playbackPhase: this.props.playback.currentState,
};
}
public componentDidMount(): void {
// We don't need to de-register: the class handles this for us internally
this.props.playback.on(UPDATE_EVENT, this.onPlaybackUpdate);

View File

@@ -27,10 +27,6 @@ export default class Clock extends React.Component<Props> {
formatFn: formatSeconds,
};
public constructor(props: Props) {
super(props);
}
public shouldComponentUpdate(nextProps: Readonly<Props>): boolean {
const currentFloor = Math.floor(this.props.seconds);
const nextFloor = Math.floor(nextProps.seconds);

View File

@@ -33,6 +33,9 @@ export default class DurationClock extends React.PureComponent<IProps, IState> {
// member property to track "did we get a duration".
durationSeconds: this.props.playback.clockInfo.durationSeconds,
};
}
public componentDidMount(): void {
this.props.playback.clockInfo.liveData.onUpdate(this.onTimeUpdate);
}

View File

@@ -26,10 +26,6 @@ type Props = Omit<ButtonProps<"div">, "title" | "onClick" | "disabled" | "elemen
* to be displayed in reference to a recording.
*/
export default class PlayPauseButton extends React.PureComponent<Props> {
public constructor(props: Props) {
super(props);
}
private onClick = (): void => {
// noinspection JSIgnoredPromiseFromCall
this.toggleState();

View File

@@ -43,6 +43,9 @@ export default class PlaybackClock extends React.PureComponent<IProps, IState> {
durationSeconds: this.props.playback.clockInfo.durationSeconds,
playbackPhase: PlaybackState.Stopped, // assume not started, so full clock
};
}
public componentDidMount(): void {
this.props.playback.on(UPDATE_EVENT, this.onPlaybackUpdate);
this.props.playback.clockInfo.liveData.onUpdate(this.onTimeUpdate);
}

View File

@@ -34,7 +34,9 @@ export default class PlaybackWaveform extends React.PureComponent<IProps, IState
heights: this.toHeights(this.props.playback.waveform),
progress: 0, // default no progress
};
}
public componentDidMount(): void {
this.props.playback.waveformData.onUpdate(this.onWaveformUpdate);
this.props.playback.clockInfo.liveData.onUpdate(this.onTimeUpdate);
}

View File

@@ -55,7 +55,9 @@ export default class SeekBar extends React.PureComponent<IProps, IState> {
this.state = {
percentage: percentageOf(this.props.playback.timeSeconds, 0, this.props.playback.durationSeconds),
};
}
public componentDidMount(): void {
// We don't need to de-register: the class handles this for us internally
this.props.playback.liveData.onUpdate(() => this.animationFrameFn.mark());
}

View File

@@ -801,7 +801,6 @@ export class SSOAuthEntry extends React.Component<ISSOAuthEntryProps, ISSOAuthEn
this.ssoUrl = props.matrixClient.getFallbackAuthUrl(this.props.loginType, this.props.authSessionId);
this.popupWindow = null;
window.addEventListener("message", this.onReceiveMessage);
this.state = {
phase: SSOAuthEntry.PHASE_PREAUTH,
@@ -810,6 +809,7 @@ export class SSOAuthEntry extends React.Component<ISSOAuthEntryProps, ISSOAuthEn
}
public componentDidMount(): void {
window.addEventListener("message", this.onReceiveMessage);
this.props.onPhaseChange(SSOAuthEntry.PHASE_PREAUTH);
}
@@ -918,10 +918,10 @@ export class FallbackAuthEntry<T = {}> extends React.Component<IAuthEntryProps &
// we have to make the user click a button, as browsers will block
// the popup if we open it immediately.
this.popupWindow = null;
window.addEventListener("message", this.onReceiveMessage);
}
public componentDidMount(): void {
window.addEventListener("message", this.onReceiveMessage);
this.props.onPhaseChange(DEFAULT_PHASE);
}

View File

@@ -41,10 +41,6 @@ interface Props {
export default class LoginWithQRFlow extends React.Component<Props> {
private checkCodeInput = createRef<HTMLInputElement>();
public constructor(props: Props) {
super(props);
}
private handleClick = (type: Click): ((e: React.FormEvent) => Promise<void>) => {
return async (e: React.FormEvent): Promise<void> => {
e.preventDefault();

View File

@@ -20,10 +20,6 @@ interface IProps {
* menu.
*/
export default class GenericElementContextMenu extends React.Component<IProps> {
public constructor(props: IProps) {
super(props);
}
public componentDidMount(): void {
window.addEventListener("resize", this.resize);
}

View File

@@ -17,10 +17,6 @@ interface IProps extends IContextMenuProps {
}
export default class LegacyCallContextMenu extends React.Component<IProps> {
public constructor(props: IProps) {
super(props);
}
public onHoldClick = (): void => {
this.props.call.setRemoteOnHold(true);
this.props.onFinished();

View File

@@ -64,6 +64,11 @@ export default class BugReportDialog extends React.Component<IProps, IState> {
this.unmounted = false;
this.issueRef = React.createRef();
}
public componentDidMount(): void {
this.unmounted = false;
this.issueRef.current?.focus();
// Get all of the extra info dumped to the console when someone is about
// to send debug logs. Since this is a fire and forget action, we do
@@ -76,10 +81,6 @@ export default class BugReportDialog extends React.Component<IProps, IState> {
});
}
public componentDidMount(): void {
this.issueRef.current?.focus();
}
public componentWillUnmount(): void {
this.unmounted = true;
}

View File

@@ -113,14 +113,6 @@ export default class CreateRoomDialog extends React.Component<IProps, IState> {
nameIsValid: false,
canChangeEncryption: false,
};
checkUserIsAllowedToChangeEncryption(cli, Preset.PrivateChat).then(({ allowChange, forcedValue }) =>
this.setState((state) => ({
canChangeEncryption: allowChange,
// override with forcedValue if it is set
isEncrypted: forcedValue ?? state.isEncrypted,
})),
);
}
private roomCreateOptions(): IOpts {
@@ -160,6 +152,15 @@ export default class CreateRoomDialog extends React.Component<IProps, IState> {
}
public componentDidMount(): void {
const cli = MatrixClientPeg.safeGet();
checkUserIsAllowedToChangeEncryption(cli, Preset.PrivateChat).then(({ allowChange, forcedValue }) =>
this.setState((state) => ({
canChangeEncryption: allowChange,
// override with forcedValue if it is set
isEncrypted: forcedValue ?? state.isEncrypted,
})),
);
// move focus to first field when showing dialog
this.nameField.current?.focus();
}

View File

@@ -58,7 +58,9 @@ export default class DeactivateAccountDialog extends React.Component<IProps, ISt
authData: null, // for UIA
authEnabled: true, // see usages for information
};
}
public componentDidMount(): void {
this.initAuth(/* shouldErase= */ false);
}

View File

@@ -63,6 +63,9 @@ export default class IncomingSasDialog extends React.Component<IProps, IState> {
opponentProfileError: null,
sas: null,
};
}
public componentDidMount(): void {
this.props.verifier.on(VerifierEvent.ShowSas, this.onVerifierShowSas);
this.props.verifier.on(VerifierEvent.Cancel, this.onVerifierCancel);
this.fetchOpponentProfile();

View File

@@ -397,6 +397,7 @@ export default class InviteDialog extends React.PureComponent<Props, IInviteDial
}
public componentDidMount(): void {
this.unmounted = false;
this.encryptionByDefault = privateShouldBeEncrypted(MatrixClientPeg.safeGet());
if (this.props.initialText) {

View File

@@ -81,9 +81,10 @@ export default class LogoutDialog extends React.Component<IProps, IState> {
this.state = {
backupStatus: BackupStatus.LOADING,
};
}
// we can't call setState() immediately, so wait a beat
window.setTimeout(() => this.startLoadBackupStatus(), 0);
public componentDidMount(): void {
this.startLoadBackupStatus();
}
/** kick off the asynchronous calls to populate `state.backupStatus` in the background */

View File

@@ -32,6 +32,9 @@ export default class VerificationRequestDialog extends React.Component<IProps, I
this.state = {
verificationRequest: this.props.verificationRequest,
};
}
public componentDidMount(): void {
this.props.verificationRequestPromise?.then((r) => {
this.setState({ verificationRequest: r });
});

View File

@@ -134,29 +134,20 @@ export default class AppTile extends React.Component<IProps, IState> {
private iframe?: HTMLIFrameElement; // ref to the iframe (callback style)
private allowedWidgetsWatchRef?: string;
private persistKey: string;
private sgWidget: StopGapWidget | null;
private sgWidget?: StopGapWidget;
private dispatcherRef?: string;
private unmounted = false;
public constructor(props: IProps, context: ContextType<typeof MatrixClientContext>) {
super(props, context);
// Tiles in miniMode are floating, and therefore not docked
if (!this.props.miniMode) {
ActiveWidgetStore.instance.dockWidget(
this.props.app.id,
isAppWidget(this.props.app) ? this.props.app.roomId : null,
);
}
// The key used for PersistedElement
this.persistKey = getPersistKey(WidgetUtils.getWidgetUid(this.props.app));
try {
this.sgWidget = new StopGapWidget(this.props);
this.setupSgListeners();
} catch (e) {
logger.log("Failed to construct widget", e);
this.sgWidget = null;
this.sgWidget = undefined;
}
this.state = this.getNewState(props);
@@ -303,6 +294,20 @@ export default class AppTile extends React.Component<IProps, IState> {
}
public componentDidMount(): void {
this.unmounted = false;
// Tiles in miniMode are floating, and therefore not docked
if (!this.props.miniMode) {
ActiveWidgetStore.instance.dockWidget(
this.props.app.id,
isAppWidget(this.props.app) ? this.props.app.roomId : null,
);
}
if (this.sgWidget) {
this.setupSgListeners();
}
// Only fetch IM token on mount if we're showing and have permission to load
if (this.sgWidget && this.state.hasPermissionToLoad) {
this.startWidget();
@@ -374,7 +379,7 @@ export default class AppTile extends React.Component<IProps, IState> {
this.startWidget();
} catch (e) {
logger.error("Failed to construct widget", e);
this.sgWidget = null;
this.sgWidget = undefined;
}
}
@@ -607,7 +612,7 @@ export default class AppTile extends React.Component<IProps, IState> {
};
public render(): React.ReactNode {
let appTileBody: JSX.Element;
let appTileBody: JSX.Element | undefined;
// Note that there is advice saying allow-scripts shouldn't be used with allow-same-origin
// because that would allow the iframe to programmatically remove the sandbox attribute, but
@@ -650,7 +655,7 @@ export default class AppTile extends React.Component<IProps, IState> {
<AppWarning errorMsg={_t("widget|error_loading")} />
</div>
);
} else if (!this.state.hasPermissionToLoad && this.props.room) {
} else if (!this.state.hasPermissionToLoad && this.props.room && this.sgWidget) {
// only possible for room widgets, can assert this.props.room here
const isEncrypted = this.context.isRoomEncrypted(this.props.room.roomId);
appTileBody = (
@@ -677,7 +682,7 @@ export default class AppTile extends React.Component<IProps, IState> {
<AppWarning errorMsg={_t("widget|error_mixed_content")} />
</div>
);
} else {
} else if (this.sgWidget) {
appTileBody = (
<>
<div className={appTileBodyClass} style={appTileBodyStyles}>

View File

@@ -41,10 +41,6 @@ export interface ExistingSourceIProps {
}
export class ExistingSource extends React.Component<ExistingSourceIProps> {
public constructor(props: ExistingSourceIProps) {
super(props);
}
private onClick = (): void => {
this.props.onSelect(this.props.source);
};

View File

@@ -127,7 +127,9 @@ export default class Dropdown extends React.Component<DropdownProps, IState> {
// the current search query
searchQuery: "",
};
}
public componentDidMount(): void {
// Listen for all clicks on the document so we can close the
// menu when the user clicks somewhere else
document.addEventListener("click", this.onDocumentClick, false);

View File

@@ -15,10 +15,6 @@ interface IProps extends Omit<React.ComponentProps<typeof TextWithTooltip>, "tab
}
export default class LinkWithTooltip extends React.Component<IProps> {
public constructor(props: IProps) {
super(props);
}
public render(): React.ReactNode {
const { children, tooltip, ...props } = this.props;

View File

@@ -79,7 +79,7 @@ interface IProps {
*/
export default class PersistedElement extends React.Component<IProps> {
private resizeObserver: ResizeObserver;
private dispatcherRef: string;
private dispatcherRef?: string;
private childContainer?: HTMLDivElement;
private child?: HTMLDivElement;
@@ -87,13 +87,6 @@ export default class PersistedElement extends React.Component<IProps> {
super(props);
this.resizeObserver = new ResizeObserver(this.repositionChild);
// Annoyingly, a resize observer is insufficient, since we also care
// about when the element moves on the screen without changing its
// dimensions. Doesn't look like there's a ResizeObserver equivalent
// for this, so we bodge it by listening for document resize and
// the timeline_resize action.
window.addEventListener("resize", this.repositionChild);
this.dispatcherRef = dis.register(this.onAction);
if (this.props.moveRef) this.props.moveRef.current = this.repositionChild;
}
@@ -132,6 +125,14 @@ export default class PersistedElement extends React.Component<IProps> {
};
public componentDidMount(): void {
// Annoyingly, a resize observer is insufficient, since we also care
// about when the element moves on the screen without changing its
// dimensions. Doesn't look like there's a ResizeObserver equivalent
// for this, so we bodge it by listening for document resize and
// the timeline_resize action.
window.addEventListener("resize", this.repositionChild);
this.dispatcherRef = dis.register(this.onAction);
this.updateChild();
this.renderApp();
}

View File

@@ -68,6 +68,7 @@ export default class PowerSelector<K extends undefined | string> extends React.C
}
public componentDidMount(): void {
this.unmounted = false;
this.initStateFromProps();
}

View File

@@ -89,6 +89,7 @@ export default class ReplyChain extends React.Component<IProps, IState> {
}
public componentDidMount(): void {
this.unmounted = false;
this.initialize();
this.trySetExpandableQuotes();
}

View File

@@ -16,10 +16,6 @@ interface IProps extends HTMLAttributes<HTMLSpanElement> {
}
export default class TextWithTooltip extends React.Component<IProps> {
public constructor(props: IProps) {
super(props);
}
public render(): React.ReactNode {
const { className, children, tooltip, tooltipProps } = this.props;

View File

@@ -37,6 +37,9 @@ class ReactionPicker extends React.Component<IProps, IState> {
this.state = {
selectedEmojis: new Set(Object.keys(this.getReactions())),
};
}
public componentDidMount(): void {
this.addListeners();
}

View File

@@ -58,7 +58,9 @@ export default class DateSeparator extends React.Component<IProps, IState> {
this.state = {
jumpToDateEnabled: SettingsStore.getValue("feature_jump_to_date"),
};
}
public componentDidMount(): void {
// We're using a watcher so the date headers in the timeline are updated
// when the lab setting is toggled.
this.settingWatcherRef = SettingsStore.watchSetting(

View File

@@ -59,7 +59,7 @@ export default class MImageBody extends React.Component<IBodyProps, IState> {
public static contextType = RoomContext;
public declare context: React.ContextType<typeof RoomContext>;
private unmounted = true;
private unmounted = false;
private image = createRef<HTMLImageElement>();
private placeholder = createRef<HTMLDivElement>();
private timeout?: number;

View File

@@ -21,10 +21,6 @@ interface IProps {
}
export default class MJitsiWidgetEvent extends React.PureComponent<IProps> {
public constructor(props: IProps) {
super(props);
}
public render(): React.ReactNode {
const url = this.props.mxEvent.getContent()["url"];
const prevUrl = this.props.mxEvent.getPrevContent()["url"];

View File

@@ -75,6 +75,10 @@ export default class MLocationBody extends React.Component<IBodyProps, IState> {
this.context.on(ClientEvent.Sync, this.reconnectedListener);
};
public componentDidMount(): void {
this.unmounted = false;
}
public componentWillUnmount(): void {
this.unmounted = true;
this.context.off(ClientEvent.Sync, this.reconnectedListener);

View File

@@ -68,11 +68,13 @@ export default class AppsDrawer extends React.Component<IProps, IState> {
};
this.resizer = this.createResizer();
this.props.resizeNotifier.on("isResizing", this.onIsResizing);
}
public componentDidMount(): void {
this.unmounted = false;
this.props.resizeNotifier.on("isResizing", this.onIsResizing);
ScalarMessaging.startListening();
WidgetLayoutStore.instance.on(WidgetLayoutStore.emissionForRoom(this.props.room), this.updateApps);
this.dispatcherRef = dis.register(this.onAction);

View File

@@ -128,10 +128,10 @@ export default class BasicMessageEditor extends React.Component<IProps, IState>
private lastCaret!: DocumentOffset;
private lastSelection: ReturnType<typeof cloneSelection> | null = null;
private readonly useMarkdownHandle: string;
private readonly emoticonSettingHandle: string;
private readonly shouldShowPillAvatarSettingHandle: string;
private readonly surroundWithHandle: string;
private useMarkdownHandle?: string;
private emoticonSettingHandle?: string;
private shouldShowPillAvatarSettingHandle?: string;
private surroundWithHandle?: string;
private readonly historyManager = new HistoryManager();
public constructor(props: IProps) {
@@ -145,28 +145,7 @@ export default class BasicMessageEditor extends React.Component<IProps, IState>
const ua = navigator.userAgent.toLowerCase();
this.isSafari = ua.includes("safari/") && !ua.includes("chrome/");
this.useMarkdownHandle = SettingsStore.watchSetting(
"MessageComposerInput.useMarkdown",
null,
this.configureUseMarkdown,
);
this.emoticonSettingHandle = SettingsStore.watchSetting(
"MessageComposerInput.autoReplaceEmoji",
null,
this.configureEmoticonAutoReplace,
);
this.configureEmoticonAutoReplace();
this.shouldShowPillAvatarSettingHandle = SettingsStore.watchSetting(
"Pill.shouldShowPillAvatar",
null,
this.configureShouldShowPillAvatar,
);
this.surroundWithHandle = SettingsStore.watchSetting(
"MessageComposerInput.surroundWith",
null,
this.surroundWithSettingChanged,
);
}
public componentDidUpdate(prevProps: IProps): void {
@@ -737,6 +716,27 @@ export default class BasicMessageEditor extends React.Component<IProps, IState>
}
public componentDidMount(): void {
this.useMarkdownHandle = SettingsStore.watchSetting(
"MessageComposerInput.useMarkdown",
null,
this.configureUseMarkdown,
);
this.emoticonSettingHandle = SettingsStore.watchSetting(
"MessageComposerInput.autoReplaceEmoji",
null,
this.configureEmoticonAutoReplace,
);
this.shouldShowPillAvatarSettingHandle = SettingsStore.watchSetting(
"Pill.shouldShowPillAvatar",
null,
this.configureShouldShowPillAvatar,
);
this.surroundWithHandle = SettingsStore.watchSetting(
"MessageComposerInput.surroundWith",
null,
this.surroundWithSettingChanged,
);
const model = this.props.model;
model.setUpdateCallback(this.updateEditorState);
const partCreator = model.partCreator;

View File

@@ -124,7 +124,7 @@ class EditMessageComposer extends React.Component<IEditMessageComposerProps, ISt
public declare context: React.ContextType<typeof RoomContext>;
private readonly editorRef = createRef<BasicMessageComposer>();
private readonly dispatcherRef: string;
private dispatcherRef?: string;
private readonly replyToEvent?: MatrixEvent;
private model!: EditorModel;
@@ -140,7 +140,9 @@ class EditMessageComposer extends React.Component<IEditMessageComposerProps, ISt
this.state = {
saveDisabled: !isRestored || !this.isContentModified(editContent["m.new_content"]!),
};
}
public componentDidMount(): void {
window.addEventListener("beforeunload", this.saveStoredEditorState);
this.dispatcherRef = dis.register(this.onAction);
}

View File

@@ -386,6 +386,7 @@ export class UnwrappedEventTile extends React.Component<EventTileProps, IState>
}
public componentDidMount(): void {
this.unmounted = false;
this.suppressReadReceiptAnimation = false;
const client = MatrixClientPeg.safeGet();
if (!this.props.forExport) {

View File

@@ -72,7 +72,7 @@ interface IState {
export default class MemberList extends React.Component<IProps, IState> {
private readonly showPresence: boolean;
private mounted = false;
private unmounted = false;
public static contextType = SDKContext;
public declare context: React.ContextType<typeof SDKContext>;
@@ -82,8 +82,6 @@ export default class MemberList extends React.Component<IProps, IState> {
super(props, context);
this.state = this.getMembersState([], []);
this.showPresence = context?.memberListStore.isPresenceEnabled() ?? true;
this.mounted = true;
this.listenForMembersChanges();
}
private listenForMembersChanges(): void {
@@ -102,11 +100,13 @@ export default class MemberList extends React.Component<IProps, IState> {
}
public componentDidMount(): void {
this.unmounted = false;
this.listenForMembersChanges();
this.updateListNow(true);
}
public componentWillUnmount(): void {
this.mounted = false;
this.unmounted = true;
const cli = MatrixClientPeg.get();
if (cli) {
cli.removeListener(RoomStateEvent.Update, this.onRoomStateUpdate);
@@ -205,7 +205,7 @@ export default class MemberList extends React.Component<IProps, IState> {
// XXX: exported for tests
public async updateListNow(showLoadingSpinner?: boolean): Promise<void> {
if (!this.mounted) {
if (this.unmounted) {
return;
}
if (showLoadingSpinner) {
@@ -215,7 +215,7 @@ export default class MemberList extends React.Component<IProps, IState> {
this.props.roomId,
this.props.searchQuery,
);
if (!this.mounted) {
if (this.unmounted) {
return;
}
this.setState({

View File

@@ -134,9 +134,6 @@ export class MessageComposer extends React.Component<IProps, IState> {
super(props, context);
this.context = context; // otherwise React will only set it prior to render due to type def above
VoiceRecordingStore.instance.on(UPDATE_EVENT, this.onVoiceStoreUpdate);
window.addEventListener("beforeunload", this.saveWysiwygEditorState);
const isWysiwygLabEnabled = SettingsStore.getValue<boolean>("feature_wysiwyg_composer");
let isRichTextEnabled = true;
let initialComposerContent = "";
@@ -145,13 +142,6 @@ export class MessageComposer extends React.Component<IProps, IState> {
if (wysiwygState) {
isRichTextEnabled = wysiwygState.isRichText;
initialComposerContent = wysiwygState.content;
if (wysiwygState.replyEventId) {
dis.dispatch({
action: "reply_to_event",
event: this.props.room.findEventById(wysiwygState.replyEventId),
context: this.context.timelineRenderingType,
});
}
}
}
@@ -171,11 +161,6 @@ export class MessageComposer extends React.Component<IProps, IState> {
};
this.instanceId = instanceCount++;
SettingsStore.monitorSetting("MessageComposerInput.showStickersButton", null);
SettingsStore.monitorSetting("MessageComposerInput.showPollsButton", null);
SettingsStore.monitorSetting(Features.VoiceBroadcast, null);
SettingsStore.monitorSetting("feature_wysiwyg_composer", null);
}
private get editorStateKey(): string {
@@ -248,6 +233,25 @@ export class MessageComposer extends React.Component<IProps, IState> {
}
public componentDidMount(): void {
VoiceRecordingStore.instance.on(UPDATE_EVENT, this.onVoiceStoreUpdate);
window.addEventListener("beforeunload", this.saveWysiwygEditorState);
if (this.state.isWysiwygLabEnabled) {
const wysiwygState = this.restoreWysiwygEditorState();
if (wysiwygState?.replyEventId) {
dis.dispatch({
action: "reply_to_event",
event: this.props.room.findEventById(wysiwygState.replyEventId),
context: this.context.timelineRenderingType,
});
}
}
SettingsStore.monitorSetting("MessageComposerInput.showStickersButton", null);
SettingsStore.monitorSetting("MessageComposerInput.showPollsButton", null);
SettingsStore.monitorSetting(Features.VoiceBroadcast, null);
SettingsStore.monitorSetting("feature_wysiwyg_composer", null);
this.dispatcherRef = dis.register(this.onAction);
this.waitForOwnMember();
UIStore.instance.trackElementDimensions(`MessageComposer${this.instanceId}`, this.ref.current!);

View File

@@ -44,15 +44,23 @@ interface IState {
}
export default class NotificationBadge extends React.PureComponent<XOR<IProps, IClickableProps>, IState> {
private countWatcherRef: string;
private countWatcherRef?: string;
public constructor(props: IProps) {
super(props);
this.props.notification.on(NotificationStateEvents.Update, this.onNotificationUpdate);
this.state = {
showCounts: SettingsStore.getValue("Notifications.alwaysShowBadgeCounts", this.roomId),
};
}
private get roomId(): string | null {
// We should convert this to null for safety with the SettingsStore
return this.props.roomId || null;
}
public componentDidMount(): void {
this.props.notification.on(NotificationStateEvents.Update, this.onNotificationUpdate);
this.countWatcherRef = SettingsStore.watchSetting(
"Notifications.alwaysShowBadgeCounts",
@@ -61,11 +69,6 @@ export default class NotificationBadge extends React.PureComponent<XOR<IProps, I
);
}
private get roomId(): string | null {
// We should convert this to null for safety with the SettingsStore
return this.props.roomId || null;
}
public componentWillUnmount(): void {
SettingsStore.unwatchSetting(this.countWatcherRef);
this.props.notification.off(NotificationStateEvents.Update, this.onNotificationUpdate);

View File

@@ -60,7 +60,7 @@ const RoomBreadcrumbTile: React.FC<{ room: Room; onClick: (ev: ButtonEvent) => v
};
export default class RoomBreadcrumbs extends React.PureComponent<IProps, IState> {
private isMounted = true;
private unmounted = false;
private toolbar = createRef<HTMLDivElement>();
public constructor(props: IProps) {
@@ -70,17 +70,20 @@ export default class RoomBreadcrumbs extends React.PureComponent<IProps, IState>
doAnimation: true, // technically we want animation on mount, but it won't be perfect
skipFirst: false, // render the thing, as boring as it is
};
}
public componentDidMount(): void {
this.unmounted = false;
BreadcrumbsStore.instance.on(UPDATE_EVENT, this.onBreadcrumbsUpdate);
}
public componentWillUnmount(): void {
this.isMounted = false;
this.unmounted = true;
BreadcrumbsStore.instance.off(UPDATE_EVENT, this.onBreadcrumbsUpdate);
}
private onBreadcrumbsUpdate = (): void => {
if (!this.isMounted) return;
if (this.unmounted) return;
// We need to trick the CSSTransition component into updating, which means we need to
// tell it to not animate, then to animate a moment later. This causes two updates

View File

@@ -94,7 +94,6 @@ export class RoomTile extends React.PureComponent<ClassProps, State> {
// generatePreview() will return nothing if the user has previews disabled
messagePreview: null,
};
this.generatePreview();
this.notificationState = RoomNotificationStateStore.instance.getRoomState(this.props.room);
this.roomProps = EchoChamber.forRoom(this.props.room);
@@ -147,6 +146,8 @@ export class RoomTile extends React.PureComponent<ClassProps, State> {
}
public componentDidMount(): void {
this.generatePreview();
// when we're first rendered (or our sublist is expanded) make sure we are visible if we're active
if (this.state.selected) {
this.scrollIntoView();

View File

@@ -255,7 +255,7 @@ export class SendMessageComposer extends React.Component<ISendMessageComposerPro
private readonly editorRef = createRef<BasicMessageComposer>();
private model: EditorModel;
private currentlyComposedEditorState: SerializedPart[] | null = null;
private dispatcherRef: string;
private dispatcherRef?: string;
private sendHistoryManager: SendHistoryManager;
public static defaultProps = {
@@ -275,15 +275,17 @@ export class SendMessageComposer extends React.Component<ISendMessageComposerPro
);
}
window.addEventListener("beforeunload", this.saveStoredEditorState);
const partCreator = new CommandPartCreator(this.props.room, this.props.mxClient);
const parts = this.restoreStoredEditorState(partCreator) || [];
this.model = new EditorModel(parts, partCreator);
this.dispatcherRef = dis.register(this.onAction);
this.sendHistoryManager = new SendHistoryManager(this.props.room.roomId, "mx_cider_history_");
}
public componentDidMount(): void {
window.addEventListener("beforeunload", this.saveStoredEditorState);
this.dispatcherRef = dis.register(this.onAction);
}
public componentDidUpdate(prevProps: ISendMessageComposerProps): void {
const replyingToThread = this.props.relation?.key === THREAD_RELATION_TYPE.name;
const differentEventTarget = this.props.relation?.event_id !== prevProps.relation?.event_id;

View File

@@ -45,6 +45,7 @@ export default class CrossSigningPanel extends React.PureComponent<{}, IState> {
}
public componentDidMount(): void {
this.unmounted = false;
const cli = MatrixClientPeg.safeGet();
cli.on(ClientEvent.AccountData, this.onAccountData);
cli.on(CryptoEvent.UserTrustStatusChanged, this.onStatusChanged);

View File

@@ -11,7 +11,6 @@ import { logger } from "matrix-js-sdk/src/logger";
import type ExportE2eKeysDialog from "../../../async-components/views/dialogs/security/ExportE2eKeysDialog";
import type ImportE2eKeysDialog from "../../../async-components/views/dialogs/security/ImportE2eKeysDialog";
import { MatrixClientPeg } from "../../../MatrixClientPeg";
import { _t } from "../../../languageHandler";
import Modal from "../../../Modal";
import AccessibleButton from "../elements/AccessibleButton";
@@ -20,6 +19,7 @@ import SettingsStore from "../../../settings/SettingsStore";
import SettingsFlag from "../elements/SettingsFlag";
import { SettingLevel } from "../../../settings/SettingLevel";
import SettingsSubsection, { SettingsSubsectionText } from "./shared/SettingsSubsection";
import MatrixClientContext from "../../../contexts/MatrixClientContext";
interface IProps {}
@@ -33,17 +33,24 @@ interface IState {
}
export default class CryptographyPanel extends React.Component<IProps, IState> {
public constructor(props: IProps) {
public static contextType = MatrixClientContext;
public declare context: React.ContextType<typeof MatrixClientContext>;
public constructor(props: IProps, context: React.ContextType<typeof MatrixClientContext>) {
super(props);
const client = MatrixClientPeg.safeGet();
const crypto = client.getCrypto();
if (!crypto) {
if (!context.getCrypto()) {
this.state = { deviceIdentityKey: null };
} else {
this.state = { deviceIdentityKey: undefined };
crypto
.getOwnDeviceKeys()
}
}
public componentDidMount(): void {
if (this.state.deviceIdentityKey === undefined) {
this.context
.getCrypto()
?.getOwnDeviceKeys()
.then((keys) => {
this.setState({ deviceIdentityKey: keys.ed25519 });
})
@@ -55,7 +62,7 @@ export default class CryptographyPanel extends React.Component<IProps, IState> {
}
public render(): React.ReactNode {
const client = MatrixClientPeg.safeGet();
const client = this.context;
const deviceId = client.deviceId;
let identityKey = this.state.deviceIdentityKey;
if (identityKey === undefined) {
@@ -126,7 +133,7 @@ export default class CryptographyPanel extends React.Component<IProps, IState> {
import("../../../async-components/views/dialogs/security/ExportE2eKeysDialog") as unknown as Promise<
typeof ExportE2eKeysDialog
>,
{ matrixClient: MatrixClientPeg.safeGet() },
{ matrixClient: this.context },
);
};
@@ -135,12 +142,12 @@ export default class CryptographyPanel extends React.Component<IProps, IState> {
import("../../../async-components/views/dialogs/security/ImportE2eKeysDialog") as unknown as Promise<
typeof ImportE2eKeysDialog
>,
{ matrixClient: MatrixClientPeg.safeGet() },
{ matrixClient: this.context },
);
};
private updateBlacklistDevicesFlag = (checked: boolean): void => {
const crypto = MatrixClientPeg.safeGet().getCrypto();
const crypto = this.context.getCrypto();
if (crypto) crypto.globalBlacklistUnverifiedDevices = checked;
};
}

View File

@@ -55,6 +55,7 @@ export default class FontScalingPanel extends React.Component<IProps, IState> {
}
public async componentDidMount(): Promise<void> {
this.unmounted = false;
// Fetch the current user profile for the message preview
const client = MatrixClientPeg.safeGet();
const userId = client.getSafeUserId();

View File

@@ -206,7 +206,7 @@ const NotificationActivitySettings = (): JSX.Element => {
* The old, deprecated notifications tab view, only displayed if the user has the labs flag disabled.
*/
export default class Notifications extends React.PureComponent<IProps, IState> {
private settingWatchers: string[];
private settingWatchers: string[] = [];
public constructor(props: IProps) {
super(props);
@@ -220,7 +220,17 @@ export default class Notifications extends React.PureComponent<IProps, IState> {
clearingNotifications: false,
ruleIdsWithError: {},
};
}
private get isInhibited(): boolean {
// Caution: The master rule's enabled state is inverted from expectation. When
// the master rule is *enabled* it means all other rules are *disabled* (or
// inhibited). Conversely, when the master rule is *disabled* then all other rules
// are *enabled* (or operate fine).
return !!this.state.masterPushRule?.enabled;
}
public componentDidMount(): void {
this.settingWatchers = [
SettingsStore.watchSetting("notificationsEnabled", null, (...[, , , , value]) =>
this.setState({ desktopNotifications: value as boolean }),
@@ -235,17 +245,7 @@ export default class Notifications extends React.PureComponent<IProps, IState> {
this.setState({ audioNotifications: value as boolean }),
),
];
}
private get isInhibited(): boolean {
// Caution: The master rule's enabled state is inverted from expectation. When
// the master rule is *enabled* it means all other rules are *disabled* (or
// inhibited). Conversely, when the master rule is *disabled* then all other rules
// are *enabled* (or operate fine).
return !!this.state.masterPushRule?.enabled;
}
public componentDidMount(): void {
// noinspection JSIgnoredPromiseFromCall
this.refreshFromServer();
this.refreshFromAccountData();

View File

@@ -83,6 +83,7 @@ export default class SecureBackupPanel extends React.PureComponent<{}, IState> {
}
public componentDidMount(): void {
this.unmounted = false;
this.loadBackupStatus();
MatrixClientPeg.safeGet().on(CryptoEvent.KeyBackupStatus, this.onKeyBackupStatus);

View File

@@ -53,9 +53,11 @@ export default class AdvancedRoomSettingsTab extends React.Component<IProps, ISt
public constructor(props: IProps) {
super(props);
const msc3946ProcessDynamicPredecessor = SettingsStore.getValue("feature_dynamic_room_predecessors");
this.state = {};
}
public componentDidMount(): void {
const msc3946ProcessDynamicPredecessor = SettingsStore.getValue("feature_dynamic_room_predecessors");
// we handle lack of this object gracefully later, so don't worry about it failing here.
const room = this.props.room;

View File

@@ -205,7 +205,9 @@ export class SpaceItem extends React.PureComponent<IItemProps, IItemState> {
collapsed,
childSpaces: this.childSpaces,
};
}
public componentDidMount(): void {
SpaceStore.instance.on(this.props.space.roomId, this.onSpaceUpdate);
this.props.space.on(RoomEvent.Name, this.onRoomNameChange);
}

View File

@@ -110,11 +110,10 @@ export default class LegacyCallView extends React.Component<IProps, IState> {
sidebarFeeds: sidebar,
sidebarShown: true,
};
this.updateCallListeners(null, this.props.call);
}
public componentDidMount(): void {
this.updateCallListeners(null, this.props.call);
this.dispatcherRef = dis.register(this.onAction);
document.addEventListener("keydown", this.onNativeKeyDown);
}