UNPKG

envoc-form

Version:

Envoc form components

70 lines (69 loc) 3.01 kB
var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; import { useEffect } from 'react'; /** Only use this if the project uses `<BrowserRouter/>` or any router that does not support the new * [react-router Data API](https://reactrouter.com/en/main/routers/picking-a-router#using-v64-data-apis) * * Legacy function to prevent the user from navigating away from a form if there are any changes. */ export default function LegacyFormBasedPreventNavigation(_a) { var _b = _a.promptMessage, promptMessage = _b === void 0 ? 'Changes you made may not be saved.' : _b, preventNavigate = _a.preventNavigate, navigator = _a.navigator; useEffect(function () { if (!preventNavigate) { return; } var unblock = function () { }; var push = navigator.push; // TODO: https://reactrouter.com/docs/en/v6/upgrading/v5#prompt-is-not-currently-supported // this is a workaround until we get native support for prompt on navigate if (navigator.block) { var blocker_1 = function (tx) { if (window.confirm(promptMessage)) { tx.retry(); } }; unblock = navigator.block(function (tx) { var autoUnblockingTx = __assign(__assign({}, tx), { retry: function () { // Automatically unblock the transition so it can play all the way // through before retrying it. TODO: Figure out how to re-enable // this block if the transition is cancelled for some reason. unblock(); tx.retry(); } }); blocker_1(autoUnblockingTx); }); } else { //https://gist.github.com/MarksCode/64e438c82b0b2a1161e01c88ca0d0355 navigator.push = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (window.confirm(promptMessage)) { push.apply(void 0, args); } }; } window.addEventListener('beforeunload', beforeUnload); return function () { unblock(); navigator.push = push; window.removeEventListener('beforeunload', beforeUnload); }; function beforeUnload(e) { e.preventDefault(); e.returnValue = promptMessage; } }, [preventNavigate, promptMessage, navigator]); return null; }