@yandex/ui
Version:
Yandex UI components
62 lines (61 loc) • 3.78 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.withHasClear = void 0;
var tslib_1 = require("tslib");
var react_1 = tslib_1.__importStar(require("react"));
var core_1 = require("@bem-react/core");
var di_1 = require("@bem-react/di");
var mergeRefs_1 = require("../../lib/mergeRefs");
var Textinput_1 = require("../Textinput");
/**
* Модификатор, отвечающий за наличие крестика для очистки текстового поля.
* @param {ITextinputHasClearProps} props
*/
exports.withHasClear = core_1.withBemMod(Textinput_1.cnTextinput(), { hasClear: true }, function (Textinput) {
return /** @class */ (function (_super) {
tslib_1.__extends(WithHasClear, _super);
function WithHasClear() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.controlRef = react_1.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 = tslib_1.__rest(_a, ["addonBefore", "onClearClick", "hasClear", "controlRef"]);
return (react_1.default.createElement(di_1.ComponentRegistryConsumer, { id: Textinput_1.cnTextinput() }, function (_a) {
var Clear = _a.Clear;
return (react_1.default.createElement(Textinput, tslib_1.__assign({}, props, { controlRef: mergeRefs_1.mergeAllRefs(_this.controlRef, controlRef), addonBefore: react_1.default.createElement(react_1.default.Fragment, null,
react_1.default.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;
}(react_1.PureComponent));
});