File size: 7,445 Bytes
ae01f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
/////////////////////////////////////////////////////////////
//
// pgAdmin 4 - PostgreSQL Tools
//
// Copyright (C) 2013 - 2024, The pgAdmin Development Team
// This software is released under the PostgreSQL Licence
//
//////////////////////////////////////////////////////////////

import { SnackbarProvider, SnackbarContent } from 'notistack';
import { makeStyles } from '@mui/styles';
import {Box} from '@mui/material';
import CloseIcon from '@mui/icons-material/CloseRounded';
import { DefaultButton, PrimaryButton } from '../components/Buttons';
import HTMLReactParser from 'html-react-parser';
import CheckRoundedIcon from '@mui/icons-material/CheckRounded';
import PropTypes from 'prop-types';
import React, { useEffect } from 'react';
import { NotifierMessage, MESSAGE_TYPE } from '../components/FormComponents';
import CustomPropTypes from '../custom_prop_types';
import gettext from 'sources/gettext';
import _ from 'lodash';
import { useModal } from './ModalProvider';
import { parseApiError } from '../api_instance';

const AUTO_HIDE_DURATION = 3000;  // In milliseconds

export const FinalNotifyContent = React.forwardRef(({children}, ref) => {
  return <SnackbarContent style= {{ justifyContent: 'end', maxWidth: '700px' }} ref={ref}>{children}</SnackbarContent>;
});
FinalNotifyContent.displayName = 'FinalNotifyContent';
FinalNotifyContent.propTypes = {
  children: CustomPropTypes.children,
};

const useModalStyles = makeStyles((theme)=>({
  footer: {
    display: 'flex',
    justifyContent: 'flex-end',
    padding: '0.5rem',
    ...theme.mixins.panelBorder.top,
  },
  margin: {
    marginLeft: '0.25rem',
  },
}));
function AlertContent({text, confirm, okLabel=gettext('OK'), cancelLabel=gettext('Cancel'), onOkClick, onCancelClick}) {
  const classes = useModalStyles();
  return (
    <Box display="flex" flexDirection="column" height="100%">
      <Box flexGrow="1" p={2}>{HTMLReactParser(text)}</Box>
      <Box className={classes.footer}>
        {confirm &&
          <DefaultButton startIcon={<CloseIcon />} onClick={onCancelClick} >{cancelLabel}</DefaultButton>
        }
        <PrimaryButton className={classes.margin} startIcon={<CheckRoundedIcon />} onClick={onOkClick} autoFocus={true} >{okLabel}</PrimaryButton>
      </Box>
    </Box>
  );
}
AlertContent.propTypes = {
  text: PropTypes.string,
  confirm: PropTypes.bool,
  onOkClick: PropTypes.func,
  onCancelClick: PropTypes.func,
  okLabel: PropTypes.string,
  cancelLabel: PropTypes.string,
};

// This can be called from iframe,
// so need to separate the context to avoid hooks error
class SnackbarNotifier {
  constructor(snackbar) {
    this.snackbarObj = snackbar;
  }

  notify(content, autoHideDuration) {
    if (content) {
      let  options = {autoHideDuration, content:(key) => (
        <FinalNotifyContent>{React.cloneElement(content, {onClose:()=>{this.snackbarObj.closeSnackbar(key);}})}</FinalNotifyContent>
      )};
      options.content.displayName = 'content';
      this.snackbarObj.enqueueSnackbar(null, options);
    }
  }

  callNotify(msg, type, autoHideDuration) {
    this.notify(
      <NotifierMessage style={{maxWidth: '50vw'}} type={type} message={msg} closable={true} />,
      autoHideDuration
    );
  }
}

class Notifier {
  constructor(modal, snackbar) {
    this.modal = modal;
    this.snackbar = snackbar;
  }

  success(msg, autoHideDuration = AUTO_HIDE_DURATION) {
    this.snackbar.callNotify(msg, MESSAGE_TYPE.SUCCESS, autoHideDuration);
  }

  warning(msg, autoHideDuration = AUTO_HIDE_DURATION) {
    this.snackbar.callNotify(msg, MESSAGE_TYPE.WARNING, autoHideDuration);
  }

  info(msg, autoHideDuration = AUTO_HIDE_DURATION) {
    this.snackbar.callNotify(msg, MESSAGE_TYPE.INFO, autoHideDuration);
  }

  error(msg, autoHideDuration = AUTO_HIDE_DURATION) {
    this.snackbar.callNotify(msg, MESSAGE_TYPE.ERROR, autoHideDuration);
  }

  // proxy
  notify(...args) {
    this.snackbar.notify(...args);
  }

  pgRespErrorNotify(error, prefixMsg='') {
    if (error.response?.status === 410) {
      this.alert(gettext('Error: Object not found - %s.', error.response.statusText), parseApiError(error));
    } else {
      this.error(prefixMsg + ' ' + parseApiError(error));
    }
  }

  pgNotifier(type, error, promptmsg, onJSONResult) {
    let msg;

    if(!error.response) {
      msg = parseApiError(error);
      promptmsg = gettext('Connection Lost');
    } else if(error.response.headers['content-type'] == 'application/json') {
      let resp = error.response.data;
      if(resp.info == 'CRYPTKEY_MISSING') {
        let pgBrowser = window.pgAdmin.Browser;
        pgBrowser.set_master_password('', ()=> {
          if(onJSONResult && typeof(onJSONResult) == 'function') {
            onJSONResult('CRYPTKEY_SET');
          }
        }, ()=> {
          if(onJSONResult && typeof(onJSONResult) == 'function') {
            onJSONResult('CRYPTKEY_NOT_SET');
          }
        });
        return;
      } else if (resp.result != null && (!resp.errormsg || resp.errormsg == '') &&
        onJSONResult && typeof(onJSONResult) == 'function') {
        return onJSONResult(resp.result);
      }
      msg = _.escape(resp.result) || _.escape(resp.errormsg) || 'Unknown error';
    } else {
      if (type === 'error') {
        this.alert('Error', promptmsg);
      }
      return;
    }
    if(type == 'error-noalert' && onJSONResult && typeof(onJSONResult) == 'function') {
      return onJSONResult();
    }
    this.alert(promptmsg, msg.replace(new RegExp(/\r?\n/, 'g'), '<br />'));
    onJSONResult('ALERT_CALLED');
  }

  alert(title, text, onOkClick, okLabel=gettext('OK')) {
    /* Use this if you want to use pgAdmin global notifier.
    Or else, if you want to use modal inside iframe only then use ModalProvider eg- query tool */
    this.modal.alert(title, text, onOkClick, okLabel);
  }

  confirm(title, text, onOkClick, onCancelClick, okLabel=gettext('Yes'), cancelLabel=gettext('No')) {
    /* Use this if you want to use pgAdmin global notifier.
    Or else, if you want to use modal inside iframe only then use ModalProvider eg- query tool */
    this.modal.confirm(title, text, onOkClick, onCancelClick, okLabel, cancelLabel);
  }

  showModal(title, content, modalOptions) {
    this.modal.showModal(title, content, modalOptions);
  }
}

export function NotifierProvider({ pgAdmin, pgWindow, getInstance, children, onReady }) {
  const modal = useModal();

  useEffect(()=>{
    // if open in an iframe then use top pgAdmin
    if(window.self != window.top) {
      pgAdmin.Browser.notifier = new Notifier(modal, pgWindow.pgAdmin.Browser.notifier.snackbar);
      onReady?.();
      getInstance?.(pgAdmin.Browser.notifier);
    }
  }, []);

  // if open in a window, then create your own Snackbar
  if(window.self == window.top) {
    return (
      <SnackbarProvider
        maxSnack={30}
        anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
        ref={(obj)=>{
          pgAdmin.Browser.notifier = new Notifier(modal, new SnackbarNotifier(obj));
          getInstance?.(pgAdmin.Browser.notifier);
          onReady?.();
        }}
      >
        {children}
      </SnackbarProvider>
    );
  }
  return (
    <>
      {children}
    </>
  );
}

NotifierProvider.propTypes = {
  pgAdmin: PropTypes.object,
  pgWindow: PropTypes.object,
  getInstance: PropTypes.func,
  children: CustomPropTypes.children,
  onReady: PropTypes.func,
};

export default Notifier;