UNPKG

@navikt/ds-react

Version:

React components from the Norwegian Labour and Welfare Administration.

46 lines 2.93 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.useFormField = void 0; const clsx_1 = __importDefault(require("clsx")); const react_1 = require("react"); const hooks_1 = require("../util/hooks"); const context_1 = require("./fieldset/context"); /** * Handles props and their state for various form-fields in context with Fieldset */ const useFormField = (props, prefix) => { var _a, _b, _c; const { size, error, errorId: propErrorId } = props; const fieldset = (0, react_1.useContext)(context_1.FieldsetContext); const genId = (0, hooks_1.useId)(); const id = (_a = props.id) !== null && _a !== void 0 ? _a : `${prefix}-${genId}`; const errorId = propErrorId !== null && propErrorId !== void 0 ? propErrorId : `${prefix}-error-${genId}`; const inputDescriptionId = `${prefix}-description-${genId}`; const disabled = (fieldset === null || fieldset === void 0 ? void 0 : fieldset.disabled) || props.disabled; const readOnly = (((fieldset === null || fieldset === void 0 ? void 0 : fieldset.readOnly) || props.readOnly) && !disabled) || undefined; const hasError = !disabled && !readOnly && !!(error || (fieldset === null || fieldset === void 0 ? void 0 : fieldset.error)); const showErrorMsg = !disabled && !readOnly && !!error && typeof error !== "boolean"; const ariaInvalid = Object.assign({}, (hasError ? { "aria-invalid": true } : {})); if ((props === null || props === void 0 ? void 0 : props.required) && process.env.NODE_ENV !== "production") { console.warn("Aksel: Use of 'required' in form-elements is heavily discuouraged. Docs about why here:"); console.warn("https://aksel.nav.no/god-praksis/artikler/obligatoriske-og-valgfrie-skjemafelter#h3bfe00453471"); } return { showErrorMsg, hasError, errorId, inputDescriptionId, size: (_b = size !== null && size !== void 0 ? size : fieldset === null || fieldset === void 0 ? void 0 : fieldset.size) !== null && _b !== void 0 ? _b : "medium", readOnly, inputProps: Object.assign(Object.assign({ id }, ariaInvalid), { "aria-describedby": (0, clsx_1.default)(props["aria-describedby"], { [inputDescriptionId]: !!(props === null || props === void 0 ? void 0 : props.description) && typeof (props === null || props === void 0 ? void 0 : props.description) === "string", [errorId]: showErrorMsg, [(_c = fieldset === null || fieldset === void 0 ? void 0 : fieldset.errorId) !== null && _c !== void 0 ? _c : ""]: hasError && !!(fieldset === null || fieldset === void 0 ? void 0 : fieldset.error), }) || undefined, disabled }), }; }; exports.useFormField = useFormField; //# sourceMappingURL=useFormField.js.map