confirmAlert.tsx 2.31 KB
Newer Older
Maxym Borodenko's avatar
Maxym Borodenko committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import Button from 'material-ui/Button';
import Dialog, {
    DialogActions,
    DialogContent,
    DialogContentText,
    DialogTitle,
} from 'material-ui/Dialog';

interface IConfirmProps extends React.ClassAttributes<any> {
    message: string;
    description: string;
    confirmLabel?: string;
    abortLabel?: string;
}

function PromiseWrapper() {
    this.with = (callback) => new Promise((resolve, reject) => {
        this.resolve = () => {
            resolve();
            callback();
        };
        this.reject = () => {
            reject();
            callback();
        };
    });
}

class Confirm extends React.Component<IConfirmProps, any> {

    public promise = new PromiseWrapper();

    private resolve = () => {
        this.promise.resolve();
    }

    private reject = () => {
        this.promise.reject();
    }

    public render() {
        const {message, description, confirmLabel = 'OK', abortLabel = 'Cancel'} = this.props;

        return (
            <Dialog
                open
                onClose={ this.resolve }
                aria-labelledby="alert-dialog-title"
                aria-describedby="alert-dialog-description"
            >
                <DialogTitle id="alert-dialog-title">{ message }</DialogTitle>
                <DialogContent>
                    <DialogContentText id="alert-dialog-description">
                        { description }
                    </DialogContentText>
                </DialogContent>
                <DialogActions>
                    <Button onClick={ this.reject } autoFocus>
                        { abortLabel }
                    </Button>
                    <Button onClick={ this.resolve } color="primary">
                      { confirmLabel }
                    </Button>
                </DialogActions>
            </Dialog>
        );
    }

}

export default (message, options = {}) => {
    const props: any = {message, ...options};

    const wrapper = document.body.appendChild(document.createElement('div'));
    const component = ReactDOM.render(React.createElement(Confirm, props), wrapper);

    const cleanup = () => {
        ReactDOM.unmountComponentAtNode(wrapper);
        setTimeout(() => wrapper.remove());
    };
    return component.promise.with(cleanup);
};