-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathuseChangeInputWithConfirmation.tsx
More file actions
78 lines (68 loc) · 2.46 KB
/
useChangeInputWithConfirmation.tsx
File metadata and controls
78 lines (68 loc) · 2.46 KB
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
import React from 'react';
import NiceModal from '@ebay/nice-modal-react';
import {useTypedSelector} from '..';
import {CONFIRMATION_DIALOG} from '../../../components/ConfirmationDialog/ConfirmationDialog';
import {SaveQueryButton} from '../../../containers/Tenant/Query/SaveQuery/SaveQuery';
import {selectIsDirty, selectUserInput} from '../../../store/reducers/query/query';
import i18n from './i18n';
function ExtendedSaveQueryButton() {
const modal = NiceModal.useModal(CONFIRMATION_DIALOG);
const closeModal = React.useCallback(() => {
modal.hide();
modal.remove();
}, [modal]);
const handleSaveQuerySuccess = React.useCallback(() => {
modal.resolve(true);
closeModal();
}, [modal, closeModal]);
const handleCancelQuerySave = React.useCallback(() => {
modal.resolve(false);
closeModal();
}, [closeModal, modal]);
const dialogProps = React.useMemo(
() => ({
onSuccess: handleSaveQuerySuccess,
onCancel: handleCancelQuerySave,
}),
[handleSaveQuerySuccess, handleCancelQuerySave],
);
return <SaveQueryButton view="action" size="l" dialogProps={dialogProps} />;
}
export async function getConfirmation(): Promise<boolean> {
return await NiceModal.show(CONFIRMATION_DIALOG, {
id: CONFIRMATION_DIALOG,
caption: i18n('context_unsaved-changes-warning'),
textButtonApply: i18n('action_apply'),
propsButtonApply: {view: 'l'},
renderButtons: (buttonApply: React.ReactNode, buttonCancel: React.ReactNode) => {
return (
<React.Fragment>
{buttonCancel}
<ExtendedSaveQueryButton />
{buttonApply}
</React.Fragment>
);
},
});
}
export function changeInputWithConfirmation<T>(callback: (args: T) => void) {
return async (args: T) => {
const confirmed = await getConfirmation();
if (!confirmed) {
return;
}
callback(args);
};
}
export function useChangeInputWithConfirmation<T>(callback: (args: T) => void) {
const userInput = useTypedSelector(selectUserInput);
const isDirty = useTypedSelector(selectIsDirty);
const callbackWithConfirmation = React.useMemo(
() => changeInputWithConfirmation<T>(callback),
[callback],
);
if (!userInput || !isDirty) {
return callback;
}
return callbackWithConfirmation;
}