@choerodon/master
Version:
A package of Master for Choerodon platform.
357 lines (285 loc) • 13.3 kB
JavaScript
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
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); 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 } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || 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 : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
import { Component } from 'react';
import PropTypes from 'prop-types';
import { warning } from "../../utils";
import addEventListener from "./addEventListener";
var TIMEOUT_TIME = 50000;
var WSProvider = /*#__PURE__*/function (_Component) {
_inherits(WSProvider, _Component);
var _super = _createSuper(WSProvider);
function WSProvider() {
var _this;
_classCallCheck(this, WSProvider);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_this.ws = new Map();
_this.windowBeforeUnloadListener = null;
_this.map = new Map();
_this.retry = false;
_this.pending = [];
_this.needReRegister = false;
_this.handleWindowBeforeUnload = function () {
_this.destroyAllSocket();
};
_this.handleOpen = function (evt, path) {
var onOpen = _this.props.onOpen;
if (typeof onOpen === 'function') {
onOpen();
}
if (_this.needReRegister) {
_this.reRegister();
_this.retry = false;
}
_this.pending.forEach(function (data) {
_this.send(data, path);
});
};
_this.handleMessage = function (_ref, path) {
var data = _ref.data;
var _JSON$parse = JSON.parse(data),
key = _JSON$parse.key,
message = _JSON$parse.message;
var onMessage = _this.props.onMessage;
var handlers = _this.map.get("".concat(path, "-").concat(key));
if (typeof onMessage === 'function') {
onMessage(message, key);
}
if (handlers) {
handlers.forEach(function (handler) {
return handler(data);
});
}
};
_this.handleError = function (e, path) {
var onError = _this.props.onError;
if (typeof onError === 'function') {
onError(e);
}
if (!_this.retry) {
_this.retry = true;
setTimeout(function () {
_this.retry = false;
_this.needReRegister = true;
_this.destroySocketByPath(path);
_this.initSocket(_this.props, path);
}, TIMEOUT_TIME);
}
};
_this.handleClose = function (e, path) {
var onClose = _this.props.onClose;
if (typeof onClose === 'function') {
onClose();
}
if (!_this.retry) {
_this.retry = true;
setTimeout(function () {
_this.retry = false;
_this.needReRegister = true;
_this.destroySocketByPath(path);
_this.initSocket(_this.props, path);
}, TIMEOUT_TIME);
}
};
_this.initSocket = function (_ref2, path) {
var server = _ref2.server;
if (server && path) {
try {
var ws = new WebSocket("".concat(server, "/").concat(path));
ws.addEventListener('open', function (evt) {
return _this.handleOpen(evt, path);
});
ws.addEventListener('message', function (evt) {
return _this.handleMessage(evt, path);
});
ws.addEventListener('error', function (evt) {
return _this.handleError(evt, path);
});
ws.addEventListener('close', function (evt) {
return _this.handleClose(evt, path);
});
ws.hb = setInterval(function () {
return _this.heartBeat(path);
}, TIMEOUT_TIME);
_this.ws.set(path, ws);
} catch (e) {
warning(false, "WSProvider is stopped. Caused by <".concat(e.message, ">"));
_this.ws.set(path, null);
}
}
};
_this.heartBeat = function (path) {
_this.send(JSON.stringify({
type: 'heartBeat'
}), path);
};
_this.send = function (message, path) {
var _assertThisInitialize = _assertThisInitialized(_this),
ws = _assertThisInitialize.ws,
pending = _assertThisInitialize.pending;
if (ws.get(path) && ws.get(path).readyState === 1) {
ws.get(path).send(message);
} else if (pending.indexOf(message) === -1) {
pending.push(message);
}
};
_this.reRegister = function () {
_this.needReRegister = false;
_toConsumableArray(_this.map.keys()).forEach(function (key) {
_this.pending.push(JSON.stringify({
type: 'sub',
data: key.slice(key.split('-')[0].length + 1)
}));
});
};
return _this;
}
_createClass(WSProvider, [{
key: "getChildContext",
value: function getChildContext() {
return {
ws: this
};
}
}, {
key: "componentWillMount",
value: function componentWillMount() {
if (typeof window !== 'undefined') {
this.windowBeforeUnloadListener = addEventListener(window, 'beforeunload', this.handleWindowBeforeUnload);
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.destroyAllSocket();
if (this.windowBeforeUnloadListener) {
this.windowBeforeUnloadListener.remove();
this.windowBeforeUnloadListener = null;
}
}
}, {
key: "destroySocketByPath",
value: function destroySocketByPath(path) {
var _this2 = this;
var ws = this.ws;
var w = ws.get(path);
if (w) {
clearInterval(w.hb);
w.removeEventListener('open', function (evt) {
return _this2.handleOpen(evt, path);
});
w.removeEventListener('message', function (evt) {
return _this2.handleMessage(evt, path);
});
w.removeEventListener('error', function (evt) {
return _this2.handleError(evt, path);
});
w.removeEventListener('close', function (evt) {
return _this2.handleClose(evt, path);
});
w.close();
ws.set(path, null);
}
}
}, {
key: "destroyAllSocket",
value: function destroyAllSocket() {
var _this3 = this;
var ws = this.ws;
if (ws.size > 0) {
ws.forEach(function (value) {
if (value) {
value.removeEventListener('open', _this3.handleOpen);
value.removeEventListener('message', _this3.handleMessage);
value.removeEventListener('error', _this3.handleError);
value.removeEventListener('close', _this3.handleClose);
clearInterval(value.hb);
value.close();
}
});
this.ws.clear();
}
}
/**
* 获得指定的连接
* @param server
* @param path
*/
}, {
key: "register",
value:
/**
* 将handler注册到对应path的webSocket的handleMessage事件上,如果这个path没有建立连接,则建立连接,并发送订阅消息的请求。
* @param key 要注册的key
* @param message 订阅消息
* @param handler
* @param path
*/
function register(key, message, handler, path) {
var server = this.props.server;
if (this.ws.get(path)) {
var handlers = this.map.get("".concat(path, "-").concat(key));
if (handlers) {
if (handlers.indexOf(handler) === -1) {
handlers.push(handler);
}
} else {
this.map.set("".concat(path, "-").concat(key), [handler]);
}
this.send(JSON.stringify(_objectSpread({}, message)), path);
} else {
this.initSocket({
server: server
}, path);
this.map.set("".concat(path, "-").concat(key), [handler]);
this.send(JSON.stringify(_objectSpread({}, message)), path);
}
}
}, {
key: "unregister",
value: function unregister(key, handler, path) {
if (this.ws) {
var handlers = this.map.get("".concat(path, "-").concat(key)); // 给后端发送取消订阅的消息
this.send(JSON.stringify({
type: 'unsub',
data: key
}), path);
if (handlers) {
var index = handlers.indexOf(handler);
if (index !== -1) {
handlers.splice(index, 1);
}
}
}
}
}, {
key: "render",
value: function render() {
return this.props.children;
}
}]);
return WSProvider;
}(Component);
WSProvider.childContextTypes = {
ws: PropTypes.object
};
export { WSProvider as default };