UNPKG

qt-public-ui

Version:

新设计规范下业务组件库

86 lines 2.82 kB
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; var _excluded = ["children"]; /* eslint-disable no-param-reassign */ import { useRef } from 'react'; import { isMenuTitle } from './utils'; import cloneDeep from 'clone-deep'; import { matchPath, useLocation, useParams } from 'react-router-dom'; export var resolvePath = function resolvePath(path) { var _path = ''; if (path) { _path = path.replace(/\/$/, ''); _path = /^\//.test(_path) ? _path : "/" + _path; } for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return args.length >= 1 ? "" + _path + resolvePath.apply(void 0, args) : _path; }; var joinConfigPath = function joinConfigPath(config, parent) { var _ref = config, children = _ref.children, cfg = _objectWithoutPropertiesLoose(_ref, _excluded); var _link = resolvePath(parent, config.link); var _config = _extends({}, cfg, { link: _link }); if (Array.isArray(config.children)) { _config.children = config.children.map(function (child) { return joinConfigPath(child, _link); }); } return _config; }; var replaceParams = function replaceParams(item, params, defaultParams) { if (isMenuTitle(item)) { item.children.forEach(function (it) { replaceParams(it, params, defaultParams); }); } else { var _item$link; var matched = ((_item$link = item.link) === null || _item$link === void 0 ? void 0 : _item$link.match(/:([^/]+)/g)) || []; matched.forEach(function (m) { var key = m.slice(1); item.link = item.link.replace(m, params[key] || defaultParams[key]); }); } return item; }; export default (function (config, options, deepclone) { if (options === void 0) { options = {}; } if (deepclone === void 0) { deepclone = true; } var _config = deepclone ? cloneDeep(config) : config; var _useLocation = useLocation(), path = _useLocation.pathname; var _options = options, _options$defaultParam = _options.defaultParams, defaultParams = _options$defaultParam === void 0 ? {} : _options$defaultParam; var params = useParams(); var menu = useRef([]); if (Array.isArray(_config)) { menu.current = _config.map(function (m) { return joinConfigPath(m); }); } else { Object.entries(_config).some(function (_ref2) { var key = _ref2[0], value = _ref2[1]; var match = matchPath(path, { path: key }); if (match) { menu.current = value; return true; } return false; }); } return menu.current.map(function (m) { return replaceParams(m, params, defaultParams); }); });