Merge pull request #4956 from matrix-org/t3chguy/ts/1

Convert Modal to TypeScript
This commit is contained in:
Michael Telatynski 2020-07-21 17:55:20 +01:00 committed by GitHub
commit e54eea0c51
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 178 additions and 113 deletions

View file

@ -24,6 +24,7 @@ import { RoomListStoreClass } from "../stores/room-list/RoomListStore";
import { PlatformPeg } from "../PlatformPeg"; import { PlatformPeg } from "../PlatformPeg";
import RoomListLayoutStore from "../stores/room-list/RoomListLayoutStore"; import RoomListLayoutStore from "../stores/room-list/RoomListLayoutStore";
import {IntegrationManagers} from "../integrations/IntegrationManagers"; import {IntegrationManagers} from "../integrations/IntegrationManagers";
import {ModalManager} from "../Modal";
declare global { declare global {
interface Window { interface Window {
@ -41,6 +42,7 @@ declare global {
mxRoomListLayoutStore: RoomListLayoutStore; mxRoomListLayoutStore: RoomListLayoutStore;
mxPlatformPeg: PlatformPeg; mxPlatformPeg: PlatformPeg;
mxIntegrationManagers: typeof IntegrationManagers; mxIntegrationManagers: typeof IntegrationManagers;
singletonModalManager: ModalManager;
} }
// workaround for https://github.com/microsoft/TypeScript/issues/30933 // workaround for https://github.com/microsoft/TypeScript/issues/30933

View file

@ -386,7 +386,7 @@ export default class ContentMessages {
const isQuoting = Boolean(RoomViewStore.getQuotingEvent()); const isQuoting = Boolean(RoomViewStore.getQuotingEvent());
if (isQuoting) { if (isQuoting) {
const QuestionDialog = sdk.getComponent("dialogs.QuestionDialog"); const QuestionDialog = sdk.getComponent("dialogs.QuestionDialog");
const {finished} = Modal.createTrackedDialog('Upload Reply Warning', '', QuestionDialog, { const {finished} = Modal.createTrackedDialog<[boolean]>('Upload Reply Warning', '', QuestionDialog, {
title: _t('Replying With Files'), title: _t('Replying With Files'),
description: ( description: (
<div>{_t( <div>{_t(
@ -397,7 +397,7 @@ export default class ContentMessages {
hasCancelButton: true, hasCancelButton: true,
button: _t("Continue"), button: _t("Continue"),
}); });
const [shouldUpload]: [boolean] = await finished; const [shouldUpload] = await finished;
if (!shouldUpload) return; if (!shouldUpload) return;
} }
@ -420,12 +420,12 @@ export default class ContentMessages {
if (tooBigFiles.length > 0) { if (tooBigFiles.length > 0) {
const UploadFailureDialog = sdk.getComponent("dialogs.UploadFailureDialog"); const UploadFailureDialog = sdk.getComponent("dialogs.UploadFailureDialog");
const {finished} = Modal.createTrackedDialog('Upload Failure', '', UploadFailureDialog, { const {finished} = Modal.createTrackedDialog<[boolean]>('Upload Failure', '', UploadFailureDialog, {
badFiles: tooBigFiles, badFiles: tooBigFiles,
totalFiles: files.length, totalFiles: files.length,
contentMessages: this, contentMessages: this,
}); });
const [shouldContinue]: [boolean] = await finished; const [shouldContinue] = await finished;
if (!shouldContinue) return; if (!shouldContinue) return;
} }
@ -437,12 +437,12 @@ export default class ContentMessages {
for (let i = 0; i < okFiles.length; ++i) { for (let i = 0; i < okFiles.length; ++i) {
const file = okFiles[i]; const file = okFiles[i];
if (!uploadAll) { if (!uploadAll) {
const {finished} = Modal.createTrackedDialog('Upload Files confirmation', '', UploadConfirmDialog, { const {finished} = Modal.createTrackedDialog<[boolean, boolean]>('Upload Files confirmation', '', UploadConfirmDialog, {
file, file,
currentIndex: i, currentIndex: i,
totalFiles: okFiles.length, totalFiles: okFiles.length,
}); });
const [shouldContinue, shouldUploadAll]: [boolean, boolean] = await finished; const [shouldContinue, shouldUploadAll] = await finished;
if (!shouldContinue) break; if (!shouldContinue) break;
if (shouldUploadAll) { if (shouldUploadAll) {
uploadAll = true; uploadAll = true;

View file

@ -1,5 +1,6 @@
/* /*
Copyright 2015, 2016 OpenMarket Ltd Copyright 2015, 2016 OpenMarket Ltd
Copyright 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
@ -17,6 +18,8 @@ limitations under the License.
import React from 'react'; import React from 'react';
import ReactDOM from 'react-dom'; import ReactDOM from 'react-dom';
import classNames from 'classnames';
import Analytics from './Analytics'; import Analytics from './Analytics';
import dis from './dispatcher/dispatcher'; import dis from './dispatcher/dispatcher';
import {defer} from './utils/promise'; import {defer} from './utils/promise';
@ -25,36 +28,48 @@ import AsyncWrapper from './AsyncWrapper';
const DIALOG_CONTAINER_ID = "mx_Dialog_Container"; const DIALOG_CONTAINER_ID = "mx_Dialog_Container";
const STATIC_DIALOG_CONTAINER_ID = "mx_Dialog_StaticContainer"; const STATIC_DIALOG_CONTAINER_ID = "mx_Dialog_StaticContainer";
class ModalManager { interface IModal<T extends any[]> {
constructor() { elem: React.ReactNode;
this._counter = 0; className?: string;
beforeClosePromise?: Promise<boolean>;
closeReason?: string;
onBeforeClose?(reason?: string): Promise<boolean>;
onFinished(...args: T): void;
close(...args: T): void;
}
// The modal to prioritise over all others. If this is set, only show interface IHandle<T extends any[]> {
// this modal. Remove all other modals from the stack when this modal finished: Promise<T>;
// is closed. close(...args: T): void;
this._priorityModal = null; }
// The modal to keep open underneath other modals if possible. Useful
// for cases like Settings where the modal should remain open while the
// user is prompted for more information/errors.
this._staticModal = null;
// A list of the modals we have stacked up, with the most recent at [0]
// Neither the static nor priority modal will be in this list.
this._modals = [
/* {
elem: React component for this dialog
onFinished: caller-supplied onFinished callback
className: CSS class for the dialog wrapper div
} */
];
this.onBackgroundClick = this.onBackgroundClick.bind(this); interface IProps<T extends any[]> {
} onFinished?(...args: T): void;
// TODO improve typing here once all Modals are TS and we can exhaustively check the props
[key: string]: any;
}
hasDialogs() { interface IOptions<T extends any[]> {
return this._priorityModal || this._staticModal || this._modals.length > 0; onBeforeClose?: IModal<T>["onBeforeClose"];
} }
getOrCreateContainer() { type ParametersWithoutFirst<T extends (...args: any) => any> = T extends (a: any, ...args: infer P) => any ? P : never;
export class ModalManager {
private counter = 0;
// The modal to prioritise over all others. If this is set, only show
// this modal. Remove all other modals from the stack when this modal
// is closed.
private priorityModal: IModal<any> = null;
// The modal to keep open underneath other modals if possible. Useful
// for cases like Settings where the modal should remain open while the
// user is prompted for more information/errors.
private staticModal: IModal<any> = null;
// A list of the modals we have stacked up, with the most recent at [0]
// Neither the static nor priority modal will be in this list.
private modals: IModal<any>[] = [];
private static getOrCreateContainer() {
let container = document.getElementById(DIALOG_CONTAINER_ID); let container = document.getElementById(DIALOG_CONTAINER_ID);
if (!container) { if (!container) {
@ -66,7 +81,7 @@ class ModalManager {
return container; return container;
} }
getOrCreateStaticContainer() { private static getOrCreateStaticContainer() {
let container = document.getElementById(STATIC_DIALOG_CONTAINER_ID); let container = document.getElementById(STATIC_DIALOG_CONTAINER_ID);
if (!container) { if (!container) {
@ -78,63 +93,99 @@ class ModalManager {
return container; return container;
} }
createTrackedDialog(analyticsAction, analyticsInfo, ...rest) { public hasDialogs() {
return this.priorityModal || this.staticModal || this.modals.length > 0;
}
public createTrackedDialog<T extends any[]>(
analyticsAction: string,
analyticsInfo: string,
...rest: Parameters<ModalManager["createDialog"]>
) {
Analytics.trackEvent('Modal', analyticsAction, analyticsInfo); Analytics.trackEvent('Modal', analyticsAction, analyticsInfo);
return this.createDialog(...rest); return this.createDialog<T>(...rest);
} }
appendTrackedDialog(analyticsAction, analyticsInfo, ...rest) { public appendTrackedDialog<T extends any[]>(
analyticsAction: string,
analyticsInfo: string,
...rest: Parameters<ModalManager["appendDialog"]>
) {
Analytics.trackEvent('Modal', analyticsAction, analyticsInfo); Analytics.trackEvent('Modal', analyticsAction, analyticsInfo);
return this.appendDialog(...rest); return this.appendDialog<T>(...rest);
} }
createDialog(Element, ...rest) { public createDialog<T extends any[]>(
return this.createDialogAsync(Promise.resolve(Element), ...rest); Element: React.ComponentType,
...rest: ParametersWithoutFirst<ModalManager["createDialogAsync"]>
) {
return this.createDialogAsync<T>(Promise.resolve(Element), ...rest);
} }
appendDialog(Element, ...rest) { public appendDialog<T extends any[]>(
return this.appendDialogAsync(Promise.resolve(Element), ...rest); Element: React.ComponentType,
...rest: ParametersWithoutFirst<ModalManager["appendDialogAsync"]>
) {
return this.appendDialogAsync<T>(Promise.resolve(Element), ...rest);
} }
createTrackedDialogAsync(analyticsAction, analyticsInfo, ...rest) { public createTrackedDialogAsync<T extends any[]>(
analyticsAction: string,
analyticsInfo: string,
...rest: Parameters<ModalManager["appendDialogAsync"]>
) {
Analytics.trackEvent('Modal', analyticsAction, analyticsInfo); Analytics.trackEvent('Modal', analyticsAction, analyticsInfo);
return this.createDialogAsync(...rest); return this.createDialogAsync<T>(...rest);
} }
appendTrackedDialogAsync(analyticsAction, analyticsInfo, ...rest) { public appendTrackedDialogAsync<T extends any[]>(
analyticsAction: string,
analyticsInfo: string,
...rest: Parameters<ModalManager["appendDialogAsync"]>
) {
Analytics.trackEvent('Modal', analyticsAction, analyticsInfo); Analytics.trackEvent('Modal', analyticsAction, analyticsInfo);
return this.appendDialogAsync(...rest); return this.appendDialogAsync<T>(...rest);
} }
_buildModal(prom, props, className, options) { private buildModal<T extends any[]>(
const modal = {}; prom: Promise<React.ComponentType>,
props?: IProps<T>,
className?: string,
options?: IOptions<T>
) {
const modal: IModal<T> = {
onFinished: props ? props.onFinished : null,
onBeforeClose: options.onBeforeClose,
beforeClosePromise: null,
closeReason: null,
className,
// these will be set below but we need an object reference to pass to getCloseFn before we can do that
elem: null,
close: null,
};
// never call this from onFinished() otherwise it will loop // never call this from onFinished() otherwise it will loop
const [closeDialog, onFinishedProm] = this._getCloseFn(modal, props); const [closeDialog, onFinishedProm] = this.getCloseFn<T>(modal, props);
// don't attempt to reuse the same AsyncWrapper for different dialogs, // don't attempt to reuse the same AsyncWrapper for different dialogs,
// otherwise we'll get confused. // otherwise we'll get confused.
const modalCount = this._counter++; const modalCount = this.counter++;
// FIXME: If a dialog uses getDefaultProps it clobbers the onFinished // FIXME: If a dialog uses getDefaultProps it clobbers the onFinished
// property set here so you can't close the dialog from a button click! // property set here so you can't close the dialog from a button click!
modal.elem = ( modal.elem = <AsyncWrapper key={modalCount} prom={prom} {...props} onFinished={closeDialog} />;
<AsyncWrapper key={modalCount} prom={prom} {...props}
onFinished={closeDialog} />
);
modal.onFinished = props ? props.onFinished : null;
modal.className = className;
modal.onBeforeClose = options.onBeforeClose;
modal.beforeClosePromise = null;
modal.close = closeDialog; modal.close = closeDialog;
modal.closeReason = null;
return {modal, closeDialog, onFinishedProm}; return {modal, closeDialog, onFinishedProm};
} }
_getCloseFn(modal, props) { private getCloseFn<T extends any[]>(
const deferred = defer(); modal: IModal<T>,
return [async (...args) => { props: IProps<T>
): [IHandle<T>["close"], IHandle<T>["finished"]] {
const deferred = defer<T>();
return [async (...args: T) => {
if (modal.beforeClosePromise) { if (modal.beforeClosePromise) {
await modal.beforeClosePromise; await modal.beforeClosePromise;
} else if (modal.onBeforeClose) { } else if (modal.onBeforeClose) {
@ -147,26 +198,26 @@ class ModalManager {
} }
deferred.resolve(args); deferred.resolve(args);
if (props && props.onFinished) props.onFinished.apply(null, args); if (props && props.onFinished) props.onFinished.apply(null, args);
const i = this._modals.indexOf(modal); const i = this.modals.indexOf(modal);
if (i >= 0) { if (i >= 0) {
this._modals.splice(i, 1); this.modals.splice(i, 1);
} }
if (this._priorityModal === modal) { if (this.priorityModal === modal) {
this._priorityModal = null; this.priorityModal = null;
// XXX: This is destructive // XXX: This is destructive
this._modals = []; this.modals = [];
} }
if (this._staticModal === modal) { if (this.staticModal === modal) {
this._staticModal = null; this.staticModal = null;
// XXX: This is destructive // XXX: This is destructive
this._modals = []; this.modals = [];
} }
this._reRender(); this.reRender();
}, deferred.promise]; }, deferred.promise];
} }
@ -207,38 +258,49 @@ class ModalManager {
* @param {onBeforeClose} options.onBeforeClose a callback to decide whether to close the dialog * @param {onBeforeClose} options.onBeforeClose a callback to decide whether to close the dialog
* @returns {object} Object with 'close' parameter being a function that will close the dialog * @returns {object} Object with 'close' parameter being a function that will close the dialog
*/ */
createDialogAsync(prom, props, className, isPriorityModal, isStaticModal, options = {}) { private createDialogAsync<T extends any[]>(
const {modal, closeDialog, onFinishedProm} = this._buildModal(prom, props, className, options); prom: Promise<React.ComponentType>,
props?: IProps<T>,
className?: string,
isPriorityModal = false,
isStaticModal = false,
options: IOptions<T> = {}
): IHandle<T> {
const {modal, closeDialog, onFinishedProm} = this.buildModal<T>(prom, props, className, options);
if (isPriorityModal) { if (isPriorityModal) {
// XXX: This is destructive // XXX: This is destructive
this._priorityModal = modal; this.priorityModal = modal;
} else if (isStaticModal) { } else if (isStaticModal) {
// This is intentionally destructive // This is intentionally destructive
this._staticModal = modal; this.staticModal = modal;
} else { } else {
this._modals.unshift(modal); this.modals.unshift(modal);
} }
this._reRender(); this.reRender();
return { return {
close: closeDialog, close: closeDialog,
finished: onFinishedProm, finished: onFinishedProm,
}; };
} }
appendDialogAsync(prom, props, className) { private appendDialogAsync<T extends any[]>(
const {modal, closeDialog, onFinishedProm} = this._buildModal(prom, props, className, {}); prom: Promise<React.ComponentType>,
props?: IProps<T>,
className?: string
): IHandle<T> {
const {modal, closeDialog, onFinishedProm} = this.buildModal<T>(prom, props, className, {});
this._modals.push(modal); this.modals.push(modal);
this._reRender(); this.reRender();
return { return {
close: closeDialog, close: closeDialog,
finished: onFinishedProm, finished: onFinishedProm,
}; };
} }
onBackgroundClick() { private onBackgroundClick = () => {
const modal = this._getCurrentModal(); const modal = this.getCurrentModal();
if (!modal) { if (!modal) {
return; return;
} }
@ -249,21 +311,21 @@ class ModalManager {
modal.closeReason = "backgroundClick"; modal.closeReason = "backgroundClick";
modal.close(); modal.close();
modal.closeReason = null; modal.closeReason = null;
};
private getCurrentModal(): IModal<any> {
return this.priorityModal ? this.priorityModal : (this.modals[0] || this.staticModal);
} }
_getCurrentModal() { private reRender() {
return this._priorityModal ? this._priorityModal : (this._modals[0] || this._staticModal); if (this.modals.length === 0 && !this.priorityModal && !this.staticModal) {
}
_reRender() {
if (this._modals.length === 0 && !this._priorityModal && !this._staticModal) {
// If there is no modal to render, make all of Riot available // If there is no modal to render, make all of Riot available
// to screen reader users again // to screen reader users again
dis.dispatch({ dis.dispatch({
action: 'aria_unhide_main_app', action: 'aria_unhide_main_app',
}); });
ReactDOM.unmountComponentAtNode(this.getOrCreateContainer()); ReactDOM.unmountComponentAtNode(ModalManager.getOrCreateContainer());
ReactDOM.unmountComponentAtNode(this.getOrCreateStaticContainer()); ReactDOM.unmountComponentAtNode(ModalManager.getOrCreateStaticContainer());
return; return;
} }
@ -274,49 +336,48 @@ class ModalManager {
action: 'aria_hide_main_app', action: 'aria_hide_main_app',
}); });
if (this._staticModal) { if (this.staticModal) {
const classes = "mx_Dialog_wrapper mx_Dialog_staticWrapper " const classes = classNames("mx_Dialog_wrapper mx_Dialog_staticWrapper", this.staticModal.className);
+ (this._staticModal.className ? this._staticModal.className : '');
const staticDialog = ( const staticDialog = (
<div className={classes}> <div className={classes}>
<div className="mx_Dialog"> <div className="mx_Dialog">
{ this._staticModal.elem } { this.staticModal.elem }
</div> </div>
<div className="mx_Dialog_background mx_Dialog_staticBackground" onClick={this.onBackgroundClick}></div> <div className="mx_Dialog_background mx_Dialog_staticBackground" onClick={this.onBackgroundClick} />
</div> </div>
); );
ReactDOM.render(staticDialog, this.getOrCreateStaticContainer()); ReactDOM.render(staticDialog, ModalManager.getOrCreateStaticContainer());
} else { } else {
// This is safe to call repeatedly if we happen to do that // This is safe to call repeatedly if we happen to do that
ReactDOM.unmountComponentAtNode(this.getOrCreateStaticContainer()); ReactDOM.unmountComponentAtNode(ModalManager.getOrCreateStaticContainer());
} }
const modal = this._getCurrentModal(); const modal = this.getCurrentModal();
if (modal !== this._staticModal) { if (modal !== this.staticModal) {
const classes = "mx_Dialog_wrapper " const classes = classNames("mx_Dialog_wrapper", modal.className, {
+ (this._staticModal ? "mx_Dialog_wrapperWithStaticUnder " : '') mx_Dialog_wrapperWithStaticUnder: this.staticModal,
+ (modal.className ? modal.className : ''); });
const dialog = ( const dialog = (
<div className={classes}> <div className={classes}>
<div className="mx_Dialog"> <div className="mx_Dialog">
{modal.elem} {modal.elem}
</div> </div>
<div className="mx_Dialog_background" onClick={this.onBackgroundClick}></div> <div className="mx_Dialog_background" onClick={this.onBackgroundClick} />
</div> </div>
); );
ReactDOM.render(dialog, this.getOrCreateContainer()); ReactDOM.render(dialog, ModalManager.getOrCreateContainer());
} else { } else {
// This is safe to call repeatedly if we happen to do that // This is safe to call repeatedly if we happen to do that
ReactDOM.unmountComponentAtNode(this.getOrCreateContainer()); ReactDOM.unmountComponentAtNode(ModalManager.getOrCreateContainer());
} }
} }
} }
if (!global.singletonModalManager) { if (!window.singletonModalManager) {
global.singletonModalManager = new ModalManager(); window.singletonModalManager = new ModalManager();
} }
export default global.singletonModalManager; export default window.singletonModalManager;

View file

@ -401,14 +401,16 @@ export const Commands = [
// If we need an identity server but don't have one, things // If we need an identity server but don't have one, things
// get a bit more complex here, but we try to show something // get a bit more complex here, but we try to show something
// meaningful. // meaningful.
let finished = Promise.resolve(); let prom = Promise.resolve();
if ( if (
getAddressType(address) === 'email' && getAddressType(address) === 'email' &&
!MatrixClientPeg.get().getIdentityServerUrl() !MatrixClientPeg.get().getIdentityServerUrl()
) { ) {
const defaultIdentityServerUrl = getDefaultIdentityServerUrl(); const defaultIdentityServerUrl = getDefaultIdentityServerUrl();
if (defaultIdentityServerUrl) { if (defaultIdentityServerUrl) {
({ finished } = Modal.createTrackedDialog('Slash Commands', 'Identity server', const { finished } = Modal.createTrackedDialog<[boolean]>(
'Slash Commands',
'Identity server',
QuestionDialog, { QuestionDialog, {
title: _t("Use an identity server"), title: _t("Use an identity server"),
description: <p>{_t( description: <p>{_t(
@ -421,9 +423,9 @@ export const Commands = [
)}</p>, )}</p>,
button: _t("Continue"), button: _t("Continue"),
}, },
)); );
finished = finished.then(([useDefault]: any) => { prom = finished.then(([useDefault]) => {
if (useDefault) { if (useDefault) {
useDefaultIdentityServer(); useDefaultIdentityServer();
return; return;
@ -435,7 +437,7 @@ export const Commands = [
} }
} }
const inviter = new MultiInviter(roomId); const inviter = new MultiInviter(roomId);
return success(finished.then(() => { return success(prom.then(() => {
return inviter.invite([address]); return inviter.invite([address]);
}).then(() => { }).then(() => {
if (inviter.getCompletionState(address) !== "invited") { if (inviter.getCompletionState(address) !== "invited") {