@navikt/ds-react
Version:
React components from the Norwegian Labour and Welfare Administration.
54 lines • 3.02 kB
JavaScript
import cl from "clsx";
import React, { useContext } from "react";
import { ReadMore } from "../read-more/ReadMore.js";
import { useId } from "../util/hooks/index.js";
import { FieldsetContext } from "./fieldset/context.js";
/**
* Handles props and their state for various form-fields in context with Fieldset
*/
export const useFormField = (props, prefix) => {
var _a, _b, _c;
const { size, error, errorId: propErrorId } = props;
const fieldset = useContext(FieldsetContext);
const genId = 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#dc7a536235fa");
}
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": cl(props["aria-describedby"], {
[inputDescriptionId]: props.description && !containsReadMore(props.description),
[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 }),
};
};
export function containsReadMore(children, checkNested = true) {
if (React.isValidElement(children)) {
if (children.type === ReadMore) {
return true;
}
if (children.props.children && checkNested) {
return containsReadMore(children.props.children, false);
}
}
else if (Array.isArray(children)) {
return children.some((child) => containsReadMore(child, checkNested));
}
return false;
}
//# sourceMappingURL=useFormField.js.map