You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
54 lines
2.3 KiB
54 lines
2.3 KiB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { |
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } |
|
return new (P || (P = Promise))(function (resolve, reject) { |
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } |
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } |
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } |
|
step((generator = generator.apply(thisArg, _arguments || [])).next()); |
|
}); |
|
}; |
|
import { useState, useEffect, useCallback, useContext } from 'react'; |
|
import { ConfirmContext } from './ConfirmContext'; |
|
const noop = () => { |
|
/*No Operation*/ |
|
}; |
|
const initialConfirmState = { |
|
isActive: false, |
|
proceed: noop, |
|
cancel: noop, |
|
}; |
|
const useConfirm = () => { |
|
const [confirm, setConfirm] = useState(initialConfirmState); |
|
const { setResolve } = useContext(ConfirmContext) || {}; |
|
useEffect(() => { |
|
if (confirm.isActive) { |
|
window.onbeforeunload = () => { |
|
return false; |
|
}; |
|
} |
|
return () => { |
|
if (confirm.isActive) |
|
window.onbeforeunload = null; |
|
}; |
|
}, [confirm]); |
|
const resetConfirmation = useCallback(() => { |
|
setConfirm(initialConfirmState); |
|
}, []); |
|
const onConfirm = () => __awaiter(void 0, void 0, void 0, function* () { |
|
const promise = new Promise((resolve, reject) => { |
|
setConfirm((prevState) => (Object.assign(Object.assign({}, prevState), { isActive: true, proceed: resolve, cancel: reject }))); |
|
}); |
|
return promise.then(() => { |
|
setResolve === null || setResolve === void 0 ? void 0 : setResolve(true); |
|
setConfirm(Object.assign(Object.assign({}, confirm), { isActive: false })); |
|
return true; |
|
}, () => { |
|
setConfirm(Object.assign(Object.assign({}, confirm), { isActive: false })); |
|
setResolve === null || setResolve === void 0 ? void 0 : setResolve(false); |
|
return false; |
|
}); |
|
}); |
|
return Object.assign(Object.assign({}, confirm), { onConfirm, |
|
resetConfirmation }); |
|
}; |
|
export default useConfirm;
|
|
|