UNPKG

@yandex/ui

Version:

Yandex UI components

59 lines (58 loc) 3.59 kB
import { __assign, __extends, __rest } from "tslib"; import React, { PureComponent, createRef } from 'react'; import { withBemMod } from '@bem-react/core'; import { ComponentRegistryConsumer } from '@bem-react/di'; import { mergeAllRefs } from '../../lib/mergeRefs'; import { cnTextinput } from '../Textinput'; /** * Модификатор, отвечающий за наличие крестика для очистки текстового поля. * @param {ITextinputHasClearProps} props */ export var withHasClear = withBemMod(cnTextinput(), { hasClear: true }, function (Textinput) { return /** @class */ (function (_super) { __extends(WithHasClear, _super); function WithHasClear() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.controlRef = createRef(); _this.onMouseDown = function (event) { // Предотвращаем потерю фокуса у элемента Control. event.preventDefault(); }; _this.onClick = function (event) { if (_this.controlRef.current !== null && !event.isDefaultPrevented()) { _this.controlRef.current.focus(); if (_this.props.onChange !== undefined) { var originalValue = _this.controlRef.current.value; // Создаем синтетическое событие для эмуляции очистки контрола. var syntheticEvent = Object.create(event); syntheticEvent.target = _this.controlRef.current; syntheticEvent.currentTarget = _this.controlRef.current; _this.controlRef.current.value = ''; _this.props.onChange(syntheticEvent); // Восстанавливаем предыдущее значение на тот случай, // если в обработчике onChange не было установлено пустое значение. _this.controlRef.current.value = originalValue; } } if (_this.props.onClearClick !== undefined) { _this.props.onClearClick(event); } }; return _this; } WithHasClear.prototype.render = function () { var _this = this; var _a = this.props, addonBefore = _a.addonBefore, // Извлекаем свойства, т.к. они не нужны на DOM узле // FIXME: https://github.com/bem/bem-react/issues/381 _onClearClick = _a.onClearClick, _hasClear = _a.hasClear, controlRef = _a.controlRef, props = __rest(_a, ["addonBefore", "onClearClick", "hasClear", "controlRef"]); return (React.createElement(ComponentRegistryConsumer, { id: cnTextinput() }, function (_a) { var Clear = _a.Clear; return (React.createElement(Textinput, __assign({}, props, { controlRef: mergeAllRefs(_this.controlRef, controlRef), addonBefore: React.createElement(React.Fragment, null, React.createElement(Clear, { onClick: _this.onClick, onMouseDown: _this.onMouseDown, size: _this.props.size, theme: _this.props.theme, view: _this.props.view, visible: Boolean(_this.props.value) }), addonBefore) }))); })); }; return WithHasClear; }(PureComponent)); });