@drivy/cobalt
Version:
Opinionated design system for Drivy's projects.
48 lines (45 loc) • 2.17 kB
JavaScript
import { jsxs, jsx } from 'react/jsx-runtime';
import cx from 'classnames';
import { forwardRef, useRef, useState, useEffect, useCallback } from 'react';
import { withFieldLabelAndHint } from './field.js';
const TextArea = forwardRef((props, ref) => {
const { autosize, className, inputClassName, status, maxLength, onChange, ...nativeProps } = props;
const internalRef = useRef(null);
const [length, setLength] = useState(0);
const [height, setHeight] = useState(0);
const hasAutosize = autosize || (maxLength && maxLength > 0);
useEffect(() => {
if (ref && "current" in ref) {
ref.current = internalRef.current;
}
}, [ref]);
const handleAutosize = useCallback((el) => {
if (!el)
return;
if (hasAutosize) {
setLength(el.value.length);
setHeight(el.scrollHeight + 2);
}
}, [hasAutosize]);
useEffect(() => {
handleAutosize(internalRef.current);
}, [handleAutosize]);
const handleChange = (event) => {
handleAutosize(event.target);
onChange === null || onChange === void 0 ? void 0 : onChange(event);
};
return (jsxs("div", { className: cx("cobalt-TextAreaField", className, {
"cobalt-TextAreaField--withLimit": maxLength && maxLength > 0,
"cobalt-TextAreaField--success": status === "success",
"cobalt-TextAreaField--error": status === "error",
}), children: [jsx("textarea", { ...nativeProps, maxLength: maxLength, style: hasAutosize
? {
height: `${height}px`,
}
: {}, onChange: handleChange, className: cx("cobalt-TextAreaField__Input", inputClassName), ref: internalRef }), length > 0 && maxLength && maxLength > 0 && (jsxs("div", { className: "cobalt-TextAreaField__RemainingChars", children: [maxLength - length, " remaining characters"] }))] }));
});
TextArea.displayName = "TextArea";
const wrappedComponent = withFieldLabelAndHint(TextArea);
wrappedComponent.displayName = "TextArea";
export { wrappedComponent as TextArea };
//# sourceMappingURL=TextArea.js.map