Commit c8d7d320 authored by 邓晓峰's avatar 邓晓峰

fix: 修复topbar样式

parent ca994e24
Pipeline #47278 skipped with stages
{
"printWidth": 80,
"printWidth": 120,
"tabWidth": 2,
"useTabs": false,
"semi": true,
......
......@@ -65,7 +65,7 @@ module.exports = {
return localName;
}
const match = context.resourcePath.match(/src(.*)/);
const match = context.resourcePath.match(/(src(.*))/);
if (match && match[1]) {
const antdProPath = match[1].replace('.less', '');
......@@ -73,10 +73,7 @@ module.exports = {
.split('/')
.map(a => a.replace(/([A-Z])/g, '-$1'))
.map(a => a.toLowerCase());
return `panda-console-base${arr.join('-')}-${localName}`.replace(
/--/g,
'-',
);
return `panda-console-base${arr.join('-')}-${localName}`.replace(/--/g, '-');
}
return localName;
},
......
......@@ -12,7 +12,6 @@ module.exports = {
title: '熊猫智慧城市监控管理解决方案',
iconfontUrl: '',
primaryColor: '#1890ff',
logo:
'https://panda-water.cn/web4/assets/images/logo/%E5%8D%95%E7%8B%AC%E5%9B%BE%E6%A1%88-%E7%99%BD%E8%89%B2.svg',
logo: 'https://panda-water.cn/web4/assets/images/logo/%E5%8D%95%E7%8B%AC%E5%9B%BE%E6%A1%88-%E7%99%BD%E8%89%B2.svg',
name: '熊猫智慧城市监控管理解决方案',
};
......@@ -5,29 +5,17 @@ const path = require('path');
const webpack = require('webpack');
const Config = require('webpack-chain');
const lodash = require('lodash');
const {
getTargetsAndBrowsersList,
getBabelPresetOpts,
getBabelOpts,
} = require('@umijs/bundler-utils');
const { getTargetsAndBrowsersList, getBabelPresetOpts, getBabelOpts } = require('@umijs/bundler-utils');
const { join } = require('lodash');
const terserOptions = require('./terserOptions');
const { css, createCSSRule } = require('./css');
const pkg = require('../../package.json');
const ASSET_PATH = process.env.ASSET_PATH || '/';
const {
ThemeColorReplacer,
themePluginOption,
} = require('../../config/plugin.config');
const { ThemeColorReplacer, themePluginOption } = require('../../config/plugin.config');
let defineConfig = require('../../config/config');
const resolveDefine = require('./resolveDefine');
const { getPkgPath, shouldTransform } = require('./pkgMatch');
const {
TYPE_ALL_EXCLUDE,
isMatch,
excludeToPkgs,
es5ImcompatibleVersionsToPkg,
} = require('./nodeModulesTransform');
const { TYPE_ALL_EXCLUDE, isMatch, excludeToPkgs, es5ImcompatibleVersionsToPkg } = require('./nodeModulesTransform');
function getUserLibDir({ library }) {
if (
......@@ -80,21 +68,12 @@ module.exports = options => {
const cwd = process.cwd();
const devtool = options.devtool || false;
chainConfig.devtool(
isDev
? devtool === false
? false
: devtool || 'cheap-module-source-map'
: devtool,
);
chainConfig.devtool(isDev ? (devtool === false ? false : devtool || 'cheap-module-source-map') : devtool);
const { mfsu } = defineConfig;
const useHash = defineConfig.hash && isProd;
const absOutputPath = process.env.npm_config_releasepath
? path.resolve(
process.env.npm_config_releasepath,
pkg.name.toLocaleLowerCase(),
)
? path.resolve(process.env.npm_config_releasepath, pkg.name.toLocaleLowerCase())
: path.resolve(process.cwd(), pkg.name.toLocaleLowerCase());
chainConfig.output
......@@ -155,10 +134,7 @@ module.exports = options => {
];
libraries.forEach(library => {
chainConfig.resolve.alias.set(
library.name,
getUserLibDir({ library: library.name }) || library.path,
);
chainConfig.resolve.alias.set(library.name, getUserLibDir({ library: library.name }) || library.path);
});
chainConfig.resolve.alias.set('@', path.join(__dirname, '../../', 'src'));
......@@ -182,6 +158,7 @@ module.exports = options => {
targets,
});
// eslint-disable-next-line global-require
const preset = require('./babel-preset');
const getPreset = preset({
...presetOpts,
......@@ -196,19 +173,14 @@ module.exports = options => {
reactRemovePropTypes: isProd,
reactRequire: true,
lockCoreJS3: {},
import: (presetOpts.import || []).concat([
{ libraryName: 'antd', libraryDirectory: 'es', style: true },
]),
import: (presetOpts.import || []).concat([{ libraryName: 'antd', libraryDirectory: 'es', style: true }]),
});
const babelOpts = {
sourceType: 'unambiguous',
babelrc: false,
presets: [...getPreset.presets, ...(defineConfig.extraBabelPresets || [])],
plugins: [
...getPreset.plugins,
...(defineConfig.extraBabelPlugins || []),
].filter(Boolean),
plugins: [...getPreset.plugins, ...(defineConfig.extraBabelPlugins || [])].filter(Boolean),
env: getPreset.env,
compact: false,
};
......@@ -381,10 +353,7 @@ module.exports = options => {
inject: true,
template: 'src/index.ejs',
favicon: defineConfig.favicon ? defineConfig.favicon : false,
title:
defineConfig.title && defineConfig.title !== false
? defineConfig.title
: '',
title: defineConfig.title && defineConfig.title !== false ? defineConfig.title : '',
chunks: defaultConfig.chunks ? defaultConfig.chunks : 'all',
};
const htmlPluginOptions = isDev
......@@ -407,39 +376,27 @@ module.exports = options => {
},
};
chainConfig
.plugin('htmlPlugins')
.use(require.resolve('html-webpack-plugin'), [htmlPluginOptions]);
chainConfig.plugin('htmlPlugins').use(require.resolve('html-webpack-plugin'), [htmlPluginOptions]);
chainConfig
.plugin('updateHtmlParams')
.use(require.resolve('./plugins/HtmlGenerator'), [
chainConfig.plugin('updateHtmlParams').use(require.resolve('./plugins/HtmlGenerator'), [
{
config: defineConfig,
},
]);
chainConfig
.plugin('replaceTheme')
.use(ThemeColorReplacer, [themePluginOption]);
chainConfig.plugin('replaceTheme').use(ThemeColorReplacer, [themePluginOption]);
const copyPatterns = [
fs.existsSync(path.join(process.cwd(), 'public')) && {
from: path.join(cwd, 'public'),
to: path.resolve(
process.env.npm_config_releasepath || process.cwd(),
pkg.name.toLocaleLowerCase(),
),
to: path.resolve(process.env.npm_config_releasepath || process.cwd(), pkg.name.toLocaleLowerCase()),
},
...(defineConfig.copy
? defineConfig.copy.map(item => {
if (typeof item === 'string') {
return {
from: path.join(cwd, item),
to: path.resolve(
process.env.npm_config_releasepath || process.cwd(),
pkg.name.toLocaleLowerCase(),
),
to: path.resolve(process.env.npm_config_releasepath || process.cwd(), pkg.name.toLocaleLowerCase()),
};
}
return {
......@@ -454,9 +411,7 @@ module.exports = options => {
].filter(Boolean);
if (copyPatterns.length) {
chainConfig
.plugin('copy')
.use(require.resolve('copy-webpack-plugin'), [copyPatterns]);
chainConfig.plugin('copy').use(require.resolve('copy-webpack-plugin'), [copyPatterns]);
}
if (isDev && defineConfig.fastRefresh) {
......@@ -464,9 +419,7 @@ module.exports = options => {
chainConfig
.plugin('fastRefresh')
.after('hmr')
.use(require('@pmmmwh/react-refresh-webpack-plugin'), [
{ overlay: false },
]);
.use(require('@pmmmwh/react-refresh-webpack-plugin'), [{ overlay: false }]);
debug('FastRefresh webpack loaded');
}
......@@ -505,19 +458,14 @@ module.exports = options => {
.loader(require.resolve('babel-loader'))
.options(babelOpts);
const rule = chainConfig.module
.rule('js-in-node_modules')
.test(/\.(js|mjs)$/);
const rule = chainConfig.module.rule('js-in-node_modules').test(/\.(js|mjs)$/);
const nodeModulesTransform = defineConfig.nodeModulesTransform || {
type: 'all',
exclude: [],
};
if (nodeModulesTransform.type === 'all') {
const exclude = lodash.uniq([
...TYPE_ALL_EXCLUDE,
...(nodeModulesTransform.exclude || []),
]);
const exclude = lodash.uniq([...TYPE_ALL_EXCLUDE, ...(nodeModulesTransform.exclude || [])]);
const pkgs = excludeToPkgs({ exclude });
rule.include
.add(/node_modules/)
......@@ -559,9 +507,7 @@ module.exports = options => {
);
chainConfig
.plugin('bundle-analyzer')
.use(require('umi-webpack-bundle-analyzer').BundleAnalyzerPlugin, [
mergeAnalyze || {},
]);
.use(require('umi-webpack-bundle-analyzer').BundleAnalyzerPlugin, [mergeAnalyze || {}]);
}
if (process.env.PROGRESS !== 'none') {
......@@ -592,11 +538,7 @@ module.exports = options => {
if (process.env.WEBPACK_PROFILE) {
chainConfig.profile(true);
const statsInclude = ['verbose', 'normal', 'minimal'];
chainConfig.stats(
statsInclude.includes(process.env.WEBPACK_PROFILE)
? process.env.WEBPACK_PROFILE
: 'verbose',
);
chainConfig.stats(statsInclude.includes(process.env.WEBPACK_PROFILE) ? process.env.WEBPACK_PROFILE : 'verbose');
const StatsPlugin = require('stats-webpack-plugin');
chainConfig.plugin('stats-webpack-plugin').use(
new StatsPlugin('stats.json', {
......@@ -617,22 +559,15 @@ module.exports = options => {
chainConfig.performance.hints(false);
if (!isWebpack5) {
chainConfig
.plugin('hash-module-ids')
.use(webpack.HashedModuleIdsPlugin, []);
chainConfig.plugin('hash-module-ids').use(webpack.HashedModuleIdsPlugin, []);
}
if (disableCompress) {
chainConfig.optimization.minimize(false);
} else if (!options.__disableTerserForTest) {
chainConfig.optimization
.minimizer('terser')
.use(require.resolve('terser-webpack-plugin'), [
chainConfig.optimization.minimizer('terser').use(require.resolve('terser-webpack-plugin'), [
{
terserOptions: deepmerge(
terserOptions,
defineConfig.terserOptions || {},
),
terserOptions: deepmerge(terserOptions, defineConfig.terserOptions || {}),
sourceMap: defineConfig.devtool !== false,
cache: process.env.TERSER_CACHE !== 'none',
parallel: true,
......@@ -660,13 +595,13 @@ module.exports = options => {
const optsMap = {
csr: {
minify: true,
target
target,
},
};
const opt = optsMap.csr;
chainConfig.optimization.minimize = true;
chainConfig.optimization.minimizer = [new ESBuildMinifyPlugin(opt)];
chainConfig.plugin('es-build').use(new ESBuildPlugin())
chainConfig.plugin('es-build').use(new ESBuildPlugin());
}
if (defineConfig.chainWebpack) {
......
......@@ -15,7 +15,7 @@ module.exports = require('./webpack.base.babel')({
optimization: {
// namedModules: true,
// namedChunks: true,
chunkIds: "named",
chunkIds: 'named',
runtimeChunk: {
name: 'runtime',
},
......
......@@ -22,7 +22,7 @@
"build": "cross-env NODE_ENV=production node --max_old_space_size=4096 internals/webpack/build.js",
"build:clean": "rimraf ./build",
"openapi": "cross-env NODE_ENV=development node server/openapi/run.js",
"start": "cross-env REACT_APP_ENV=dev NODE_ENV=development node --max_old_space_size=8192 server --port=$port",
"start": "cross-env REACT_APP_ENV=dev NODE_ENV=development node --max_old_space_size=4192 server --port=$port",
"start:tunnel": "cross-env NODE_ENV=development ENABLE_TUNNEL=true node server",
"start:production": "npm run test && npm run build && npm run start:prod",
"start:prod": "cross-env NODE_ENV=production node server",
......@@ -110,9 +110,9 @@
"@wisdom-map/Map": "^1.0.12-17",
"@wisdom-map/arcgismap": "^1.0.79-17",
"@wisdom-map/util": "^1.0.27-0",
"@wisdom-utils/components": "0.0.37",
"@wisdom-utils/components": "0.0.56",
"@wisdom-utils/runtime": "0.0.15",
"@wisdom-utils/utils": "0.0.77",
"@wisdom-utils/utils": "0.0.95",
"animate.css": "^4.1.1",
"antd": "^4.17.4",
"compression": "1.7.4",
......@@ -288,6 +288,7 @@
"svg-url-loader": "^2.3.2",
"swagger-ui-react": "^4.0.0-beta.4",
"swagger2openapi": "^7.0.5",
"swc-loader": "^0.1.15",
"terser-webpack-plugin": "1.2.3",
"traverse": "^0.6.6",
"umi-webpack-bundle-analyzer": "3.6.0",
......
......@@ -32,11 +32,7 @@ initLocale();
const unlisten = (function() {
let prePathname = '';
return history.listen(location => {
if (
location.pathname.indexOf('/civbase/user/login') > -1 &&
location.pathname !== prePathname
) {
console.log('init config');
if (location.pathname.indexOf('/civbase/user/login') > -1 && location.pathname !== prePathname) {
initGlobalConfig();
}
prePathname = location.pathname;
......
......@@ -5,11 +5,7 @@ import { connect } from 'react-redux';
import Icon from '@ant-design/icons';
import classNames from 'classnames';
import { useHistory } from '@wisdom-utils/runtime';
import {
HeaderSearch,
useIntl,
AvatarDropdown as Avatar,
} from '@wisdom-utils/components';
import { HeaderSearch, useIntl, AvatarDropdown as Avatar } from '@wisdom-utils/components';
import { actionCreators } from '../../containers/App/store';
import styles from './index.less';
import NoticeIconView from './NoticeIconView';
......
......@@ -2,20 +2,9 @@ import React, { Component } from 'react';
import { Button, Form, Input, Modal } from 'antd';
import { connect } from 'react-redux';
import {
Notifier,
NoticeIcon,
FormattedMessage,
} from '@wisdom-utils/components';
import {
ERR_OK,
MESSAGE_TYPE,
NEW_MESSAGE,
} from '@wisdom-utils/components/lib/AppLayout/notifier/constants';
import {
findPathByWidget,
isJSON,
} from '@wisdom-utils/components/lib/AppLayout/helpers';
import { Notifier, NoticeIcon, FormattedMessage } from '@wisdom-utils/components';
import { ERR_OK, MESSAGE_TYPE, NEW_MESSAGE } from '@wisdom-utils/components/lib/AppLayout/notifier/constants';
import { findPathByWidget, isJSON } from '@wisdom-utils/components/lib/AppLayout/helpers';
import service from '../../api/service/notification';
import { actionCreators } from '../../containers/App/store';
import isProd from '../../utils/env';
......
......@@ -46,22 +46,22 @@
background: #fff;
}
}
.account {
.avatar {
margin: ~'calc((@{layout-header-height} - 24px) / 2)' 0;
// margin-right: 8px;
color: @primary-color;
vertical-align: top;
background: rgba(255, 255, 255, 0.85);
width: 36px;
height: 36px;
border-radius: 50%;
box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.3);
transition: box-shadow 0.1s linear, opacity 0.4s linear;
background-position: center;
overflow: hidden;
}
}
//.account {
// .avatar {
// margin: ~'calc((@{layout-header-height} - 24px) / 2)' 0;
// // margin-right: 8px;
// color: @primary-color;
// vertical-align: top;
// background: rgba(255, 255, 255, 0.85);
// width: 36px;
// height: 36px;
// border-radius: 50%;
// box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.3);
// transition: box-shadow 0.1s linear, opacity 0.4s linear;
// background-position: center;
// overflow: hidden;
// }
//}
}
.dark {
......
......@@ -3,45 +3,28 @@ import React from 'react';
import { Helmet } from 'react-helmet';
import { connect } from 'react-redux';
import { Router, Switch } from '@wisdom-utils/runtime';
import { renderRoutes } from '../../utils/routes';
import { helpers } from '@wisdom-utils/utils';
// eslint-disable-next-line import/extensions
import { dyRoutes } from '../../routes/config';
const pkg = require('../../../package.json');
const config = require('../../../config/config');
const defaultSetting = config.layout;
const { renderRoutes } = helpers;
function App(props) {
//
const metaSecurity = /https/.test(window.location.protocol) ? (
<meta
httpEquiv="Content-Security-Policy"
content="upgrade-insecure-requests"
/>
<meta httpEquiv="Content-Security-Policy" content="upgrade-insecure-requests" />
) : null;
return (
<>
<Helmet
title={`${(props.global && props.global.title) ||
defaultSetting.title}`}
>
<title>{`${(props.global && props.global.title) ||
defaultSetting.title}`}</title>
<link
rel="shortcut icon"
href={`https://panda-water.cn/web4/${props.global &&
props.global.shortcutIcon}`}
/>
<Helmet title={`${(props.global && props.global.title) || defaultSetting.title}`}>
<title>{`${(props.global && props.global.title) || defaultSetting.title}`}</title>
<link rel="shortcut icon" href={`https://panda-water.cn/web4/${props.global && props.global.shortcutIcon}`} />
{metaSecurity}
<meta
name="description"
content={`${props.global && props.global.title}`}
/>
<meta name="description" content={`${props.global && props.global.title}`} />
</Helmet>
<Router basename={config.base || pkg.name.toLocaleLowerCase() || ''}>
<Switch>
{renderRoutes(dyRoutes(props.menu || [], props.global.layout).routes)}
</Switch>
<Switch>{renderRoutes('panda-console-base', dyRoutes(props.menu || [], props.global.layout).routes)}</Switch>
</Router>
</>
);
......
import { fromJS } from 'immutable';
import Cookies from 'js-cookie';
import { AppConfig, store, event, Storage } from '@wisdom-utils/utils';
import { AppConfig, store, event, Storage, helpers } from '@wisdom-utils/utils';
import { Storeage as Store } from '@wisdom-utils/utils/lib/helpers';
import pkg from '../../../../package.json';
import defaultSetting from '../../../../config/defaultSetting';
import generRoutes, {
generFlatRoutes,
transformWidgets,
} from '../../../utils/routes';
// import { transformWidgets } from '../../../utils/routes';
// eslint-disable-next-line import/no-duplicates
import {
CLEAR_RCENT_KEYWORD,
COMPLEX_CONFIG,
......@@ -35,20 +33,14 @@ import {
PD_VIEW,
} from './constants';
const { generMainRoutes, generFlatRoutes, transformWidgets } = helpers;
const proxy = require('../../../../config/proxy');
const keywordStorage = new Storage(
`__global_search_keywords__micro_${window.location.hostname}`,
);
const recentVisitedStorage = new Storage(
`__global_recent_visited__micro_${window.location.hostname}`,
);
const recentProductStorage = new Storage(
`__global__recent_product__micro_${window.location.hostname}`,
);
const currentProduct = new Store(
`__global__recent_productIndex__micro_${window.location.hostname}`,
);
const keywordStorage = new Storage(`__global_search_keywords__micro_${window.location.hostname}`);
const recentVisitedStorage = new Storage(`__global_recent_visited__micro_${window.location.hostname}`);
const recentProductStorage = new Storage(`__global__recent_product__micro_${window.location.hostname}`);
const currentProduct = new Store(`__global__recent_productIndex__micro_${window.location.hostname}`);
Cookies.set('loginMode', Cookies.get('loginMode') || 'pdw');
export const initialState = fromJS({
globalConfig: {},
......@@ -80,12 +72,9 @@ export const initialState = fromJS({
const appReducer = (state = initialState, action) => {
switch (action.type) {
case GET_CONFIG:
// eslint-disable-next-line no-debugger
// eslint-disable-next-line no-underscore-dangle
/* eslint-disable */
window.__INITIAL_STATE__ = Object.assign(
{},
// eslint-disable-next-line no-underscore-dangle
action.data,
{
assetsRoot: proxy.assetsRoot,
......@@ -93,14 +82,10 @@ const appReducer = (state = initialState, action) => {
env: process.env.NODE_ENV === 'development' ? 'daily' : 'prod',
},
);
window.arcgisAssetsPath = `${
window.location.origin
}/${pkg.name.toLocaleLowerCase()}/assets`;
// eslint-disable-next-line global-require,no-underscore-dangle
window.arcgisAssetsPath = `${window.location.origin}/${pkg.name.toLocaleLowerCase()}/assets`;
window.__INITIAL_STATE__.mdi = 'SDI';
window.__INITIAL_STATE__.menu = 'banner-left';
window.globalConfig = AppConfig(window.__INITIAL_STATE__);
// eslint-disable-next-line no-undef
createStoreage.set('globalConfig', window.globalConfig);
// eslint-disable-next-line no-undef,no-case-declarations
......@@ -109,14 +94,11 @@ const appReducer = (state = initialState, action) => {
// eslint-disable-next-line no-case-declarations
const { homepage } = window.globalConfig;
const modulePkg = {};
window.globalConfig &&
window.globalConfig.products &&
Array.isArray(window.globalConfig.products) &&
window.globalConfig.products.map(item => {
window.globalConfig && window.globalConfig.products && Array.isArray(window.globalConfig.products) && window.globalConfig.products.map(item => {
modulePkg[item.PackageName] = item;
});
config.widgets = transformWidgets(config.widgets);
const generMenu = generRoutes(config.widgets || [], null, 0, modulePkg);
const generMenu = generMainRoutes(config.widgets || [], null, 0, modulePkg);
let flatMenu = [];
if (generMenu) {
flatMenu = generFlatRoutes(generMenu || [], null, null, modulePkg);
......@@ -133,27 +115,14 @@ const appReducer = (state = initialState, action) => {
let currentMenuIndex = 0;
if (home) {
const parent =
home.level >= 2
? home.parent.parent
: home.level >= 3
? home.parent.parent.parent
: home.parent;
const parent = home.level >= 2 ? home.parent.parent : home.level >= 3 ? home.parent.parent.parent : home.parent;
if (parent) {
currentMenuIndex = generMenu.findIndex(
item => item.name === parent.label,
);
currentMenuIndex = generMenu.findIndex(item => item.name === parent.label);
currentProduct.set('currentMenuIndex', currentMenuIndex);
store.set('updateMenuIndex', currentMenuIndex);
}
}
// eslint-disable-next-line no-case-declarations
// eslint-disable-next-line no-case-declarations
window.globalConfig.home = home;
Cookies.set('city', Cookies.get('city') || window.globalConfig.client);
window.globalConfig = config;
return state.merge({
......
......@@ -3,7 +3,7 @@ import { params, Storeage } from '@wisdom-utils/utils/lib/helpers';
import { appService } from './api';
import { initMicroApps } from './micro';
import { actionCreators } from './containers/App/store';
import { getToken, isString } from './utils/utils';
import { getToken } from './utils/utils';
import loader, { render } from './render';
import store from './stores';
import Login from './pages/user/login/login';
......@@ -11,14 +11,12 @@ import Login from './pages/user/login/login';
const namespace = `__PANDA_STORE__${location.hostname}`;
window.createStoreage = new Storeage(namespace);
export const initGlobalConfig = () => {
// eslint-disable-next-line no-debugger
// eslint-disable-next-line no-undef
/* eslint-disable */
createStoreage.remove(`__PANDA_STORE__${location.hostname}`);
window.globalConfig = {};
window.__INITIAL_STATE__ = {};
let config = window.globalConfig || {};
//createStoreage.get('globalConfig') || {};
// createStoreage.get('globalConfig') || {};
store.dispatch(actionCreators.updateComplexConfig({}));
if (!getToken() || config.token == null) {
// eslint-disable-next-line no-undef
......@@ -37,7 +35,7 @@ export const initGlobalConfig = () => {
if (!getToken()) {
localStorage.removeItem('loginSite');
}
/* eslint-disable */
if (window.globalConfig.token !== null && Object.keys(window.globalConfig).length > 0) {
store.dispatch(actionCreators.getConfig(window.globalConfig));
// render({ appContent: '', loading: true });
......@@ -47,28 +45,21 @@ export const initGlobalConfig = () => {
}
} else {
// eslint-disable-next-line react-hooks/rules-of-hooks
let client = params.getParams('client') || Cookies.get('city')
let client = params.getParams('client') || Cookies.get('city');
client = client && client !== 'undefined' ? client : 'city';
appService.getWateWayConfig({
appService
.getWateWayConfig({
ignoreSite: true,
}).then(res => {
const hasGateWay =
!res || !res.data ? false : isString(res.data) ? JSON.parse(res.data) : typeof res.data === 'boolean' ? res.data : false;
// if (res.code === 0 && res.data === 'true') {
// store.dispatch(
// actionCreators.getConfig(
// Object.assign({}, window.globalConfig, {
// hasGateWay,
// apiGatewayDomain: `${window.location.origin}/PandaCore`,
// }),
// ),
// );
// }
})
.then(res => {
/* eslint-disable */
const hasGateWay = !res || !res.data ? false : _.isString(res.data) ? JSON.parse(res.data) : typeof res.data === 'boolean' ? res.data : false;
return {
hasGateWay,
apiGatewayDomain: `${window.location.origin}/PandaCore`,
}
}).then((gateWayConfig) => {
};
})
.then(gateWayConfig => {
appService
.queryConfig({
client: client || 'city',
......@@ -83,22 +74,26 @@ export const initGlobalConfig = () => {
// Cookies.set('city', data.client);
store.dispatch(
actionCreators.getConfig(
Object.assign({}, data, {
Object.assign(
{},
data,
{
token: '',
access_token: '',
userInfo: null
}, gateWayConfig),
userInfo: null,
},
gateWayConfig,
),
),
);
//Cookies.set('city', params.getParams('client'))
// Cookies.set('city', params.getParams('client'))
if (data.loginTemplate === '新春 - 智联.html') {
updateTheme('#ff9600');
}
// eslint-disable-next-line no-new
if (getToken()) {
// eslint-disable-next-line no-new
new Login(
{
......@@ -106,7 +101,8 @@ export const initGlobalConfig = () => {
token: getToken(),
}),
// eslint-disable-next-line no-shadow
updateConfig: data =>store.dispatch(actionCreators.getConfig(data)),
updateConfig: data =>
store.dispatch(actionCreators.getConfig(data)),
isInit: false,
logout: () => store.dispatch(actionCreators.logout()),
},
......@@ -114,7 +110,8 @@ export const initGlobalConfig = () => {
(async () => {
(await (getToken() &&
window.globalConfig &&
window.globalConfig.token)) && initMicroApps(loader, store);
window.globalConfig.token)) &&
initMicroApps(loader, store);
})();
},
true,
......@@ -138,6 +135,5 @@ export const initGlobalConfig = () => {
store.dispatch(actionCreators.getConfigError(error));
});
});
}
};
};
import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Anchor, Button, Popover, Radio, Result, Spin } from 'antd';
import { store } from '@wisdom-utils/utils';
......@@ -14,19 +8,16 @@ import { dom } from '@wisdom-utils/utils/lib/helpers';
import { connect } from 'react-redux';
import { useMountedState } from 'react-use';
import {
LeftOutlined,
LoadingOutlined,
MenuFoldOutlined,
} from '@ant-design/icons';
import { LeftOutlined, LoadingOutlined, MenuFoldOutlined } from '@ant-design/icons';
import ProLayout, { getPageTitle } from '@ant-design/pro-layout';
import { getMatchMenu } from '@umijs/route-utils';
import { useHistory } from '@wisdom-utils/runtime';
import { Panel } from '@wisdom-utils/components';
import { findPathByLeafId } from '@wisdom-utils/components/lib/AppLayout/helpers';
import RightContent from '@/components/GlobalHeader/RightContent';
import { actionCreators } from '@/containers/App/store';
import Authorized from '@/utils/Authorized';
import { findPathByLeafId, getBaseName } from '@/utils/utils';
import { getBaseName } from '@/utils/utils';
import pkg from '../../package.json';
import SecurityLayout from './SecurityLayout';
import Site from './Site';
......@@ -41,10 +32,7 @@ const antIcon = <LoadingOutlined style={{ fontSize: 12 }} spin />;
// const baseURI = isProd
// ? window.location.origin
// : `http://${window.location.hostname}:3020`;
const optionsWith = [
{ label: '按站点', value: 'site' },
{ label: '按城市', value: 'city' },
];
const optionsWith = [{ label: '按站点', value: 'site' }, { label: '按城市', value: 'city' }];
const noMatch = (
<Result
status={403}
......@@ -55,11 +43,7 @@ const noMatch = (
);
const renderIcon = (icon, size, alias) => (
<img
src={icon}
style={{ width: `${size}px`, height: `${size}px`, opacity: '0.8' }}
alt=""
/>
<img src={icon} style={{ width: `${size}px`, height: `${size}px`, opacity: '0.8' }} alt="" />
);
const menuExtraRender = currentRoutes => {
......@@ -68,23 +52,13 @@ const menuExtraRender = currentRoutes => {
return {
render: ({ collapsed }) => {
if (currentRoutes) {
const iconURL =
currentRoutes && currentRoutes.extData && currentRoutes.extData.icon;
const iconURL = currentRoutes && currentRoutes.extData && currentRoutes.extData.icon;
return (
<>
<Spin
spinning={currentRoutes.extData && !currentRoutes.extData.icon}
>
<Spin spinning={currentRoutes.extData && !currentRoutes.extData.icon}>
{iconURL && (
<a
style={{ display: 'flex', alignItems: 'center' }}
onClick={() => setToggleSystem(!toggleSystem)}
>
<img
src={iconURL}
style={{ width: '20px', height: '20px' }}
alt=""
/>
<a style={{ display: 'flex', alignItems: 'center' }} onClick={() => setToggleSystem(!toggleSystem)}>
<img src={iconURL} style={{ width: '20px', height: '20px' }} alt="" />
<span
style={{
......@@ -98,9 +72,7 @@ const menuExtraRender = currentRoutes => {
>
{currentRoutes && currentRoutes.name}
</span>
<MenuFoldOutlined
style={{ color: '#888', marginLeft: '10px' }}
/>
<MenuFoldOutlined style={{ color: '#888', marginLeft: '10px' }} />
</a>
)}
</Spin>
......@@ -119,10 +91,7 @@ const StationsItem = (item, action) => {
action.changeGroup && action.changeGroup(event, data);
};
return (
<li
key={item.groupID}
style={{ marginRight: `${item.style.marginRight}px` }}
>
<li key={item.groupID} style={{ marginRight: `${item.style.marginRight}px` }}>
<a
className={classNames(styles.city_select, styles.showTip)}
title={item.city}
......@@ -131,9 +100,7 @@ const StationsItem = (item, action) => {
onClick={event => changeGroup(event, item)}
>
{item.groupName}
{item.promoteTip && HOT.includes(item.promoteTip) && (
<div title={`${item.promoteTip}`}>{item.promoteTip}</div>
)}
{item.promoteTip && HOT.includes(item.promoteTip) && <div title={`${item.promoteTip}`}>{item.promoteTip}</div>}
</a>
</li>
);
......@@ -159,11 +126,7 @@ const Stations = props => {
return (
<>
<div className={styles.focusStations}>
<ul>
{Array.isArray(data)
? data.map(item => StationsItem(item, props.action))
: null}
</ul>
<ul>{Array.isArray(data) ? data.map(item => StationsItem(item, props.action)) : null}</ul>
</div>
<Radio.Group
options={optionsWith}
......@@ -176,36 +139,21 @@ const Stations = props => {
/>
<div style={{ maxWidth: '520px', position: 'relative' }}>
{defaultTab === 'site' ? (
<div
className={classNames(styles.city_pane, styles.station_container)}
ref={cityPane}
>
<div className={classNames(styles.city_pane, styles.station_container)} ref={cityPane}>
<Anchor
affix={false}
onClick={handleClick}
targetOffset={targetOffset}
getContainer={() => cityContent.current}
>
<ul className={styles.py}>
{props.data &&
props.data.siteCityList &&
props.data.siteCityList.letters}
</ul>
<div
className={styles.cityContent}
style={{ height: '335px' }}
ref={cityContent}
>
{props.data &&
props.data.siteCityList &&
props.data.siteCityList.content}
<ul className={styles.py}>{props.data && props.data.siteCityList && props.data.siteCityList.letters}</ul>
<div className={styles.cityContent} style={{ height: '335px' }} ref={cityContent}>
{props.data && props.data.siteCityList && props.data.siteCityList.content}
</div>
</Anchor>
</div>
) : (
<div className="city_pane city_container">
{props.data.citySelector}
</div>
<div className="city_pane city_container">{props.data.citySelector}</div>
)}
<Spin spinning={props.loading} tip="加载中" />
</div>
......@@ -213,16 +161,7 @@ const Stations = props => {
);
};
const renderTitle = ({
title,
action,
data,
loading,
setLoading,
collapsed,
fixedHeader,
config,
}) => {
const renderTitle = ({ title, action, data, loading, setLoading, collapsed, fixedHeader, config }) => {
// eslint-disable-next-line react-hooks/rules-of-hooks,no-debugger
// eslint-disable-next-line react-hooks/rules-of-hooks
const [visible, setVisible] = useState(false);
......
......@@ -466,7 +466,6 @@
}
& :global {
.@{ant-prefix}-dropdown-menu-item {
display: flex;
......
import React, {
useEffect,
useRef,
useState,
useContext,
} from 'react';
import {
Anchor,
Popover,
Radio,
Spin,
Tabs,
Divider,
Dropdown,
Menu,
Tooltip,
ConfigProvider,
Skeleton,
} from 'antd';
import React, { useEffect, useRef, useState, useContext } from 'react';
import { Anchor, Popover, Radio, Spin, Tabs, Divider, Dropdown, Menu, Tooltip, ConfigProvider, Skeleton } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import Icon, {
// LeftOutlined,
......@@ -25,7 +8,7 @@ import Icon, {
// MenuFoldOutlined,
DownOutlined,
} from '@ant-design/icons';
import { store } from '@wisdom-utils/utils';
import { store, helpers } from '@wisdom-utils/utils';
import classNames from 'classnames';
import { ReactSVG } from 'react-svg';
import Cookies from 'js-cookie';
......@@ -33,20 +16,22 @@ import { connect } from 'react-redux';
import { useHistory } from '@wisdom-utils/runtime';
import KeepAlive from 'react-activation';
import AMapLoader from '@amap/amap-jsapi-loader';
import { MinPanel } from '@wisdom-utils/components';
import { findPathByLeafId } from '@wisdom-utils/components/lib/AppLayout/helpers';
import RightContent from '@/components/GlobalHeader/ExtendRightContent';
// import Panel from '@/components/SliderPanel/MinPanel';
import { MinPanel as Panel } from '@wisdom-utils/components';
import { actionCreators } from '@/containers/App/store';
import { ArcgisMap, AMap, CesiumMap } from '../pages/map';
import { WEB_GIS_TYPE } from '../constants';
import { findPathByLeafId, getBaseName } from '@/utils/utils';
import { renderRoutes, getParams } from '../utils/routes';
// import { getBaseName } from '@/utils/utils';
// eslint-disable-next-line import/no-duplicates
import SecurityLayout from './SecurityLayout';
import Site from './Site';
import styles from './UserLayout.less';
import layoutStyles from './BasicLayout.less';
// eslint-disable-next-line import/extensions
const { TabPane } = Tabs;
const { renderRoutes, params } = helpers;
const { getParamsV1 } = params;
const { layout: defaultSetting } = require('../../config/config');
// import Login from '../pages/user/login/login';
const antIcon = <LoadingOutlined style={{ fontSize: 12 }} spin />;
......@@ -230,14 +215,12 @@ const renderSite = ({ data, config, loading, setLoading, action }) => {
style={{
borderLeft:
data.stations.length === 0 ? '0px' : '1px solid rgba(256, 256, 256, 0.3)',
}}
>
}}>
<img src={data.weathers && data.weathers.icon} className={layoutStyles.icon} />
<span className={layoutStyles.text}>{data.weathers && data.weathers.text}</span>
</span>
) : null}
</>
)
}
......@@ -260,7 +243,7 @@ const BasicLayout = props => {
() => new Site(props, setSiteLoading),
);
const basename = getBaseName();
// const basename = getBaseName();
const history = useHistory();
// 处理隐藏菜单
......@@ -407,7 +390,7 @@ const BasicLayout = props => {
}
}
}
const params = getParams(props.location.pathname);
const params = getParamsV1(props.location.pathname);
if(params.hasOwnProperty('mapType') && params.mapType === WEB_GIS_TYPE.AMAP) {
AMapLoader.reset();
setMapMode(WEB_GIS_TYPE.AMAP)
......@@ -417,22 +400,6 @@ const BasicLayout = props => {
}
console.log(props.location, currentRoutes)
}, [props.location]);
// window.share.event.on('event:history', params => {
// setTimeout(() => {
// debugger
// const routes = currentRoutes.routes[selectIndex];
// if(routes) {
// const route = routes && routes.routes.find(item => item.path === decodeURI(window.location.pathname.replace('/civbase', '')));
// setTabActiveKey(route.path)
// }
// // window.share.event.removeListener('event:history')
// }, 0)
// })
// window.share && window.share.event.on('event:microError', event => {
// // window.history.pushState({message: '应用服务请求异常,请检查应用配置'}, null, '/civbase/404')
// history.push('/404');
// });
useEffect(() => {
window.share.event.on('updateSite', res => setCityData(res));
......@@ -645,7 +612,7 @@ const BasicLayout = props => {
</div>
</aside>
<div className={layoutStyles.layout} style={{ width: 'calc(100% - 80px)' }}>
<Panel
<MinPanel
visible={toggleSystem}
keyboard
onClose={() => setToggleSystem(false)}
......@@ -682,7 +649,6 @@ const BasicLayout = props => {
}
<RightContent />
</div>
</div>
</div>
<div className={layoutStyles['menu-item-children']}>
......@@ -718,16 +684,11 @@ const BasicLayout = props => {
</div>
<PageContainer style={{paddingTop: '0px', height: '100%'}}>
{
renderRoutes(props.route.routes, props)
renderRoutes('panda-console-base', props.route.routes, props)
}
{
window.location.pathname.startsWith('/civbase/civ_3d') ? <KeepAlive><CesiumMap /></KeepAlive> : window.location.pathname.startsWith('/civbase/civ_webgis') ? ((mapMode === 'AMap' ? <AMap/>: <ArcgisMap options={{ type: 'ArcgisMap' }}/>)) : null
}
<div id="micro-container" className="subapp-container">
{props.children}
......@@ -742,7 +703,7 @@ const BasicLayout = props => {
): (
<PageContainer style={{paddingTop: '0px', height: '100%'}}>
{
renderRoutes(props.route.routes, props)
renderRoutes('panda-console-base', props.route.routes, props)
}
{
......
......@@ -3,10 +3,10 @@ import React from 'react';
import { Helmet, HelmetProvider } from 'react-helmet-async';
import { connect } from 'react-redux';
import { getMenuData, getPageTitle } from '@ant-design/pro-layout';
import { renderRoutes } from '../utils/routes';
// import { renderRoutes } from '../utils/routes';
import { helpers } from '@wisdom-utils/utils';
import styles from './UserLayout.less';
const { renderRoutes } = helpers;
const UserLayout = props => {
const {
route = {
......@@ -35,7 +35,7 @@ const UserLayout = props => {
<div className={styles.container}>
<div className={styles.content}>
{renderRoutes(route.routes, props)}
{renderRoutes('panda-console-base', route.routes, props)}
{props.children}
</div>
{/* <DefaultFooter links={[]} copyright="Copyright © 熊猫智慧水务 2020 All Rights Reserved 沪ICP备11036640-1"/> */}
......@@ -43,7 +43,7 @@ const UserLayout = props => {
</HelmetProvider>
);
};
// const mapStateToProps = state => ({
// global: state.getIn(['global', 'globalConfig']),
// });
export default UserLayout;
const mapStateToProps = state => ({
global: state.getIn(['global', 'globalConfig']),
});
export default connect(mapStateToProps)(UserLayout);
This diff is collapsed.
......@@ -51,25 +51,19 @@ export const dyRoutes = (routes, layout) => {
},
{
path: '/iframe',
component: Iframe
component: Iframe,
},
{
path: '/404',
component: dynamic({
loader: () =>
import(
/* webpackChunkName: 'p__404' */ '../pages/exception/404'
),
loader: () => import(/* webpackChunkName: 'p__404' */ '../pages/exception/404'),
loading: LoadingComponent,
}),
},
{
path: '/500',
component: dynamic({
loader: () =>
import(
/* webpackChunkName: 'p__500' */ '../pages/exception/500'
),
loader: () => import(/* webpackChunkName: 'p__500' */ '../pages/exception/500'),
loading: LoadingComponent,
}),
},
......@@ -90,24 +84,17 @@ export const dyRoutes = (routes, layout) => {
{
path: '/404',
component: dynamic({
loader: () =>
import(
/* webpackChunkName: 'p__404' */ '../pages/exception/404'
),
loader: () => import(/* webpackChunkName: 'p__404' */ '../pages/exception/404'),
loading: LoadingComponent,
}),
},
{
path: '/500',
component: dynamic({
loader: () =>
import(
/* webpackChunkName: 'p__500' */ '../pages/exception/500'
),
loader: () => import(/* webpackChunkName: 'p__500' */ '../pages/exception/500'),
loading: LoadingComponent,
}),
},
],
};
};
......@@ -17,9 +17,7 @@ export default ({ key, reducer }) => WrappedComponent => {
static contextType = ReactReduxContext;
static displayName = `withReducer(${WrappedComponent.displayName ||
WrappedComponent.name ||
'Component'})`;
static displayName = `withReducer(${WrappedComponent.displayName || WrappedComponent.name || 'Component'})`;
constructor(props, context) {
super(props, context);
......
......@@ -2,10 +2,10 @@ import * as React from 'react';
import * as ReactDOM from 'react-dom';
function registerGlobal(root, deps) {
Object.keys(deps).forEach((key) => {
Object.keys(deps).forEach(key => {
root[key] = deps[key];
});
};
}
registerGlobal(window, {
// 在这里注册暴露给子工程的全局变量
......
import React from 'react';
import { guid, params, urlHelpers } from '@wisdom-utils/utils/lib/helpers';
import LoadingComponent from '@ant-design/pro-layout/es/PageLoading';
import { dynamic } from '@wisdom-utils/runtime';
import { matchPath, Route, Switch} from 'react-router';
const { getParamsV1 } = params;
const { isURL, isAbsoluteURL, getURL, transformURL } = urlHelpers
export const getParams = getParamsV1;
const DEFAULT_APPLICATION = 'civweb4';
const level = 0;
const generRotes = (widgets, parent, level = 0) => {
const ret = [];
if(!widgets || widgets.length === 0){
return
};
(widgets).forEach((item, index) => {
if (item.hasOwnProperty('widgets') && item.widgets !== null && Array.isArray(item.widgets) && item.widgets.length > 0) {
const _level_ = level + 1;
const path = `/civweb/${guid('web_console')}`;
const subKey = guid('panda');
const alias = DEFAULT_APPLICATION;
const convertURL = item.icon ? transformURL(item.icon.replace(/\s*/g, '')): '';
const icon = (item && item.icon && item.icon !== null &&
isAbsoluteURL(convertURL) ? convertURL: /(\\|\/)/.test(convertURL) ?
window.globalConfig.transformDevAssetsBaseURL(transformURL(item.icon.replace(/\s*/g, ''))): item.icon
) || '';
ret.push({
name: item.label,
level: _level_,
path,
component: 'BasicLayout',
parent,
alias: alias,
hideInMenu: item.hideInMenu || false,
routes: generRotes(
item.widgets,
Object.assign({}, item, { path, key: subKey }),
_level_,
item.label
),
extData: {
...item,
icon: icon,
},
});
} else {
const baseURL = item.product || DEFAULT_APPLICATION;
if(item.hasOwnProperty('url') && item.url === '') return;
let url = item.hasOwnProperty('url') && item.url !== undefined && item.url !== '' ? `/${baseURL}/${item.url.replace(/\s*/g, '')}`
: !item.hasOwnProperty('url')
? guid('web_console')
: '';
if (url.includes('url=')) {
url = url.split('url=')[1];
url = getURL(url);
}
if(isURL(item.url)) {
url = item.url
}
url = transformURL(url);
//url = url.replace(/[(\\|)|(&)]widget=[0-9]*/, '')
const convertURL = item.icon && transformURL(item.icon.replace(/\s*/g, ''));
const icon = (item && item.icon && item.icon !== null &&
isAbsoluteURL(convertURL) ? convertURL: /(\\|\/)/.test(convertURL) ?
window.globalConfig.transformDevAssetsBaseURL(transformURL(item.icon.replace(/\s*/g, ''))): item.icon
) || '';
const l = level ? level + 1 : -1;
let common = {
name: item.label,
level: l,
component: 'BasicLayout',
path: baseURL !== '' ? transformURL(url) : '',
href: url,
target: isURL(url) ? '_blank' : '',
key: guid('panda'),
hideInMenu: item.label === '系统菜单组' ? true: item.hideInMenu,
//l > 3 ? true: item.hideInMenu || false,
alias: item.product || DEFAULT_APPLICATION,
extData: {
...item,
icon,
},
parent,
params: getParams(url),
};
if(/iframe/.test(url)) {
url = url.replace(/\/report/, '');
common = {
name: item.label,
level: l,
component: dynamic({ loader: () =>
import ( /* webpackChunkName: "p__[request]" */ `@/pages/${component}.js`), loading: LoadingComponent }),
path: baseURL !== '' ? transformURL(url) : '',
href: url,
target: isURL(url) ? '_blank' : '',
key: guid('panda'),
hideInMenu: item.label === '系统菜单组' ? true: item.hideInMenu,
//l > 3 ? true: item.hideInMenu || false,
alias: item.product || DEFAULT_APPLICATION,
extData: {
...item,
icon,
},
params: getParams(url),
parent,
}
}
ret.push(common);
}
});
return ret;
};
export const transformWidgets = (widgets) => {
if(!widgets || widgets.length === 0) {
return []
}
return widgets.map(item => {
const widgets = item.widgets;
const homepage = window.globalConfig.homepage;
const homePageConvertArray = homepage ? homepage.split("/"): [];
const findIndex = widgets && widgets.findIndex(item => item.label === '系统菜单组');
if(findIndex === -1 && homePageConvertArray[0] !== 'civweb4') {
const index = widgets.findIndex(item => item.label === '首页');
if(index === -1) {
widgets.push({
label: "首页",
icon: '',
product: homePageConvertArray[0],
shortName: "首页",
hideInMenu: true,
url: homePageConvertArray.slice(1, homePageConvertArray.length).join("/")
});
}
item.widgets = Array.from(new Set(widgets));
}
return item;
});
}
export function simpleNormalizeChildren(children) {
for (let i = 0; i < children.length; i++) {
if (Array.isArray(children[i])) {
return Array.prototype.concat.apply([], children);
}
}
return children;
}
export const generFlatRoutes = (widgets, parent, subSystem, modulePkg) => {
const treeKeys = [];
const flatMenu = [];
if(!widgets || Array.isArray(widgets) && widgets.length === 0) {
return [];
}
(widgets || []).forEach(item => {
if (item.hasOwnProperty('routes')) {
const route = generFlatRoutes(item.routes, item, item.name, modulePkg);
flatMenu.push(simpleNormalizeChildren(route));
} else {
flatMenu.push({
...item,
origin: item,
moduleName: modulePkg[item.alias],
treeKeys,
subSystem,
parent,
});
}
});
return simpleNormalizeChildren(flatMenu);
};
export function RouteWithSubRoutes(route) {
return (
<Route path={route.path} render={props => (<route.component {...props} route={route} routes={route.routes} params={route.params}/>)}></Route>
)
}
function matchRoutes(routes, pathname, branch) {
if (branch === void 0) {
branch = [];
}
routes.some(function (route) {
var match = route.path ? matchPath(pathname, route) : branch.length ? branch[branch.length - 1].match // use parent match
: Router.computeRootMatch(pathname); // use default "root" match
if (match) {
branch.push({
route: route,
match: match
});
if (route.routes) {
matchRoutes(route.routes, pathname, branch);
}
}
return match;
});
return branch;
}
function renderRoutes(routes, extraProps, switchProps) {
if (extraProps === void 0) {
extraProps = {};
}
if (switchProps === void 0) {
switchProps = {};
}
return routes ? React.createElement(Switch, switchProps, routes.map(function (route, i) {
return React.createElement(Route, {
key: route.key || i,
path: route.path,
exact: route.exact,
strict: route.strict,
render: function render(props) {
return route.render ? route.render(Object.assign({}, props, {}, extraProps, {
routes: route.routes,
params: route.params,
route: route,
rootPrefix: 'panda-console-base'
})) : React.createElement(route.component, Object.assign({}, props, extraProps, {
route: route,
routes: route.routes,
params: route.params,
rootPrefix: 'panda-console-base'
}));
}
});
})) : null;
}
export {
renderRoutes,
matchPath
}
export default generRotes;
......@@ -2,13 +2,9 @@ import Cookies from 'js-cookie';
import pathRegexp from 'path-to-regexp';
import { parse } from 'querystring';
import pkg from '../../package.json';
const { toString } = Object.prototype;
/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;
export const isUrl = path => reg.test(path);
export const getPageQuery = () => parse(window.location.href.split('?')[1]);
export const getAuthorityFromRouter = (router, pathname) => {
......@@ -51,86 +47,7 @@ export function isPromise(obj) {
export function getBaseName() {
return pkg.name.toLocaleLowerCase();
}
let cache = {};
export function findPathByLeafId(leafId, nodes, path, key, clear) {
if (path === undefined) {
path = {};
}
let tmpPath = path;
if(clear) {
cache = {};
}
if (cache[leafId]) {
return cache[leafId];
}
// eslint-disable-next-line no-plusplus
for (let i = 0; i < nodes.length; i++) {
if (nodes[i] && nodes[i][key] && leafId === nodes[i][key]) {
tmpPath = nodes[i];
cache[leafId] = tmpPath;
return tmpPath;
}
if (nodes[i] && nodes[i].routes) {
const findResult = findPathByLeafId(
leafId,
nodes[i].routes,
tmpPath,
key,
);
if (findResult) {
cache[leafId] = findResult;
return findResult;
}
}
}
}
export function findPathByWidget(leafId, nodes, path, key) {
if (path === undefined) {
path = {};
}
let tmpPath = path;
// eslint-disable-next-line no-plusplus
for (let i = 0; i < nodes.length; i++) {
if (nodes[i] && nodes[i][key] && nodes[i][key].indexOf(leafId) > -1) {
tmpPath = nodes[i];
return tmpPath;
}
if (nodes[i] && nodes[i].widgets) {
const findResult = findPathByWidget(
leafId,
nodes[i].widgets,
tmpPath,
key,
// eslint-disable-next-line no-restricted-globals
location,
);
if (findResult) {
return findResult;
}
}
}
return tmpPath;
}
export function isJSON(str) {
if (typeof str === 'string') {
try {
const obj = JSON.parse(str);
if (typeof obj === 'object' && obj) {
return true;
}
return false;
} catch (e) {
return false;
}
}
}
export function isString(str) {
return toString.call(str) === '[object String]';
}
export const getKeyName = path => {
const truePath = path.split('?')[0];
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment