confirmAlert.tsx 2.49 KB
Newer Older
Maxym Borodenko's avatar
Maxym Borodenko committed
1
2
import * as React from 'react';
import * as ReactDOM from 'react-dom';
Matija Obreza's avatar
Matija Obreza committed
3
4
5
6
7
8
9
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';

Maxym Borodenko's avatar
Maxym Borodenko committed
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

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