You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

526 lines
17 KiB

"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _react = _interopRequireDefault(require("react"));
var _reactDom = _interopRequireDefault(require("react-dom"));
var _styledComponents = _interopRequireDefault(require("styled-components"));
var _isMobile = _interopRequireDefault(require("is-mobile"));
var _socket = require("./socket");
var _utils = require("./utils");
var _bubbleLocale = _interopRequireDefault(require("./bubble-locale"));
var _Bubble = _interopRequireDefault(require("./Bubble"));
var _Modal = _interopRequireDefault(require("./Modal"));
var _Loading = _interopRequireDefault(require("./Loading"));
var _Error = _interopRequireDefault(require("./Error"));
var _ErrorBoundary = _interopRequireDefault(require("./ErrorBoundary"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], 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); }
function _templateObject() {
var data = _taggedTemplateLiteral(["\n display: flex;\n justify-content: center;\n align-items: center;\n flex-direction: column;\n text-align: center;\n color: #fff;\n height: 100%;\n font-size: 14px;\n"]);
_templateObject = function _templateObject() {
return data;
};
return data;
}
function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }
var winPath = function winPath(input) {
if (!input) {
return '';
}
var isExtendedLengthPath = /^\\\\\?\\/.test(input);
if (isExtendedLengthPath) {
return input;
}
return input.replace(/\\/g, '/');
};
var LoadingWrapper = _styledComponents.default.div(_templateObject());
var App = /*#__PURE__*/function (_React$Component) {
_inherits(App, _React$Component);
var _super = _createSuper(App);
function App(props) {
var _this;
_classCallCheck(this, App);
_this = _super.call(this, props);
_this.handleLocale = function (locale) {
_this.setState({
locale: locale
});
};
_this.getMiniUrl = function () {
var currentProject = _this.state.currentProject;
return "".concat(_this.baseUrl, "/?mini&").concat(currentProject && currentProject.key ? "&key=".concat(currentProject.key) : '');
};
_this.addTemplate = function () {
var el = document.getElementById('umi-ui-bubble');
if (el && el.contentWindow) {
if (_this.messageMap.get('template')) {
el.contentWindow.postMessage(JSON.stringify({
action: 'umi.ui.block.addTemplate',
payload: _this.messageMap.get('template')
}), '*');
}
}
};
_this.handleMessage = function (event) {
try {
var _JSON$parse = JSON.parse(event.data),
action = _JSON$parse.action,
_JSON$parse$payload = _JSON$parse.payload,
payload = _JSON$parse$payload === void 0 ? {} : _JSON$parse$payload;
switch (action) {
// 编辑态改变文字
case 'umi.ui.changeEdit':
{
_this.setState({
edit: true,
editText: payload
});
break;
}
// 显示 mini
case 'umi.ui.showMini':
{
_this.toggleMiniOpen(true);
break;
}
// 隐藏 mini
case 'umi.ui.hideMini':
{
_this.toggleMiniOpen(false);
break;
}
// 切换loading
case 'umi.ui.toggleIconLoading':
{
_this.setState(function (_ref) {
var loading = _ref.loading;
return {
loading: !loading
};
});
break;
}
// 触发 notice
case 'umi.ui.showNotice':
{
_this.setState({
notice: true
});
break;
}
// 隐藏 notice
case 'umi.ui.hideNotice':
{
_this.setState({
notice: false
});
break;
}
// 打开对应模板
case 'umi.ui.block.addTemplate':
{
_this.toggleMiniOpen(true);
_this.messageMap.set('template', payload); // 第一次应该不执行
_this.addTemplate();
break;
}
case 'umi.ui.block.addTemplate.ready':
{
_this.addTemplate();
break;
}
default: // no thing
}
} catch (_) {// no thing
}
return false;
};
_this.initUIService = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
var _this$props, currentProject, path, res;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_this$props = _this.props, currentProject = _this$props.currentProject, path = _this$props.path; // console.log('currentProject', currentProject);
if (!_this.state.connected) {
_context.next = 7;
break;
}
if (currentProject.key) {
_context.next = 7;
break;
}
_context.next = 5;
return (0, _socket.callRemote)({
type: '@@project/getKeyOrAddWithPath',
payload: {
path: path
}
});
case 5:
res = _context.sent;
_this.setState({
currentProject: res
});
case 7:
case "end":
return _context.stop();
}
}
}, _callee);
}));
_this.closeModal = function (e) {
e.stopPropagation();
_this.setState({
open: false
});
};
_this.onIframeLoad = function () {
_this.setState({
uiLoaded: true
});
};
_this.toggleMiniOpen = /*#__PURE__*/function () {
var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(open) {
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (!(typeof _this.state.open === 'undefined')) {
_context2.next = 3;
break;
}
_context2.next = 3;
return _this.initUIService();
case 3:
if (open) {
_this.setState({
loading: false,
open: open
});
} else {
_this.setState(function (prevState) {
return {
open: !prevState.open,
loading: false
};
});
}
case 4:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return function (_x) {
return _ref3.apply(this, arguments);
};
}();
_this.resetEdit = function () {
_this.setState({
edit: false,
editText: {}
});
};
_this.getMessage = function () {
var locale = _this.state.locale;
return _bubbleLocale.default[locale] || _bubbleLocale.default['zh-CN'];
};
var _locale = (0, _utils.getLocale)();
_this.messageMap = new Map();
_this.state = {
open: undefined,
connected: false,
uiLoaded: false,
loading: false,
notice: false,
currentProject: props.currentProject,
locale: _locale,
edit: false,
editText: {},
tips: ''
};
window.addEventListener('message', _this.handleMessage, false);
var _window$location = window.location,
hostname = _window$location.hostname,
protocol = _window$location.protocol;
var port = _this.props.port;
_this.baseUrl = "".concat(protocol, "//").concat(hostname, ":").concat(port);
return _this;
}
_createClass(App, [{
key: "componentDidUpdate",
value: function componentDidUpdate() {
var nextLocale = (0, _utils.getLocale)();
if (this.state.locale !== nextLocale) {
this.handleLocale(nextLocale);
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.setState({
tips: ''
});
window.removeEventListener('message', this.handleMessage, false);
}
}, {
key: "componentDidMount",
value: function () {
var _componentDidMount = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
var _this2 = this;
var path, message;
return regeneratorRuntime.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
path = this.props.path;
message = this.getMessage();
_context3.prev = 2;
_context3.next = 5;
return (0, _socket.init)("".concat(this.baseUrl, "/umiui"), {
onError: function onError(e) {
// https://developer.mozilla.org/zh-CN/docs/Web/API/CloseEvent
// 非 localhost 访问
var code = e.code;
_this2.setState({
connected: false,
tips: message["code_".concat(code)] || ''
});
},
onMessage: function onMessage(_ref4) {
var type = _ref4.type,
payload = _ref4.payload;
// 区分不同项目
if (!payload || winPath(payload.projectPath) !== winPath(path)) return;
switch (type) {
case 'org.umi.ui.bubble.showLoading':
_this2.setState({
loading: true
});
break;
case 'org.umi.ui.bubble.hideLoading':
_this2.setState({
loading: false
});
break;
default:
break;
}
}
});
case 5:
this.setState({
connected: true
});
_context3.next = 12;
break;
case 8:
_context3.prev = 8;
_context3.t0 = _context3["catch"](2);
console.error('Init socket failed', _context3.t0);
this.setState({
connected: false
});
case 12:
case "end":
return _context3.stop();
}
}
}, _callee3, this, [[2, 8]]);
}));
function componentDidMount() {
return _componentDidMount.apply(this, arguments);
}
return componentDidMount;
}()
}, {
key: "render",
value: function render() {
var _this$state = this.state,
open = _this$state.open,
connected = _this$state.connected,
uiLoaded = _this$state.uiLoaded,
loading = _this$state.loading,
notice = _this$state.notice,
locale = _this$state.locale,
edit = _this$state.edit,
editText = _this$state.editText,
tips = _this$state.tips;
var _this$props$isBigfish = this.props.isBigfish,
isBigfish = _this$props$isBigfish === void 0 ? false : _this$props$isBigfish;
var miniUrl = this.getMiniUrl(); // get locale when first render
// switch in the project can't be listened, the lifecycle can't be trigger
// TODO: use Context but need to compatible with other React version
var message = this.getMessage();
return /*#__PURE__*/_react.default.createElement(_Bubble.default, {
isBigfish: isBigfish // TODO: loading when currentProject not loaded
,
toggleMiniOpen: this.toggleMiniOpen,
resetEdit: this.resetEdit,
open: open,
loading: loading,
notice: notice,
message: message,
edit: edit,
editText: editText,
locale: locale
}, open !== undefined && /*#__PURE__*/_react.default.createElement(_Modal.default, {
visible: open
}, !uiLoaded && !tips && /*#__PURE__*/_react.default.createElement(LoadingWrapper, null, /*#__PURE__*/_react.default.createElement(_Loading.default, null), /*#__PURE__*/_react.default.createElement("p", {
style: {
marginTop: 8
}
}, message.loading)), !connected ? /*#__PURE__*/_react.default.createElement(_Error.default, {
message: message,
tips: tips,
isBigfish: isBigfish
}) : /*#__PURE__*/_react.default.createElement("iframe", {
id: "umi-ui-bubble",
onLoad: this.onIframeLoad,
style: {
width: '100%',
height: '100%'
} // localhost maybe hard code
,
src: miniUrl,
frameBorder: "0",
scrolling: "no",
seamless: "seamless",
title: "iframe_umi_ui"
})));
}
}]);
return App;
}(_react.default.Component);
var doc = window.document;
var node = doc.createElement('div');
doc.body.appendChild(node);
var _default = function _default(props) {
if (!(0, _isMobile.default)(navigator.userAgent)) {
_reactDom.default.render( /*#__PURE__*/_react.default.createElement(_ErrorBoundary.default, null, /*#__PURE__*/_react.default.createElement(App, props)), node);
}
};
exports.default = _default;