UNPKG

@fishx/module-renderer

Version:

Support render Fish, Fishx module

264 lines (256 loc) 13.1 kB
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure 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 _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 _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } /** * ChildModuleRenderer - Child Module 渲染器 * @description 渲染 FishX Child Module 应用 * * @param {string} id - 菜单名称(Priv Code) * @param {string} moduleName - Child Module Url (FishX child module id) * @param {string} path - Child Module default path * @param {string} urlBasename - asset url basename, @demo urlBasename = '/portal' * @param {Object} moduleProps - module props * @param {React.ReactNode | string} fallback - Child Module Fallback * @param {boolean} showLoading - Child Module Loading Flag * @param {React.ReactNode | string} loadingContent - Child Module Loading Content * @param {() => void} onLoaded - Child Module Loaded Callback * @param {(error: any) => void} onError - Child Module Error Callback * @returns {React.ReactElement} */ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { debounce } from 'lodash-es'; import { load } from "./utils"; // Filter attributes mutations var OBSERVE_CONFIG = { attributes: false, childList: true, subtree: true }; function ChildModuleRenderer(props) { var _props$id = props.id, id = _props$id === void 0 ? '' : _props$id, moduleName = props.moduleName, _props$path = props.path, path = _props$path === void 0 ? '/' : _props$path, _props$urlBasename = props.urlBasename, urlBasename = _props$urlBasename === void 0 ? '' : _props$urlBasename, _props$moduleProps = props.moduleProps, moduleProps = _props$moduleProps === void 0 ? {} : _props$moduleProps, _props$fallback = props.fallback, fallback = _props$fallback === void 0 ? '404' : _props$fallback, _props$showLoading = props.showLoading, showLoading = _props$showLoading === void 0 ? true : _props$showLoading, _props$loadingContent = props.loadingContent, loadingContent = _props$loadingContent === void 0 ? 'Loading...' : _props$loadingContent, _props$debug = props.debug, debug = _props$debug === void 0 ? false : _props$debug, onLoaded = props.onLoaded, onError = props.onError; var menuComponentPrivs = moduleProps.menuComponentPrivs; var containerId = useMemo(function () { return "child-module-".concat(id.replace(' ', '')); }, [id]); var _useState = useState(false), _useState2 = _slicedToArray(_useState, 2), errorFlag = _useState2[0], setErrorFlag = _useState2[1]; var _useState3 = useState(false), _useState4 = _slicedToArray(_useState3, 2), isLoading = _useState4[0], setIsLoading = _useState4[1]; var containerRef = useRef(null); var fishxRef = useRef({ id: id, isLoaded: false, history: null, containerId: containerId }); var fetchRef = useRef({ isFetching: false, fetched: false }); // 查询远程资源状态 var handleError = useCallback(debounce(function (error) { setIsLoading(false); setErrorFlag(true); // eslint-disable-next-line no-console console.error(error); if (typeof onError === 'function') onError(error); }, 300), []); var renderRemoteMenu = useCallback(debounce(function () { try { setErrorFlag(false); setIsLoading(false); var dom = document.getElementById(containerId); if (dom) { var instance = fishxRef.current; if (debug) console.log('[FishXModule] info:', { moduleName: moduleName, containerId: containerId, path: path, moduleProps: moduleProps, onLoaded: onLoaded, onError: onError }); // 应对不同模块共用同一个渲染组件 var history = id === instance.id ? instance.history : null; var res; var i = 0; if (window[moduleName]) { res = window[moduleName].render("#".concat(containerId), _objectSpread(_objectSpread({}, moduleProps), {}, { history: history }), path); } else { // FIXME: 加载js资源之后,有可能模块还未完成初始化,即window[module]为undefined,因此再尝试多次渲染,超过5次认为失败 var itvlId = setInterval(function () { try { if (i < 5 && !res) { res = window[moduleName] && window[moduleName].render("#".concat(containerId), _objectSpread(_objectSpread({}, moduleProps), {}, { history: history }), path); if (res) { clearInterval(itvlId); } else { i += 1; } } else { clearInterval(itvlId); } } catch (error) { clearInterval(itvlId); i = 5; } }, 200); } if (i >= 5) { throw new Error("".concat(moduleName, " Module Load Failed!")); } if (!instance.isLoaded) { instance.isLoaded = true; } // 更新 instance 数据 instance.id = id; instance.containerId = containerId; instance.history = res && res.history; } if (typeof onLoaded === 'function') onLoaded(); } catch (error) { handleError(error); } }, 500), [moduleName, containerId, path, moduleProps, onLoaded, handleError, id, debug, fishxRef.current]); var loadMoudle = useCallback(function () { if (!fetchRef.current.isFetching) { fetchRef.current.isFetching = true; load(moduleName, urlBasename).then(function () { fetchRef.current.isFetching = false; fetchRef.current.fetched = true; renderRemoteMenu(); }).then(function () { if (typeof onLoaded === 'function') onLoaded(); }).catch(function (error) { handleError(error); fetchRef.current.isFetching = false; fetchRef.current.fetched = false; }); } }, [moduleName, urlBasename, moduleProps]); // 加载并渲染子应用 useEffect(function () { setErrorFlag(false); if (window[moduleName]) { renderRemoteMenu(); } else { setIsLoading(true); loadMoudle(); } }, [moduleName, id, urlBasename, moduleProps]); // cleanup when unmount useEffect(function () { return function () { try { var instance = fishxRef.current; if (window[moduleName] && renderRemoteMenu) { renderRemoteMenu.cancel(); } if (window[moduleName] && typeof window[moduleName].unmount === 'function' && instance.containerId) { window[moduleName].unmount("#".concat(instance.containerId)); instance.isLoaded = false; } } catch (error) { handleError(error); } }; }, []); var hideElement = useCallback(debounce(function () { Array.isArray(menuComponentPrivs) && menuComponentPrivs.forEach(function (id) { var elements = document.querySelectorAll("[data-comp-code='".concat(id, "']")); if (elements.length > 0) { elements.forEach(function (ele) { ele.style.display = 'none'; }); } }); }, 300), [menuComponentPrivs]); // 监听子应用的 dom 变化,隐藏不需要的 dom // TODO: 支持子应用关闭observer useEffect(function () { // Callback function to execute when mutations are observed var mutationHandler = function mutationHandler(mutationList) { var _iterator = _createForOfIteratorHelper(mutationList), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var mutation = _step.value; if (mutation.type === 'childList') { hideElement(); } else if (mutation.type === 'attributes') { console.log("The ".concat(mutation.attributeName, " attribute was modified.")); } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } }; var observer = new MutationObserver(mutationHandler); if (containerRef.current) observer.observe(containerRef.current, OBSERVE_CONFIG); return function () { observer.disconnect(); }; }, [containerRef.current, hideElement]); return /*#__PURE__*/React.createElement("div", { style: { width: '100%', height: '100%', overflow: 'auto' }, ref: containerRef, className: "module-container" }, showLoading && isLoading && /*#__PURE__*/React.createElement("div", { style: { width: '100%', height: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center' } }, loadingContent), !isLoading && errorFlag ? fallback : /*#__PURE__*/React.createElement("div", { id: containerId, style: { width: '100%', height: '100%' }, key: containerId })); } export default ChildModuleRenderer;