infinity-forge
Version:
66 lines • 3.11 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.useTabWithFormHandler = useTabWithFormHandler;
var ui_1 = require("../../../../../ui/index.js");
var react_1 = require("react");
function useTabWithFormHandler(props) {
var _a;
var formHandler = (0, ui_1.useFormHandler)();
(0, react_1.useEffect)(function () {
var _a, _b;
if (!formHandler || !((_a = props === null || props === void 0 ? void 0 : props.tabs) === null || _a === void 0 ? void 0 : _a.length))
return;
var tabReference = props.tabID;
var errors = (_b = formHandler === null || formHandler === void 0 ? void 0 : formHandler.formik) === null || _b === void 0 ? void 0 : _b.errors;
if (!errors || Object.keys(errors).length === 0)
return;
// Recursivo e compatível com arrays aninhadas
var getFirstErrorPath = function (obj, prefix) {
if (prefix === void 0) { prefix = ''; }
if (!obj)
return null;
if (typeof obj === 'string')
return prefix;
if (Array.isArray(obj)) {
for (var i = 0; i < obj.length; i++) {
var nested = getFirstErrorPath(obj[i], "".concat(prefix, "[").concat(i, "]"));
if (nested)
return nested;
}
}
if (typeof obj === 'object') {
for (var _i = 0, _a = Object.keys(obj); _i < _a.length; _i++) {
var key = _a[_i];
var newPrefix = prefix ? "".concat(prefix, ".").concat(key) : key;
var nested = getFirstErrorPath(obj[key], newPrefix);
if (nested)
return nested;
}
}
return null;
};
var handleTabAndScroll = function () {
var firstErrorPath = getFirstErrorPath(errors);
if (!firstErrorPath)
return;
var errorElement = document.querySelector("[name=\"".concat(firstErrorPath, "\"]"));
if (!errorElement)
return;
var tabContainer = errorElement.closest("[id^=\"".concat(tabReference, "_\"]"));
if (!tabContainer)
return;
var tabContainerId = tabContainer.id;
var tabKey = tabContainerId.replace("".concat(tabReference, "_"), '');
props.changeTab(tabKey);
// Scroll + focus no campo com erro
setTimeout(function () {
var _a;
errorElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
(_a = errorElement.focus) === null || _a === void 0 ? void 0 : _a.call(errorElement);
}, 300);
};
var timeout = setTimeout(handleTabAndScroll, 100);
return function () { return clearTimeout(timeout); };
}, [(_a = formHandler === null || formHandler === void 0 ? void 0 : formHandler.formik) === null || _a === void 0 ? void 0 : _a.errors]);
}
//# sourceMappingURL=index.js.map