@cc98/react-ubb-editor
Version:
A ubb editor component based on react
66 lines (65 loc) • 2.75 kB
JavaScript
import { __assign, __extends } from "tslib";
import React from 'react';
import Text from './styles/Textarea';
var Textarea = /** @class */ (function (_super) {
__extends(Textarea, _super);
function Textarea(props) {
var _this = _super.call(this, props) || this;
_this.scrollTop = 0;
_this.undo = function () {
if (_this.state.valueStack.length === 1) {
return;
}
var prevValue = _this.state.valueStack.pop();
_this.state.redoStack.push(prevValue);
prevValue = _this.state.valueStack[_this.state.valueStack.length - 1];
_this.props.onChange(prevValue);
};
_this.redo = function () {
var prevValue = _this.state.redoStack.pop();
if (prevValue) {
_this.state.valueStack.push(prevValue);
_this.props.onChange(prevValue);
}
};
_this.blur = function () {
_this.textarea.blur();
};
_this.changeValue = function (value) {
_this.props.onChange(value);
_this.state.valueStack.push(value);
_this.textarea.scrollTop = _this.scrollTop;
};
_this.handleFocus = function (e) {
_this.textarea.scrollTop = _this.scrollTop;
if (_this.props.onFocus)
_this.props.onFocus(e);
};
_this.state = {
valueStack: props.value === '' ? [''] : ['', props.value],
redoStack: [],
};
return _this;
}
Textarea.getDerivedStateFromProps = function (nextProps, prevState) {
if (nextProps.value !== prevState.valueStack[prevState.valueStack.length - 1]) {
prevState.valueStack.push(nextProps.value);
prevState.redoStack = [];
return __assign({}, prevState);
}
return null;
};
Textarea.prototype.render = function () {
var _this = this;
return (React.createElement(Text, __assign({ ref: function (it) { return (_this.textarea = it); } }, this.props, { defaultValue: undefined, onChange: function (e) { return _this.changeValue(e.target.value); }, onScroll: function () { return (_this.scrollTop = _this.textarea.scrollTop); }, onFocus: this.handleFocus, onInput: function () { return _this.setState({ redoStack: [] }); }, onKeyDown: function (e) {
if (_this.props.onKeyDown)
_this.props.onKeyDown(e);
if (e.key === 'z' && e.ctrlKey)
_this.undo();
if (e.key === 'y' && e.ctrlKey)
_this.redo();
} })));
};
return Textarea;
}(React.PureComponent));
export default Textarea;