UNPKG

@activecollab/components

Version:

ActiveCollab Components

72 lines 2.37 kB
import _extends from "@babel/runtime/helpers/esm/extends"; import React, { useState, useCallback, forwardRef, useRef, useEffect } from "react"; import classnames from "classnames"; import { StyledAutoResizeTextarea } from "./Styles"; import useForkRef from "../../utils/useForkRef"; export const AutoResizeTextarea = /*#__PURE__*/forwardRef((_ref, ref) => { let { minRows = 1, maxRows = 6, lineHeight = 18, onChange, className, preventNewRowOnEnter = false, cursorAtTextEnd = false, onKeyDown, value, mode = "outlined", ...rest } = _ref; const innerRef = useRef(null); const [rows, setRows] = useState(minRows); const handleRef = useForkRef(ref, innerRef); const calcRows = useCallback(elem => { if (elem) { const previousRows = elem.rows || minRows; elem.rows = minRows; const currentRows = Math.floor(elem.scrollHeight / lineHeight); if (currentRows === previousRows) { elem.rows = currentRows; } if (currentRows >= maxRows) { elem.rows = maxRows; elem.scrollTop = elem.scrollHeight; } setRows(currentRows < maxRows ? currentRows : maxRows); } }, [lineHeight, maxRows, minRows]); useEffect(() => { calcRows(innerRef.current); }, [value, calcRows]); const handleOnChange = useCallback(e => { calcRows(e.target); typeof onChange === "function" && onChange(e); }, [onChange, calcRows]); const handleFocus = useCallback(e => { if (cursorAtTextEnd) { e.target.setSelectionRange(e.target.value.length, e.target.value.length); } }, [cursorAtTextEnd]); const handleTextAreaKeyDown = useCallback(e => { if (preventNewRowOnEnter && e.key === "Enter") { e.preventDefault(); } typeof onKeyDown === "function" && onKeyDown(e); }, [preventNewRowOnEnter, onKeyDown]); return /*#__PURE__*/React.createElement(StyledAutoResizeTextarea, _extends({}, rest, { value: value, ref: handleRef, onChange: handleOnChange, onKeyDown: handleTextAreaKeyDown, onFocus: handleFocus, rows: rows, mode: mode, className: classnames("c-autoresizetextarea", className), style: { minHeight: lineHeight + "px", lineHeight: lineHeight + "px" } })); }); AutoResizeTextarea.displayName = "AutoResizeTextarea"; //# sourceMappingURL=AutoResizeTextarea.js.map