@kwiz/fluentui
Version:
KWIZ common controls for FluentUI
50 lines • 2.35 kB
JavaScript
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { MessageBar } from "@fluentui/react-components";
import { isNotEmptyString, isNullOrEmptyString, jsonClone, stringEqualsOrEmpty } from "@kwiz/common";
import React, { useCallback, useEffect, useState } from "react";
//create context
export const FormValidationContext = React.createContext({});
/** fields inside a FormEX component can react to validation errors */
export function useFormValidationContext() {
const ctx = React.useContext(FormValidationContext);
return ctx;
}
/** Creates a form validation context, reports back if form is valid so you can enable/disable the save button */
export function Internal_FormEX({ children, onValid, submitError }) {
const [showErrors, setShowErrors] = useState(false);
const [errors, setErrors] = useState({});
useEffect(() => {
let valid = true;
Object.values(errors).forEach(value => {
if (isNotEmptyString(value))
valid = false;
});
onValid === null || onValid === void 0 ? void 0 : onValid(valid);
}, [errors, onValid]);
const setError = useCallback((error, key) => {
//clear form errors on any other field change...
let clearFormError = isNotEmptyString(key);
key = isNullOrEmptyString(key) ? "form" : key;
//current error
const currentError = errors[key];
if (!stringEqualsOrEmpty(currentError, error)) {
clearFormError = clearFormError && isNullOrEmptyString(error);
const newErrors = jsonClone(errors);
if (clearFormError)
delete newErrors.form;
newErrors[key] = error;
//report back to a form errors collection
setErrors(newErrors);
}
}, [errors]);
useEffect(() => {
if (!showErrors && isNotEmptyString(submitError))
setShowErrors(true);
}, [submitError, showErrors]);
return _jsxs(FormValidationContext.Provider, { value: {
errors,
setError,
showErrors
}, children: [isNotEmptyString(submitError) && _jsx(MessageBar, { intent: "error", children: submitError }), isNotEmptyString(errors.form) && _jsx(MessageBar, { intent: "error", children: errors.form }), children] });
}
//# sourceMappingURL=form-context.js.map