frc-ui
Version:
React Web UI
605 lines (499 loc) • 21.6 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _react = _interopRequireDefault(require("react"));
var _classnames = _interopRequireDefault(require("classnames"));
var _uuid = require("uuid");
var _Hoc = require("../common/Hoc");
var _ChatInsetContent = _interopRequireDefault(require("../common/ChatInsetContent"));
var _interfaces = require("../interfaces");
var _Button = _interopRequireDefault(require("./Button"));
var _common = require("../common");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
var __decorate = void 0 && (void 0).__decorate || function (decorators, target, key, desc) {
var c = arguments.length,
r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
d;
if ((typeof Reflect === "undefined" ? "undefined" : _typeof(Reflect)) === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) {
if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
}
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var Send = /*#__PURE__*/function (_React$PureComponent) {
_inherits(Send, _React$PureComponent);
var _super = _createSuper(Send);
function Send(props) {
var _this;
_classCallCheck(this, Send);
_this = _super.call(this, props);
_this.urlReg = /^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+/;
_this.textMaxFreq = 10;
_this.textTimeWindow = 10;
_this.textSendRecord = [];
_this.saveRef = function (name) {
return function (ref) {
_this[name] = ref;
};
};
_this.getMessage = function () {
if (!_this.chatMessage) return [];
var childNodes = _this.chatMessage.childNodes;
var length = childNodes.length;
var message = [];
for (var i = 0; i < length; i++) {
var node = childNodes[i];
if (node.nodeName === '#text') {
message = _this.analysisText(node['textContent'], message);
} else {
message.push({
type: node['eleType'],
content: node['content']
});
}
}
_this.setState({
textLength: 0
});
return message;
};
_this.analysisText = function (text) {
var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
if (!text) return message;
var arr = (text || '').split(' ');
arr && arr.map(function (t) {
message.push({
type: _this.urlReg.test(t) ? _interfaces.MessageType.LINK : _interfaces.MessageType.TEXT,
content: t
});
message.push({
type: _interfaces.MessageType.TEXT,
content: ' '
});
});
return message;
};
_this.initColorIndex = function (permission) {
var localStorage = window.localStorage;
var danmakuColor = '#ffffff';
if (permission && localStorage) {
var colorValue = localStorage.getItem('danmakuColor');
if (!colorValue && colorValue !== '') {
return colorValue;
}
}
return danmakuColor;
};
_this.send = function () {
var message = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
if (!message || message.length === 0) return;
var _this$props = _this.props,
Socket = _this$props.Socket,
user = _this$props.user,
permission = _this$props.permission,
channel = _this$props.channel,
isAnonymous = _this$props.isAnonymous,
fontSize = _this$props.fontSize,
anonymousName = _this$props.anonymousName,
locale = _this$props.locale,
trendType = _this$props.trendType,
isGag = _this$props.isGag,
setName = _this$props.setName;
var often = _this.state.often;
var has = (permission || []).some(function (p) {
return p === _interfaces.PermissionEnum.CHAT_ROOM;
});
if (isGag || often || !has) {
return;
}
var per = permission || [];
var fontSizePermission = per.some(function (p) {
return p === _interfaces.PermissionEnum.DANMAKU_FONT;
});
var colorPermission = per.some(function (p) {
return p === _interfaces.PermissionEnum.DANMAKU_COLOR;
});
var chatMessage = {
id: (0, _uuid.v1)(),
username: user && user.username,
isAnonymous: isAnonymous,
channel: channel,
userId: user && user.userId,
loginName: user && user.username,
showName: user && user.companyName + '-' + user.name,
message: message,
style: {
color: _this.initColorIndex(colorPermission),
fontSize: (fontSizePermission ? fontSize : 20) + 'px'
}
};
if (anonymousName && isAnonymous) {
if (typeof setName === 'function') {
chatMessage.showName = setName(Object.assign(Object.assign({}, user), {
trendType: trendType,
isAnonymous: isAnonymous,
anonymousName: anonymousName
}));
} else {
chatMessage.showName = (locale && locale.trendType[trendType || _interfaces.TrendType.NONE] || '') + anonymousName;
}
}
if (Socket) Socket.send('chat', chatMessage);
};
_this.moveCursor = function () {
if (!_this.chatMessage) return;
_this.chatMessage.focus();
if (window.getSelection && _this.chatMessage.lastChild) {
var sel = window.getSelection();
var tempRange = document.createRange();
var n = _this.chatMessage.lastChild || 0;
tempRange.setStart(n, 0);
if (sel) {
sel.removeAllRanges();
sel.addRange(tempRange);
}
}
};
_this.insetContent = function (type, content) {
var _this$props2 = _this.props,
isGag = _this$props2.isGag,
permission = _this$props2.permission;
var often = _this.state.often;
var has = (permission || []).some(function (p) {
return p === _interfaces.PermissionEnum.CHAT_ROOM;
});
if (isGag || often || !has) {
return;
}
if (!_this.chatMessage) return;
_this.currentType = type;
(0, _ChatInsetContent["default"])({
type: type,
content: content
}, _this.chatMessage);
_this.moveCursor();
};
_this.handlePaste = function (event) {
event.preventDefault();
var emit = _this.props.emit;
var textMaxLength = _this.props.textMaxLength || 0;
var textLength = _this.state.textLength;
var cbd = event.clipboardData;
for (var i = 0; i < cbd.items.length; i++) {
var item = cbd.items[i];
if (item.kind === 'file' || item.type.indexOf('image') > -1) {
var blob = item.getAsFile();
if (!blob || blob.size === 0) {
return;
}
var formData = new FormData();
formData.append('file', blob, '');
formData.append('ttl', '1d');
emit && emit('chatFile', {
type: _interfaces.FsType.PASTE_IMAGE,
file: formData
}); // blobToDataURL(blob, (url) => this.insetContent(Type.IMAGE, url));
} else if (item.kind === 'string' && item.type === 'text/plain') {
item.getAsString(function (str) {
var regStr = str;
regStr = regStr.replace(/\s+/g, '');
regStr = regStr.replace(/<\/?.+?>/g, '');
regStr = regStr.replace(/[\r\n]/g, '');
if (textLength < textMaxLength) {
var length = regStr.length;
if (textLength + length > textMaxLength) {
var remindLength = textMaxLength - textLength;
var count = 0;
for (var ti = 0; ti < str.length; ti++) {
if (!/\s+/g.test(str[ti]) && !/<\/?.+?>/g.test(str[ti]) && !/[\r\n]/g.test(str[ti])) {
count += 1;
}
if (remindLength <= count) {
str = str.substring(0, ti);
break;
}
}
length = count;
}
_this.setState({
textLength: _this.state.textLength + length
});
str = str.replace(/[\n]/g, ' <br/> ');
var arr = (str || '').split(' ');
(arr || []).map(function (t) {
if (t === '<br/>') {
_this.insetContent(_interfaces.MessageType.ELEMENT, 'br');
} else {
_this.insetContent(_this.urlReg.test(str) ? _interfaces.MessageType.LINK : _interfaces.MessageType.TEXT, t);
}
});
}
});
} else if (item.kind === 'string' && item.type === 'text/html') {
item.getAsString(function (str) {
console.log(str);
});
}
}
};
_this.handleKeyDown = function (event) {
var shortcutKey = (0, _common.getLocalStorageItem)(_interfaces.LocalStorageKey.shortcutKey, 'EnterSend');
if ((event.ctrlKey || event.metaKey) && event.keyCode === 13) {
if (shortcutKey === 'EnterSend') {
_this.handleAddBlank(event);
} else if (shortcutKey === 'CtrlEnterSend') {
_this.handleSend();
}
} else if (event.keyCode === 13) {
if (shortcutKey === 'EnterSend') {
_this.handleSend();
} else if (shortcutKey === 'CtrlEnterSend') {
_this.handleAddBlank(event);
}
} else {
_this.currentType = _interfaces.MessageType.TEXT;
if (_this.state.textLength >= (_this.props.textMaxLength || 0) && event.keyCode !== 8 && event.keyCode !== 37 && event.keyCode !== 38 && event.keyCode !== 39 && event.keyCode !== 40) {
event.preventDefault();
}
}
};
_this.handleKeyUp = function (event) {
if (!_this.chatMessage) return;
var textMaxLength = _this.props.textMaxLength;
var childNodes = _this.chatMessage.childNodes;
var length = 0;
if (!childNodes) return;
for (var i = 0; i < childNodes.length; i++) {
var node = childNodes[i];
if (!node) continue;
if (node.nodeName === '#text') {
var tempLength = length + (node.textContent ? node.textContent.length : 0);
if (textMaxLength && tempLength > textMaxLength) {
node.textContent = node.textContent ? node.textContent.substring(0, textMaxLength - length) : node.textContent;
length = textMaxLength;
} else {
length = tempLength;
}
} else if (node['eleType'] === _interfaces.MessageType.TEXT) {
var _tempLength = length + (node.textContent ? node.textContent.length : 0);
if (textMaxLength && _tempLength > textMaxLength) {
node.textContent = node.textContent ? node.textContent.substring(0, textMaxLength - length) : node.textContent;
node['content'] = node.textContent;
length = textMaxLength;
} else {
length = _tempLength;
}
}
}
if (textMaxLength && length > textMaxLength) {
event.preventDefault();
}
_this.setState({
textLength: length
});
};
_this.handleAddBlank = function (event) {
event && event.preventDefault();
if (_this.currentType === _interfaces.MessageType.TEXT || !_this.currentType) {
_this.insetContent(_interfaces.MessageType.ELEMENT, 'br');
}
_this.insetContent(_interfaces.MessageType.ELEMENT, 'br');
};
_this.handleSend = function (event) {
if (event) event.preventDefault();
var message = _this.getMessage();
if (_this.checkOften()) {
_this.chatMessage && (_this.chatMessage.innerHTML = '');
return;
}
setTimeout(function () {
_this.chatMessage && (_this.chatMessage.innerHTML = '');
}, 16);
_this.send(message);
};
_this.handleOnClick = function () {
_this.closeHistory();
if (_this.state.often) {
_this.setState({
often: false,
textLength: 0
});
}
};
_this.handleInput = function (event) {
_this.handleKeyUp(event);
};
_this.handleFocus = function () {
_this.closeHistory();
};
_this.closeHistory = function () {
var _this$props3 = _this.props,
emit = _this$props3.emit,
success = _this$props3.success,
history = _this$props3.history;
if (emit && history) {
emit('chat', {
history: false
});
success && success('chatMessage.histories', {
payload: 'clear'
});
}
};
_this.renderCover = function (has) {
var _this$props4 = _this.props,
locale = _this$props4.locale,
isGag = _this$props4.isGag,
prefix = _this$props4.prefix;
var often = _this.state.often;
var cls = "".concat(prefix, "-send-cover");
if (!has) return /*#__PURE__*/_react["default"].createElement("div", {
className: cls
}, locale && locale.noChatPermissionText);
if (isGag) return /*#__PURE__*/_react["default"].createElement("div", {
className: cls
}, locale && locale.gagText);
if (often) return /*#__PURE__*/_react["default"].createElement("div", {
className: cls
}, locale && locale.oftenText);
return null;
};
_this.checkOften = function () {
var timestamp = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Date().getTime();
var often = _this.state.often;
if (_this.textSendRecord.length < _this.textMaxFreq) {
_this.textSendRecord.push(timestamp);
often && _this.setState({
often: false
});
return false;
}
if (_this.textSendRecord.length > 0) {
var first = _this.textSendRecord[0];
if ((timestamp - first) / 1000 > _this.textTimeWindow) {
_this.textSendRecord.push(timestamp);
_this.textSendRecord.shift();
often && _this.setState({
often: false
});
return false;
}
}
!often && _this.setState({
often: true
});
return true;
};
_this.renderInput = function (has) {
var prefix = _this.props.prefix;
var props = {
ref: _this.saveRef('chatMessage'),
className: "".concat(prefix, "-send-input"),
// contentEditable: has && !isGag && !often,
contentEditable: false,
onKeyDown: _this.handleKeyDown,
onKeyUp: _this.handleKeyUp,
onPaste: _this.handlePaste,
onClick: _this.handleOnClick,
onInput: _this.handleInput,
onFocus: _this.handleFocus
};
return /*#__PURE__*/_react["default"].createElement("div", Object.assign({}, props, {
style: {
cursor: 'not-allowed'
}
}), _this.renderCover(has));
};
_this.renderTip = function (has) {
var textMaxLength = _this.props.textMaxLength;
var _this$state = _this.state,
textLength = _this$state.textLength,
often = _this$state.often;
var _this$props5 = _this.props,
isGag = _this$props5.isGag,
prefix = _this$props5.prefix,
locale = _this$props5.locale;
if (has && !isGag && !often) {
return /*#__PURE__*/_react["default"].createElement("div", {
className: "".concat(prefix, "-send-text-length")
}, locale && locale.inputTip(Math.max((textMaxLength || 0) - textLength, 0)));
}
return null;
};
_this.state = {
textLength: 0,
often: false,
textSendRecord: []
};
return _this;
}
_createClass(Send, [{
key: "componentWillReceiveProps",
value: function componentWillReceiveProps(nextProps) {
var emo = nextProps.emo,
textMaxLength = nextProps.textMaxLength,
uploadImage = nextProps.uploadImage;
if (emo && emo !== this.props.emo) {
if (emo.type === 'emo') {
if (textMaxLength && textMaxLength > this.state.textLength) {
this.insetContent(_interfaces.MessageType.EMO, emo.emo);
this.setState({
textLength: this.state.textLength + 1
});
}
} else if (emo.type === 'collectEmo') {
var message = [{
type: _interfaces.MessageType.GIF,
content: emo.emo
}];
this.send(message);
}
}
if (uploadImage && uploadImage !== this.props.uploadImage && uploadImage.url) {
this.insetContent(_interfaces.MessageType.IMAGE, uploadImage.url);
}
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(preProps, preState) {
if (preState.often !== this.state.often) this.moveCursor();
}
}, {
key: "render",
value: function render() {
var _this$props6 = this.props,
prefix = _this$props6.prefix,
className = _this$props6.className,
permission = _this$props6.permission,
isGag = _this$props6.isGag;
var often = this.state.often;
var has = (permission || []).some(function (p) {
return p === _interfaces.PermissionEnum.CHAT_ROOM;
});
var cls = (0, _classnames["default"])("".concat(prefix, "-send"), className);
return /*#__PURE__*/_react["default"].createElement("div", {
className: cls
}, this.renderInput(has), /*#__PURE__*/_react["default"].createElement("div", {
className: "".concat(prefix, "-send-bottom")
}, this.renderTip(has), " ", has && !isGag && !often && /*#__PURE__*/_react["default"].createElement(_Button["default"], {
onClick: this.handleSend
})));
}
}]);
return Send;
}(_react["default"].PureComponent);
Send = __decorate([(0, _Hoc.Consumer)(['textMaxLength', 'isGag', 'isAnonymous', 'permission', 'fontSize', 'trendType', 'emo', 'uploadImage', 'history', 'anonymousName'])], Send);
var _default = Send;
exports["default"] = _default;