UNPKG

wix-style-react

Version:
431 lines (430 loc) • 15.9 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); exports.__esModule = true; exports.default = void 0; var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _react = _interopRequireDefault(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _StatusIndicator = _interopRequireDefault(require("../StatusIndicator")); var _constants = require("../StatusIndicator/constants.js"); var _debounce = _interopRequireDefault(require("lodash/debounce")); var _isNaN = _interopRequireDefault(require("lodash/isNaN")); var _InputAreaSt = require("./InputArea.st.css"); var _constants2 = require("./constants"); var _filterObject = require("../utils/filterObject"); var _StatusContext = require("../FormField/StatusContext"); var _context = require("../WixStyleReactProvider/context"); var _jsxFileName = "/home/builduser/work/a9c1ac8876d5057c/packages/wix-style-react/dist/cjs/InputArea/InputArea.js"; /** * General inputArea container */ class InputArea extends _react.default.PureComponent { constructor() { super(...arguments); this._computedStyle = null; this.state = { focus: false, counter: (this.props.value || this.props.defaultValue || '').length, computedRows: this.props.minRowsAutoGrow }; // For testing purposes only this._getDataAttr = _ref => { var { statusContext } = _ref; var { size, status, disabled, resizable, forceHover, forceFocus } = this.props; return (0, _filterObject.filterObject)({ [_constants2.dataAttr.SIZE]: size, [_constants2.dataAttr.STATUS]: !disabled ? (0, _StatusContext.getStatusFromContext)(statusContext, status) : null, [_constants2.dataAttr.DISABLED]: !!disabled, [_constants2.dataAttr.RESIZABLE]: !!resizable && !disabled, [_constants2.dataAttr.HOVER]: !!forceHover, [_constants2.dataAttr.FOCUS]: !!(forceFocus || this.state.focus) }, (key, value) => !!value); }; this.focus = () => { this.textArea && this.textArea.focus(); }; this.blur = () => { this.textArea && this.textArea.blur(); }; this.select = () => { this.textArea && this.textArea.select(); }; this._onFocus = e => { this.setState({ focus: true }); this.props.onFocus && this.props.onFocus(e); if (this.props.autoSelect) { // Set timeout is needed here since onFocus is called before react // gets the reference for the input (specifically when autoFocus // is on. So setTimeout ensures we have the ref.input needed in select) setTimeout(() => this.select(), 0); } }; this._onBlur = e => { this.setState({ focus: false }); this.props.onBlur && this.props.onBlur(e); }; this._onKeyDown = e => { this.props.onKeyDown && this.props.onKeyDown(e); if (e.key === 'Enter') { this.props.onEnterPressed && this.props.onEnterPressed(e); } else if (e.key === 'Escape') { this.props.onEscapePressed && this.props.onEscapePressed(); } }; this._onChange = e => { this.props.onChange && this.props.onChange(e); }; this._onInput = () => { this._calculateComputedRows(); }; this._calculateComputedRows = () => { var { minRowsAutoGrow } = this.props; this.setState({ computedRows: 1 }, () => { var rowsCount = this._getRowsCount(); var computedRows = Math.max(minRowsAutoGrow, rowsCount); this.setState({ computedRows }); }); }; this._updateComputedStyle = (0, _debounce.default)(() => { this._computedStyle = window.getComputedStyle(this.textArea); }, 500, { leading: true }); this._getComputedStyle = () => { this._updateComputedStyle(); return this._computedStyle; }; this._getRowsCount = () => { var computedStyle = this._getComputedStyle(); var fontSize = parseInt(computedStyle.getPropertyValue('font-size'), 10); var lineHeight = parseInt(computedStyle.getPropertyValue('line-height'), 10); var lineHeightValue; if ((0, _isNaN.default)(lineHeight)) { if ((0, _isNaN.default)(fontSize)) { return InputArea.MIN_ROWS; } lineHeightValue = this._getDefaultLineHeight() * fontSize; } else { lineHeightValue = lineHeight; } return Math.floor(this.textArea.scrollHeight / lineHeightValue); }; this._getDefaultLineHeight = () => { if (!this._defaultLineHeight) { var { parentNode } = this.textArea; var computedStyles = this._getComputedStyle(); var fontFamily = computedStyles.getPropertyValue('font-family'); var fontSize = computedStyles.getPropertyValue('font-size'); var tempElement = document.createElement('span'); var defaultStyles = 'position:absolute;display:inline;border:0;margin:0;padding:0;line-height:normal;'; tempElement.setAttribute('style', "".concat(defaultStyles, "font-family:").concat(fontFamily, ";font-size:").concat(fontSize, ";")); tempElement.innerText = 'M'; parentNode.appendChild(tempElement); this._defaultLineHeight = parseInt(tempElement.clientHeight, 10) / parseInt(fontSize, 10); tempElement.parentNode.removeChild(tempElement); } return this._defaultLineHeight; }; } componentDidMount() { var { autoFocus, autoGrow, value } = this.props; autoFocus && this._onFocus(); if (autoGrow) { this._calculateComputedRows(); } /* * autoFocus doesn't automatically selects text like focus do. * Therefore we set the selection range, but in order to support prior implementation we set the start position as the end in order to place the cursor there. */ if (autoFocus && !!value) { this.textArea.setSelectionRange(value.length, value.length); } } componentDidUpdate(prevProps) { var { minRowsAutoGrow, value, defaultValue, autoGrow, hasCounter } = this.props; if (autoGrow && prevProps.minRowsAutoGrow !== minRowsAutoGrow) { this._calculateComputedRows(); } if (hasCounter && prevProps.value !== value) { this.setState({ counter: (value || defaultValue || '').length }); } } componentWillUnmount() { this._updateComputedStyle.cancel(); } render() { var { dataHook, className, autoFocus, defaultValue, disabled, forceFocus, forceHover, id, name, onKeyUp, placeholder, readOnly, tabIndex, rows, autoGrow, value, required, minHeight, maxHeight, maxLength, resizable, hasCounter, size, tooltipPlacement, status, statusMessage, children } = this.props; var inlineStyle = {}; var rowsAttr = rows ? rows : autoGrow ? this.state.computedRows : undefined; var onInput = !rows && autoGrow ? this._onInput : undefined; if (minHeight) { inlineStyle.minHeight = minHeight; } if (maxHeight) { inlineStyle.maxHeight = maxHeight; } var ariaAttribute = {}; Object.keys(this.props).filter(key => key.startsWith('aria')).map(key => ariaAttribute['aria-' + key.substr(4).toLowerCase()] = this.props[key]); return /*#__PURE__*/_react.default.createElement(_context.WixStyleReactContext.Consumer, { __self: this, __source: { fileName: _jsxFileName, lineNumber: 143, columnNumber: 7 } }, _ref2 => { var { newColorsBranding } = _ref2; return /*#__PURE__*/_react.default.createElement(_StatusContext.StatusContext.Consumer, { __self: this, __source: { fileName: _jsxFileName, lineNumber: 146, columnNumber: 13 } }, statusContext => { var finalStatus = (0, _StatusContext.getStatusFromContext)(statusContext, status); return /*#__PURE__*/_react.default.createElement("div", (0, _extends2.default)({ "data-hook": dataHook, className: (0, _InputAreaSt.st)(_InputAreaSt.classes.root, { disabled, size, status: finalStatus, hasFocus: forceFocus || this.state.focus, forceHover, resizable, readOnly, newColorsBranding }, className) }, this._getDataAttr({ statusContext }), { __self: this, __source: { fileName: _jsxFileName, lineNumber: 151, columnNumber: 19 } }), /*#__PURE__*/_react.default.createElement("div", { className: _InputAreaSt.classes.inputArea, __self: this, __source: { fileName: _jsxFileName, lineNumber: 170, columnNumber: 21 } }, typeof children === 'function' ? children({ rows: rowsAttr, ref: _ref3 => this.textArea = _ref3, onFocus: this._onFocus, onBlur: this._onBlur, onKeyDown: this._onKeyDown, onInput }) : /*#__PURE__*/_react.default.createElement("textarea", (0, _extends2.default)({ rows: rowsAttr, maxLength: maxLength, ref: _ref4 => this.textArea = _ref4, id: id, name: name, style: inlineStyle, defaultValue: defaultValue, disabled: disabled, value: value, required: required, onFocus: this._onFocus, onBlur: this._onBlur, onKeyDown: this._onKeyDown, onChange: this._onChange, onInput: onInput, placeholder: placeholder, tabIndex: tabIndex, autoFocus: autoFocus, onKeyUp: onKeyUp }, (0, _StatusContext.getAriaAttributesFromContext)(statusContext), ariaAttribute, { readOnly: readOnly, __self: this, __source: { fileName: _jsxFileName, lineNumber: 181, columnNumber: 25 } })), hasCounter && maxLength && /*#__PURE__*/_react.default.createElement("span", { className: _InputAreaSt.classes.counter, "data-hook": "counter", __self: this, __source: { fileName: _jsxFileName, lineNumber: 209, columnNumber: 25 } }, this.state.counter, "/", maxLength)), /*#__PURE__*/_react.default.createElement("div", { className: _InputAreaSt.classes.status, __self: this, __source: { fileName: _jsxFileName, lineNumber: 216, columnNumber: 21 } }, (!!status || finalStatus === _constants.STATUS.LOADING) && !disabled && /*#__PURE__*/_react.default.createElement(_StatusIndicator.default, { dataHook: _constants2.dataHooks.tooltip, status: finalStatus, message: statusMessage, tooltipPlacement: tooltipPlacement, __self: this, __source: { fileName: _jsxFileName, lineNumber: 219, columnNumber: 27 } }))); }); }); } } // For autoGrow prop min rows is 2 so the textarea does not look like an input InputArea.MIN_ROWS = 2; InputArea.displayName = 'InputArea'; InputArea.defaultProps = { minRowsAutoGrow: InputArea.MIN_ROWS, size: 'medium' }; InputArea.propTypes = { /** Applies a data-hook HTML attribute that can be used in the tests. */ dataHook: _propTypes.default.string, /** Specifies a CSS class name to be appended to the component’s root element. */ className: _propTypes.default.string, /** Specifies custom textarea render function */ children: _propTypes.default.func, /** Associate a control with the regions that it controls. */ ariaControls: _propTypes.default.string, /** Associate a region with its descriptions. Similar to aria-controls but instead associating descriptions to the region and description identifiers are separated with a space. */ ariaDescribedby: _propTypes.default.string, /** Define a string that labels the current element in case where a text label is not visible on the screen. */ ariaLabel: _propTypes.default.string, /** Focus the element on mount (standard React input autoFocus). */ autoFocus: _propTypes.default.bool, /** Controls the size of the input. */ size: _propTypes.default.oneOf(['small', 'medium']), /** Sets a default value for those who want to use this component un-controlled. */ defaultValue: _propTypes.default.string, /** Specifies whether input should be disabled. */ disabled: _propTypes.default.bool, /** Specifies the status of a field. */ status: _propTypes.default.oneOf(['error', 'warning', 'loading']), /** Defines the message to display on status icon hover. If not given or empty there will be no tooltip. */ statusMessage: _propTypes.default.node, /** USED FOR TESTING. Forces focus state on the input. */ forceFocus: _propTypes.default.bool, /** USED FOR TESTING. Forces hover state on the input. */ forceHover: _propTypes.default.bool, /** Specifies whether character count is enabled. */ hasCounter: _propTypes.default.bool, /** Assigns an unique identifier for the root element. */ id: _propTypes.default.string, /** Reference element data when a form is submitted. */ name: _propTypes.default.string, /** Sets the maximum height of an area in pixels. */ maxHeight: _propTypes.default.string, /** Defines the maximum text length in number of characters. */ maxLength: _propTypes.default.number, /** Sets the minimum height of an area in pixels. */ minHeight: _propTypes.default.string, /** Defines a standard input onBlur callback */ onBlur: _propTypes.default.func, /** Defines a standard input onChange callback. */ onChange: _propTypes.default.func, /** Defines a callback handler that is called when user presses enter. */ onEnterPressed: _propTypes.default.func, /** Defines a callback handler that is called when user presses escape. */ onEscapePressed: _propTypes.default.func, /** Defines a standard input onFocus callback. */ onFocus: _propTypes.default.func, /** Defines a standard input onKeyDown callback. */ onKeyDown: _propTypes.default.func, /** Defines a standard input onKeyUp callback. */ onKeyUp: _propTypes.default.func, /** Sets a placeholder message to display. */ placeholder: _propTypes.default.string, /** Specifies whether input is read only. */ readOnly: _propTypes.default.bool, /** Specifies whether area can be manually resized by the user. */ resizable: _propTypes.default.bool, /** Sets initial height of an area to fit a specified number of rows. */ rows: _propTypes.default.number, /** Specifies whether area should grow and shrink according to user input. */ autoGrow: _propTypes.default.bool, /** Sets the minimum amount of rows the component can have in `autoGrow` mode */ minRowsAutoGrow: _propTypes.default.number, /** Indicates that element can be focused and where it participates in sequential keyboard navigation. */ tabIndex: _propTypes.default.number, /** Controls placement of a status tooltip. */ tooltipPlacement: _propTypes.default.string, /** Defines input value. */ value: _propTypes.default.string, /** Specifies whether the input area is a mandatory field. */ required: _propTypes.default.bool }; var _default = exports.default = InputArea; //# sourceMappingURL=InputArea.js.map