Compare commits

...
25 Commits
Author SHA1 Message Date
zuiidea 5abad21082 ✨ Optimization Split Chunks, Antd Icon, CI. 2020-08-20 14:16:32 +08:00
Baorong Li 1ae41c7ae5 Merge pull request #1060 from mlboy/patch-1
Update README.md
2020-06-03 14:46:44 +08:00
mlboy e41671dbf9 Update README.md
调整antd版本
2020-05-13 07:42:01 +08:00
Baorong Li eaeb9092e4 bump antd-admin@5.3.0 2020-05-10 21:05:23 +08:00
Baorong Li 2f3ca0a006 Merge branch 'develop' 2020-05-10 21:04:40 +08:00
Baorong Li 1b65351be4 upgrade umi@3 fin. 2020-03-24 15:17:57 +08:00
Baorong Li 0422f6d51e upgrade umi@3 partly 2020-03-24 12:12:20 +08:00
Baorong Li 8d050d4040 fix pathToRegexp not work 2020-03-20 11:59:04 +08:00
zuiidea 82b3a4b384 ⚡️ Exclude node_modules by babel-loader. 2020-03-19 22:26:55 +08:00
Baorong Li d2f391a881 upgrade umi@3 partly 2020-03-19 17:06:31 +08:00
Baorong Li 9e778487d9 upgrade umi@3 partly 2020-03-19 12:50:12 +08:00
Baorong Li 7938d71f2f upgrade umi@3 partly 2020-03-19 00:05:44 +08:00
Baorong Li 422a6fed30 upgrade umi@3 partly 2020-03-18 16:17:25 +08:00
Baorong Li c6ea0454b3 upgrade umi@3 partly 2020-03-15 08:24:05 +08:00
Baorong Li 467767a6c5 upgrade umi@3 partly 2020-03-05 23:22:02 +08:00
Baorong Li cf795c512a bump antd-admin@5.2.0 2020-03-05 20:21:22 +08:00
Baorong Li 18b499030d upgrade antd@4.0.0 2020-02-29 22:47:45 +08:00
zuiidea d800d6f3ce Merge branch 'master' into develop 2020-01-08 09:31:45 +08:00
zuiidea 185f706107 💚 Fixing now config. 2020-01-07 17:17:57 +08:00
zuiidea 5a4661cdad Merge branch 'develop' of https://github.com/zuiidea/antd-admin into develop 2020-01-07 16:02:51 +08:00
zuiidea 7abdd94a0e 🚀 Optimize deployment configuration. 2020-01-07 16:02:33 +08:00
Baorong Li 22f0684ab0 chore: docs normal 2020-01-07 15:58:48 +08:00
Baorong Li 80b2c63693 Merge pull request #1040 from vagusX/feat/migrate-antd-v4
feat: migrate to antd v4
2019-12-02 22:07:08 -06:00
vagusX 4b2a553bda feat: add antd v4 dependencies 2019-12-03 10:19:54 +08:00
vagusX ad30e73b10 feat: migrate to antd v4 2019-12-03 09:58:49 +08:00
68 changed files with 1017 additions and 756 deletions
+10 -19
View File
@@ -4,24 +4,15 @@ node_js:
script:
- npm run build
before_install:
- |
if [ "$TRAVIS_BRANCH" = "develop" ]; then
for prefixed_envvar in ${!DEV_*}; do
eval export ${prefixed_envvar#DEV_}="${!prefixed_envvar}"
done
elif [ "$TRAVIS_BRANCH" = "master" ]; then
for prefixed_envvar in ${!PROD_*}; do
eval export ${prefixed_envvar#PROD_}="${!prefixed_envvar}"
done
else
for prefixed_envvar in ${!TEST_*}; do
eval export ${prefixed_envvar#TEST_}="${!prefixed_envvar}"
done
fi
- openssl aes-256-cbc -K $encrypted_18b2305b78c9_key -iv $encrypted_18b2305b78c9_iv -in config/id_rsa.enc -out ~/.ssh/id_rsa -d
- chmod 600 ~/.ssh/id_rsa
- echo -e "Host $HOST\n\tStrictHostKeyChecking no\n" >> ~/.ssh/config
- yarn global add now
after_script:
- scp -o stricthostkeychecking=no -r ./dist root@$HOST:$BUILD_DIR
- cd ./docs && now -A $DOC_NOW_CONFIG -t $NOW_TOKEN && now alias -A $DOC_NOW_CONFIG -t $NOW_TOKEN
- |
if [[ $TRAVIS_BRANCH == 'master' ]]; then
echo $PROD_SITE_NOW_CONFIG >> dist/vercel.json && echo $PROD_DOC_NOW_CONFIG >> docs/vercel.json;
else
echo $DEV_SITE_NOW_CONFIG >> dist/vercel.json && echo $DEV_DOC_NOW_CONFIG >> docs/vercel.json;
fi
- cd ./dist
- now -A vercel.json -t $NOW_TOKEN --prod -c
- cd ../docs
- now -A vercel.json -t $NOW_TOKEN --prod -c
+108 -78
View File
@@ -1,92 +1,28 @@
// https://umijs.org/config/
import { resolve } from 'path'
import { i18n } from './src/utils/config'
const fs = require('fs')
const path = require('path')
const lessToJs = require('less-vars-to-js')
const isDevelopment = process.env.NODE_ENV === 'development'
// how to speed compile: https://umijs.org/guide/boost-compile-speed
export default {
ignoreMomentLocale: true,
targets: { ie: 9 },
treeShaking: true,
plugins: [
[
// https://umijs.org/plugin/umi-plugin-react.html
'umi-plugin-react',
{
dva: { immer: true },
antd: true,
dynamicImport: {
webpackChunkName: true,
loadingComponent: './components/Loader/Loader',
},
routes: {
exclude: [
/model\.(j|t)sx?$/,
/service\.(j|t)sx?$/,
/models\//,
/components\//,
/services\//,
/chart\/Container\.js$/,
/chart\/ECharts\/.+Component\.js$/,
/chart\/ECharts\/.+ComPonent\.js$/,
/chart\/ECharts\/theme\/.+\.js$/,
/chart\/highCharts\/.+Component\.js$/,
/chart\/highCharts\/mapdata\/.+\.js$/,
/chart\/Recharts\/.+Component\.js$/,
/chart\/Recharts\/Container\.js$/,
],
update: routes => {
if (!i18n) return routes
const newRoutes = []
for (const item of routes[0].routes) {
newRoutes.push(item)
if (item.path) {
newRoutes.push(
Object.assign({}, item, {
path:
`/:lang(${i18n.languages
.map(item => item.key)
.join('|')})` + item.path,
})
)
}
}
routes[0].routes = newRoutes
return routes
},
},
dll: {
include: ['dva', 'dva/router', 'dva/saga', 'dva/fetch', 'antd/es'],
},
pwa: {
manifestOptions: {
srcPath: 'manifest.json',
},
},
},
],
],
// Theme for antd
// https://ant.design/docs/react/customize-theme
theme: './config/theme.config.js',
// Webpack Configuration
proxy: {
'/api/v1/weather': {
target: 'https://api.seniverse.com/',
changeOrigin: true,
pathRewrite: { '^/api/v1/weather': '/v3/weather' },
},
},
// IMPORTANT! change next line to yours or delete. And hide in dev
publicPath: isDevelopment ? '/' : 'https://cdn.antd-admin.zuiidea.com/',
alias: {
api: resolve(__dirname, './src/services/'),
components: resolve(__dirname, './src/components'),
config: resolve(__dirname, './src/utils/config'),
models: resolve(__dirname, './src/models'),
routes: resolve(__dirname, './src/routes'),
services: resolve(__dirname, './src/services'),
themes: resolve(__dirname, './src/themes'),
utils: resolve(__dirname, './src/utils'),
},
antd: {},
// a lower cost way to genereate sourcemap, default is cheap-module-source-map, could save 60% time in dev hotload
devtool: 'eval',
dva: { immer: true },
dynamicImport: {
loading: 'components/Loader/Loader',
},
extraBabelPresets: ['@lingui/babel-preset-react'],
extraBabelPlugins: [
[
@@ -98,5 +34,99 @@ export default {
},
'lodash',
],
[
'import',
{
libraryName: '@ant-design/icons',
libraryDirectory: 'es/icons',
camel2DashComponentName: false,
},
'ant-design-icons',
],
],
hash: true,
ignoreMomentLocale: true,
// umi3 comple node_modules by default, could be disable
nodeModulesTransform: {
type: 'none',
exclude: [],
},
// Webpack Configuration
proxy: {
'/api/v1/weather': {
target: 'https://api.seniverse.com/',
changeOrigin: true,
pathRewrite: { '^/api/v1/weather': '/v3/weather' },
},
},
targets: { ie: 9 },
// Theme for antd
// https://ant.design/docs/react/customize-theme
theme: lessToJs(
fs.readFileSync(path.join(__dirname, './src/themes/default.less'), 'utf8')
),
chainWebpack: function (config, { webpack }) {
config.merge({
optimization: {
minimize: true,
splitChunks: {
chunks: 'all',
minSize: 30000,
minChunks: 3,
automaticNameDelimiter: '.',
cacheGroups: {
react: {
name: 'react',
priority: 20,
test: /[\\/]node_modules[\\/](react|react-dom|react-dom-router)[\\/]/,
},
antd: {
name: 'antd',
priority: 20,
test: /[\\/]node_modules[\\/](antd|@ant-design\/icons)[\\/]/,
},
'echarts-gl': {
name: 'echarts-gl',
priority: 30,
test: /[\\/]node_modules[\\/]echarts-gl[\\/]/,
},
zrender: {
name: 'zrender',
priority: 30,
test: /[\\/]node_modules[\\/]zrender[\\/]/,
},
echarts: {
name: 'echarts',
priority: 20,
test: /[\\/]node_modules[\\/](echarts|echarts-for-react|echarts-liquidfill)[\\/]/,
},
highcharts: {
name: 'highcharts',
priority: 20,
test: /[\\/]node_modules[\\/]highcharts[\\/]/,
},
recharts: {
name: 'recharts',
priority: 20,
test: /[\\/]node_modules[\\/]recharts[\\/]/,
},
draftjs: {
name: 'draftjs',
priority: 30,
test: /[\\/]node_modules[\\/](draft-js|react-draft-wysiwyg|draftjs-to-html|draftjs-to-markdown)[\\/]/,
},
async: {
chunks: 'async',
minChunks: 2,
name: 'async',
maxInitialRequests: 1,
minSize: 0,
priority: 5,
reuseExistingChunk: true,
},
},
},
},
})
},
}
+1 -1
View File
@@ -11,7 +11,7 @@
An excellent front-end solution for enterprise applications.
[![antd](https://img.shields.io/badge/antd-^3.10.0-blue.svg?style=flat-square)](https://github.com/ant-design/ant-design)
[![antd](https://img.shields.io/badge/antd-^4.0.0-blue.svg?style=flat-square)](https://github.com/ant-design/ant-design)
[![umi](https://img.shields.io/badge/umi-^2.2.1-orange.svg?style=flat-square)](https://github.com/umijs/umi)
[![GitHub issues](https://img.shields.io/github/issues/zuiidea/antd-admin.svg?style=flat-square)](https://github.com/zuiidea/antd-admin/issues)
[![MIT](https://img.shields.io/dub/l/vibe-d.svg?style=flat-square)](http://opensource.org/licenses/MIT)
BIN
View File
Binary file not shown.
-8
View File
@@ -1,8 +0,0 @@
const fs = require('fs')
const path = require('path')
const lessToJs = require('less-vars-to-js')
module.exports = () => {
const themePath = path.join(__dirname, '../src/themes/default.less')
return lessToJs(fs.readFileSync(themePath, 'utf8'))
}
+1
View File
@@ -9,3 +9,4 @@
- Guide
- [Deploy](deploy.md)
- [Change Log](change-log.md)
- [FAQ](faq.md)
+1 -1
View File
@@ -28,7 +28,7 @@
- Support internationalization, extract source fields from source code, load language packs on demand, and automatically translate online.
- Support for the introduction of `ant-design-pro` components, `lodash` functions on demand.
- Support for the introduction `lodash` functions on demand.
  
- Support multiple layouts, which rules can be used according to the rules.
+9
View File
@@ -0,0 +1,9 @@
# FAQ
Most asked
## create new page
1. just copy a page in /src/pages (route here auto generated by [umi](https://umijs.org/guide/router.html#basic-routing))
2. modify namespace/pathToRegexp in model.js
3. modify mock route.js to add a route
-6
View File
@@ -1,6 +0,0 @@
{
"name": "antd-admin-devdoc",
"alias": ["devdoc-antd-admin.now.sh", "devdoc.antd-admin.zuiidea.com"],
"type": "static",
"public": true
}
-6
View File
@@ -1,6 +0,0 @@
{
"name": "antd-admin-doc",
"alias": ["doc-antd-admin.now.sh", "doc.antd-admin.zuiidea.com"],
"type": "static",
"public": true
}
+1 -1
View File
@@ -28,7 +28,7 @@
- 支持国际化,源码中抽离翻译字段,按需加载语言包,自动在线翻译。
- 支持按需引入 `ant-design-pro` 组件、`lodash` 函数。
- 支持按需引入 `lodash` 函数。
- 支持多布局,可根据规则规定哪些路由使用哪种布局。
+7
View File
@@ -0,0 +1,7 @@
# 问题集锦
## 新建页面
1. 直接从/src/pages复制一个page (会自动创建路由[umi](https://umijs.org/zh/guide/router.html#%E7%BA%A6%E5%AE%9A%E5%BC%8F%E8%B7%AF%E7%94%B1))
2. 修改 namespace/pathToRegexp 在 model.js
3. 修改 mock中route.js增加一条route
+1 -1
View File
@@ -12,7 +12,7 @@
npm run add-locale ja
```
2. 提取代码中需要翻译的字段,即 `<Trans>message</Trans>`、`` i18n.t`message `` 中 `message` 字段,运行下面命令后 `src/locales/ja/messages.json` 将会出现提取后的字段配置。
2. 提取代码中需要翻译的字段,即 `<Trans>message</Trans>`、`` intl.formatMessage({ id: 'message `` 中 `message` 字段,运行下面命令后 `src/locales/ja/messages.json' }) 将会出现提取后的字段配置。
```bash
npm run extract
+1 -1
View File
@@ -105,7 +105,7 @@ const Dashboard = Mock.mock({
content:
"I'm selfish, impatient and a little insecure. I make mistakes, I am out of control and at times hard to handle. But if you can't handle me at my worst, then you sure as hell don't deserve me at my best.",
avatar:
'http://img.hb.aicdn.com/bc442cf0cc6f7940dcc567e465048d1a8d634493198c4-sPx5BR_fw236',
'//cdn.antd-admin.zuiidea.com/bc442cf0cc6f7940dcc567e465048d1a8d634493198c4-sPx5BR_fw236',
},
numbers: [
{
+1 -1
View File
@@ -90,7 +90,7 @@ const database = [
name: 'Editor'
},
icon: 'edit',
route: '/UIElement/editor',
route: '/editor',
},
{
id: '5',
+2 -1
View File
@@ -1,4 +1,5 @@
import { Mock, Constant, qs, randomAvatar } from './_utils'
import { Mock, Constant, randomAvatar } from './_utils'
import qs from 'qs'
const { ApiPrefix } = Constant
+33 -31
View File
@@ -1,18 +1,18 @@
{
"name": "antd-admin",
"version": "5.1.3",
"version": "5.3.0",
"license": "MIT",
"description": "An admin dashboard application demo built upon Ant Design and UmiJS",
"dependencies": {
"@ant-design/icons": "^4.2.2",
"@lingui/react": "^2.8.0",
"ant-design-pro": "^2.3.0",
"antd": "^3.24.0",
"antd": "^4.0.0",
"axios": "^0.19.0",
"classnames": "^2.2.6",
"d3-shape": "^1.3.0",
"draftjs-to-html": "^0.8.4",
"draftjs-to-markdown": "^0.5.1",
"dva": "2.4.1",
"draft-js": "^0.11.7",
"draftjs-to-html": "^0.9.0",
"draftjs-to-markdown": "^0.6.0",
"dva-model-extend": "^0.1.2",
"echarts": "^4.4.0",
"echarts-for-react": "^2.0.15-beta.1",
@@ -25,47 +25,48 @@
"lodash": "^4.17.11",
"md5": "^2.2.1",
"nprogress": "^0.2.0",
"path-to-regexp": "^3.1.0",
"path-to-regexp": "^6.1.0",
"prop-types": "^15.7.0",
"qs": "^6.9.0",
"react-adsense": "^0.1.0",
"react-countup": "^4.2.0",
"react-draft-wysiwyg": "^1.13.0",
"react-helmet": "^5.2.0",
"react-helmet": "^6.0.0",
"react-highcharts": "^16.1.0",
"react-perfect-scrollbar": "^1.5.0",
"recharts": "^1.8.0",
"recharts": "^2.0.0-beta.3",
"store": "^2.0.0"
},
"devDependencies": {
"@lingui/babel-preset-react": "^2.8.2",
"@lingui/cli": "^2.8.2",
"@lingui/loader": "^2.8.2",
"babel-core": "7.0.0-bridge.0",
"@lingui/babel-preset-react": "^2.9.0",
"@lingui/cli": "^2.9.0",
"@lingui/loader": "^2.9.0",
"@umijs/preset-react": "^1.4.0",
"babel-eslint": "^10.0.1",
"babel-plugin-dev-expression": "^0.2.1",
"babel-plugin-import": "^1.12.0",
"babel-plugin-macros": "^2.6.0",
"babel-plugin-module-resolver": "^3.2.0",
"cross-env": "^6.0.0",
"eslint": "^5.15.0",
"eslint-config-react-app": "^4.0.0",
"eslint-plugin-flowtype": "^3.11.0",
"babel-plugin-module-resolver": "^4.0.0",
"cross-env": "^7.0.0",
"eslint": "^7.0.0",
"eslint-config-react-app": "^5.0.0",
"eslint-plugin-flowtype": "^5.1.0",
"eslint-plugin-import": "^2.18.0",
"eslint-plugin-jsx-a11y": "^6.2.1",
"eslint-plugin-react": "^7.14.0",
"eslint-plugin-react-hooks": "^1.6.0",
"husky": "^2.7.0",
"eslint-plugin-react-hooks": "^4.0.0",
"husky": "^4.2.0",
"less-vars-to-js": "^1.3.0",
"lint-staged": "^8.1.0",
"mockjs": "^1.0.1-beta3",
"lint-staged": "^10.0.0",
"mockjs": "^1.1.0",
"module": "^1.2.5",
"prettier": "^1.18.0",
"stylelint": "^10.0.0",
"stylelint-config-prettier": "^5.2.0",
"stylelint-config-standard": "^18.3.0",
"umi": "^2.10.0",
"umi-plugin-react": "^1.12.0"
"prettier": "^2.0.0",
"stylelint": "^13.2.0",
"stylelint-config-prettier": "^8.0.0",
"stylelint-config-standard": "^20.0.0",
"typescript": "^3.8.3",
"umi": "^3.2.0"
},
"engines": {
"node": ">= 10.0.0"
},
"lint-staged": {
"src/**/*.js": [
@@ -92,13 +93,14 @@
"format": "minimal",
"extractBabelOptions": {
"presets": [
"umi/babel"
"@umijs/babel-preset-umi"
]
}
},
"scripts": {
"analyze": "cross-env ANALYZE=1 umi build",
"build": "umi build",
"check:model": "umi dva list model",
"lint:js": "eslint --ext .js src",
"lint:style": "stylelint \"src/**/*.less\" --syntax less",
"start": "umi dev",
+4 -3
View File
@@ -1,6 +1,7 @@
import React from 'react'
import PropTypes from 'prop-types'
import { Dropdown, Button, Icon, Menu } from 'antd'
import { BarsOutlined, DownOutlined } from '@ant-design/icons'
import { Dropdown, Button, Menu } from 'antd'
const DropOption = ({
onMenuClick,
@@ -17,8 +18,8 @@ const DropOption = ({
{...dropdownProps}
>
<Button style={{ border: 'none', ...buttonStyle }}>
<Icon style={{ marginRight: 2 }} type="bars" />
<Icon type="down" />
<BarsOutlined style={{ marginRight: 2 }} />
<DownOutlined />
</Button>
</Dropdown>
)
+21
View File
@@ -0,0 +1,21 @@
import React from 'react';
import { TooltipProps } from 'antd/lib/tooltip';
export interface EllipsisTooltipProps extends TooltipProps {
title?: undefined;
overlayStyle?: undefined;
}
export interface EllipsisProps {
tooltip?: boolean | EllipsisTooltipProps;
length?: number;
lines?: number;
style?: React.CSSProperties;
className?: string;
fullWidthRecognition?: boolean;
}
export function getStrFullLength(str: string): number;
export function cutStrByFullLength(str: string, maxLength: number): string;
export default class Ellipsis extends React.Component<EllipsisProps, any> {}
+270
View File
@@ -0,0 +1,270 @@
import React, { Component } from 'react';
import { Tooltip } from 'antd';
import classNames from 'classnames';
import styles from './index.less';
/* eslint react/no-did-mount-set-state: 0 */
/* eslint no-param-reassign: 0 */
const isSupportLineClamp = document.body.style.webkitLineClamp !== undefined;
const TooltipOverlayStyle = {
overflowWrap: 'break-word',
wordWrap: 'break-word',
};
export const getStrFullLength = (str = '') =>
str.split('').reduce((pre, cur) => {
const charCode = cur.charCodeAt(0);
if (charCode >= 0 && charCode <= 128) {
return pre + 1;
}
return pre + 2;
}, 0);
export const cutStrByFullLength = (str = '', maxLength) => {
let showLength = 0;
return str.split('').reduce((pre, cur) => {
const charCode = cur.charCodeAt(0);
if (charCode >= 0 && charCode <= 128) {
showLength += 1;
} else {
showLength += 2;
}
if (showLength <= maxLength) {
return pre + cur;
}
return pre;
}, '');
};
const getTooltip = ({ tooltip, overlayStyle, title, children }) => {
if (tooltip) {
const props = tooltip === true ? { overlayStyle, title } : { ...tooltip, overlayStyle, title };
return <Tooltip {...props}>{children}</Tooltip>;
}
return children;
};
const EllipsisText = ({ text, length, tooltip, fullWidthRecognition, ...other }) => {
if (typeof text !== 'string') {
throw new Error('Ellipsis children must be string.');
}
const textLength = fullWidthRecognition ? getStrFullLength(text) : text.length;
if (textLength <= length || length < 0) {
return <span {...other}>{text}</span>;
}
const tail = '...';
let displayText;
if (length - tail.length <= 0) {
displayText = '';
} else {
displayText = fullWidthRecognition ? cutStrByFullLength(text, length) : text.slice(0, length);
}
const spanAttrs = tooltip ? {} : { ...other };
return getTooltip({
tooltip,
overlayStyle: TooltipOverlayStyle,
title: text,
children: (
<span {...spanAttrs}>
{displayText}
{tail}
</span>
),
});
};
export default class Ellipsis extends Component {
state = {
text: '',
targetCount: 0,
};
componentDidMount() {
if (this.node) {
this.computeLine();
}
}
componentDidUpdate(perProps) {
const { lines } = this.props;
if (lines !== perProps.lines) {
this.computeLine();
}
}
computeLine = () => {
const { lines } = this.props;
if (lines && !isSupportLineClamp) {
const text = this.shadowChildren.innerText || this.shadowChildren.textContent;
const lineHeight = parseInt(getComputedStyle(this.root).lineHeight, 10);
const targetHeight = lines * lineHeight;
this.content.style.height = `${targetHeight}px`;
const totalHeight = this.shadowChildren.offsetHeight;
const shadowNode = this.shadow.firstChild;
if (totalHeight <= targetHeight) {
this.setState({
text,
targetCount: text.length,
});
return;
}
// bisection
const len = text.length;
const mid = Math.ceil(len / 2);
const count = this.bisection(targetHeight, mid, 0, len, text, shadowNode);
this.setState({
text,
targetCount: count,
});
}
};
bisection = (th, m, b, e, text, shadowNode) => {
const suffix = '...';
let mid = m;
let end = e;
let begin = b;
shadowNode.innerHTML = text.substring(0, mid) + suffix;
let sh = shadowNode.offsetHeight;
if (sh <= th) {
shadowNode.innerHTML = text.substring(0, mid + 1) + suffix;
sh = shadowNode.offsetHeight;
if (sh > th || mid === begin) {
return mid;
}
begin = mid;
if (end - begin === 1) {
mid = 1 + begin;
} else {
mid = Math.floor((end - begin) / 2) + begin;
}
return this.bisection(th, mid, begin, end, text, shadowNode);
}
if (mid - 1 < 0) {
return mid;
}
shadowNode.innerHTML = text.substring(0, mid - 1) + suffix;
sh = shadowNode.offsetHeight;
if (sh <= th) {
return mid - 1;
}
end = mid;
mid = Math.floor((end - begin) / 2) + begin;
return this.bisection(th, mid, begin, end, text, shadowNode);
};
handleRoot = n => {
this.root = n;
};
handleContent = n => {
this.content = n;
};
handleNode = n => {
this.node = n;
};
handleShadow = n => {
this.shadow = n;
};
handleShadowChildren = n => {
this.shadowChildren = n;
};
render() {
const { text, targetCount } = this.state;
const {
children,
lines,
length,
className,
tooltip,
fullWidthRecognition,
...restProps
} = this.props;
const cls = classNames(styles.ellipsis, className, {
[styles.lines]: lines && !isSupportLineClamp,
[styles.lineClamp]: lines && isSupportLineClamp,
});
if (!lines && !length) {
return (
<span className={cls} {...restProps}>
{children}
</span>
);
}
// length
if (!lines) {
return (
<EllipsisText
className={cls}
length={length}
text={children || ''}
tooltip={tooltip}
fullWidthRecognition={fullWidthRecognition}
{...restProps}
/>
);
}
const id = `antd-pro-ellipsis-${`${new Date().getTime()}${Math.floor(Math.random() * 100)}`}`;
// support document.body.style.webkitLineClamp
if (isSupportLineClamp) {
const style = `#${id}{-webkit-line-clamp:${lines};-webkit-box-orient: vertical;}`;
const node = (
<div id={id} className={cls} {...restProps}>
<style>{style}</style>
{children}
</div>
);
return getTooltip({
tooltip,
overlayStyle: TooltipOverlayStyle,
title: children,
children: node,
});
}
const childNode = (
<span ref={this.handleNode}>
{targetCount > 0 && text.substring(0, targetCount)}
{targetCount > 0 && targetCount < text.length && '...'}
</span>
);
return (
<div {...restProps} ref={this.handleRoot} className={cls}>
<div ref={this.handleContent}>
{getTooltip({
tooltip,
overlayStyle: TooltipOverlayStyle,
title: text,
children: childNode,
})}
<div className={styles.shadow} ref={this.handleShadowChildren}>
{children}
</div>
<div className={styles.shadow} ref={this.handleShadow}>
<span>{text}</span>
</div>
</div>
</div>
);
}
}
+24
View File
@@ -0,0 +1,24 @@
.ellipsis {
display: inline-block;
width: 100%;
overflow: hidden;
word-break: break-all;
}
.lines {
position: relative;
.shadow {
position: absolute;
z-index: -999;
display: block;
color: transparent;
opacity: 0;
}
}
.lineClamp {
position: relative;
display: -webkit-box;
overflow: hidden;
text-overflow: ellipsis;
}
+17
View File
@@ -0,0 +1,17 @@
---
title: Ellipsis
subtitle: 文本自动省略号
cols: 1
order: 10
---
文本过长自动处理省略号,支持按照文本长度和最大行数两种方式截取。
## API
| 参数 | 说明 | 类型 | 默认值 |
| -------------------- | ------------------------------------------------ | ------- | ------ |
| tooltip | 移动到文本展示完整内容的提示 | boolean | - |
| length | 在按照长度截取下的文本最大字符数,超过则截取省略 | number | - |
| lines | 在按照行数截取下最大的行数,超过则截取省略 | number | `1` |
| fullWidthRecognition | 是否将全角字符的长度视为 2 来计算字符串长度 | boolean | - |
+13
View File
@@ -0,0 +1,13 @@
import { getStrFullLength, cutStrByFullLength } from './index';
describe('test calculateShowLength', () => {
it('get full length', () => {
expect(getStrFullLength('一二,a,')).toEqual(8);
});
it('cut str by full length', () => {
expect(cutStrByFullLength('一二,a,', 7)).toEqual('一二,a');
});
it('cut str when length small', () => {
expect(cutStrByFullLength('一22三', 5)).toEqual('一22');
});
});
+14
View File
@@ -0,0 +1,14 @@
import React from 'react';
export interface GlobalFooterProps {
links?: Array<{
key?: string;
title: React.ReactNode;
href: string;
blankTarget?: boolean;
}>;
copyright?: React.ReactNode;
style?: React.CSSProperties;
className?: string;
}
export default class GlobalFooter extends React.Component<GlobalFooterProps, any> {}
+28
View File
@@ -0,0 +1,28 @@
import React from 'react';
import classNames from 'classnames';
import styles from './index.less';
const GlobalFooter = ({ className, links, copyright }) => {
const clsString = classNames(styles.globalFooter, className);
return (
<footer className={clsString}>
{links && (
<div className={styles.links}>
{links.map(link => (
<a
key={link.key}
title={link.key}
target={link.blankTarget ? '_blank' : '_self'}
href={link.href}
>
{link.title}
</a>
))}
</div>
)}
{copyright && <div className={styles.copyright}>{copyright}</div>}
</footer>
);
};
export default GlobalFooter;
+29
View File
@@ -0,0 +1,29 @@
@import '~antd/lib/style/themes/default.less';
.globalFooter {
margin: 48px 0 24px 0;
padding: 0 16px;
text-align: center;
.links {
margin-bottom: 8px;
a {
color: @text-color-secondary;
transition: all 0.3s;
&:not(:last-child) {
margin-right: 40px;
}
&:hover {
color: @text-color;
}
}
}
.copyright {
color: @text-color-secondary;
font-size: @font-size-base;
}
}
+15
View File
@@ -0,0 +1,15 @@
---
title: GlobalFooter
subtitle: 全局页脚
cols: 1
order: 7
---
页脚属于全局导航的一部分,作为对顶部导航的补充,通过传递数据控制展示内容。
## API
| 参数 | 说明 | 类型 | 默认值 |
| --------- | -------- | ---------------------------------------------------------------- | ------ |
| links | 链接数据 | array<{ title: ReactNode, href: string, blankTarget?: boolean }> | - |
| copyright | 版权信息 | ReactNode | - |
+11 -8
View File
@@ -1,20 +1,23 @@
import React, { PureComponent, Fragment } from 'react'
import PropTypes from 'prop-types'
import { Breadcrumb, Icon } from 'antd'
import Link from 'umi/navlink'
import withRouter from 'umi/withRouter'
import { Breadcrumb } from 'antd'
import { Link, withRouter } from 'umi'
import { withI18n } from '@lingui/react'
import { pathMatchRegexp, queryAncestors, addLangPrefix } from 'utils'
import iconMap from 'utils/iconMap'
const { pathToRegexp } = require('path-to-regexp')
import { queryAncestors } from 'utils'
import styles from './Bread.less'
@withI18n()
@withRouter
class Bread extends PureComponent {
generateBreadcrumbs = paths => {
generateBreadcrumbs = (paths) => {
return paths.map((item, key) => {
const content = item && (
<Fragment>
{item.icon && <Icon type={item.icon} style={{ marginRight: 4 }} />}
{item.icon && (
<span style={{ marginRight: 4 }}>{iconMap[item.icon]}</span>
)}
{item.name}
</Fragment>
)
@@ -23,7 +26,7 @@ class Bread extends PureComponent {
item && (
<Breadcrumb.Item key={key}>
{paths.length - 1 !== key ? (
<Link to={addLangPrefix(item.route) || '#'}>{content}</Link>
<Link to={item.route || '#'}>{content}</Link>
) : (
content
)}
@@ -37,7 +40,7 @@ class Bread extends PureComponent {
// Find a route that matches the pathname.
const currentRoute = routeList.find(
_ => _.route && pathMatchRegexp(_.route, location.pathname)
(_) => _.route && pathToRegexp(_.route).exec(location.pathname)
)
// Find the breadcrumb navigation of the current route match and all its ancestors.
+11 -15
View File
@@ -1,7 +1,13 @@
import React, { PureComponent, Fragment } from 'react'
import PropTypes from 'prop-types'
import { Menu, Icon, Layout, Avatar, Popover, Badge, List } from 'antd'
import { Ellipsis } from 'ant-design-pro'
import { Menu, Layout, Avatar, Popover, Badge, List } from 'antd'
import { Ellipsis } from 'components'
import {
BellOutlined,
RightOutlined,
MenuFoldOutlined,
MenuUnfoldOutlined,
} from '@ant-design/icons'
import { Trans, withI18n } from '@lingui/react'
import { setLocale } from 'utils'
import moment from 'moment'
@@ -104,11 +110,7 @@ class Header extends PureComponent {
}
description={moment(item.date).fromNow()}
/>
<Icon
style={{ fontSize: 10, color: '#ccc' }}
type="right"
theme="outlined"
/>
<RightOutlined style={{ fontSize: 10, color: '#ccc' }} />
</List.Item>
)}
/>
@@ -129,7 +131,7 @@ class Header extends PureComponent {
offset={[-10, 10]}
className={styles.iconButton}
>
<Icon className={styles.iconFont} type="bell" />
<BellOutlined className={styles.iconFont} />
</Badge>
</Popover>
)
@@ -146,14 +148,8 @@ class Header extends PureComponent {
className={styles.button}
onClick={onCollapseChange.bind(this, !collapsed)}
>
<Icon
type={classnames({
'menu-unfold': collapsed,
'menu-fold': !collapsed,
})}
/>
{collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
</div>
<div className={styles.rightContainer}>{rightContent}</div>
</Layout.Header>
)
+10 -14
View File
@@ -1,14 +1,10 @@
import React, { PureComponent, Fragment } from 'react'
import PropTypes from 'prop-types'
import { Menu, Icon } from 'antd'
import Navlink from 'umi/navlink'
import withRouter from 'umi/withRouter'
import {
arrayToTree,
queryAncestors,
pathMatchRegexp,
addLangPrefix,
} from 'utils'
import { Menu } from 'antd'
import { NavLink, withRouter } from 'umi'
import { pathToRegexp } from 'path-to-regexp'
import { arrayToTree, queryAncestors } from 'utils'
import iconMap from 'utils/iconMap'
import store from 'store'
const { SubMenu } = Menu
@@ -46,7 +42,7 @@ class SiderMenu extends PureComponent {
key={item.id}
title={
<Fragment>
{item.icon && <Icon type={item.icon} />}
{item.icon && iconMap[item.icon]}
<span>{item.name}</span>
</Fragment>
}
@@ -57,10 +53,10 @@ class SiderMenu extends PureComponent {
}
return (
<Menu.Item key={item.id}>
<Navlink to={addLangPrefix(item.route) || '#'}>
{item.icon && <Icon type={item.icon} />}
<NavLink to={item.route || '#'}>
{item.icon && iconMap[item.icon]}
<span>{item.name}</span>
</Navlink>
</NavLink>
</Menu.Item>
)
})
@@ -81,7 +77,7 @@ class SiderMenu extends PureComponent {
// Find a menu that matches the pathname.
const currentMenu = menus.find(
_ => _.route && pathMatchRegexp(_.route, location.pathname)
_ => _.route && pathToRegexp(_.route).exec(location.pathname)
)
// Find the key that should be selected according to the current menu.
+3 -2
View File
@@ -1,7 +1,8 @@
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { Icon, Switch, Layout } from 'antd'
import { Switch, Layout } from 'antd'
import { withI18n, Trans } from '@lingui/react'
import { BulbOutlined } from '@ant-design/icons'
import ScrollBar from '../ScrollBar'
import { config } from 'utils'
import SiderMenu from './Menu'
@@ -57,7 +58,7 @@ class Sider extends PureComponent {
{!collapsed && (
<div className={styles.switchTheme}>
<span>
<Icon type="bulb" />
<BulbOutlined />
<Trans>Switch Theme</Trans>
</span>
<Switch
+3 -1
View File
@@ -3,7 +3,9 @@ import FilterItem from './FilterItem'
import DropOption from './DropOption'
import Loader from './Loader'
import ScrollBar from './ScrollBar'
import GlobalFooter from './GlobalFooter'
import Ellipsis from './Ellipsis'
import * as MyLayout from './Layout/index.js'
import Page from './Page'
export { MyLayout, Editor, FilterItem, DropOption, Loader, Page, ScrollBar }
export { MyLayout, Editor, GlobalFooter, Ellipsis, FilterItem, DropOption, Loader, Page, ScrollBar }
+2 -2
View File
@@ -1,12 +1,12 @@
import React, { PureComponent, Fragment } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'dva'
import { connect } from 'umi'
import { Helmet } from 'react-helmet'
import { Loader } from 'components'
import { queryLayout } from 'utils'
import NProgress from 'nprogress'
import config from 'utils/config'
import withRouter from 'umi/withRouter'
import { withRouter } from 'umi'
import PublicLayout from './PublicLayout'
import PrimaryLayout from './PrimaryLayout'
+7 -7
View File
@@ -2,13 +2,13 @@
/* global document */
import React, { PureComponent, Fragment } from 'react'
import PropTypes from 'prop-types'
import withRouter from 'umi/withRouter'
import { connect } from 'dva'
import { MyLayout } from 'components'
import { withRouter } from 'umi'
import { connect } from 'umi'
import { MyLayout, GlobalFooter } from 'components'
import { BackTop, Layout, Drawer } from 'antd'
import { GlobalFooter } from 'ant-design-pro'
import { enquireScreen, unenquireScreen } from 'enquire-js'
import { config, pathMatchRegexp, langFromPath } from 'utils'
const { pathToRegexp } = require("path-to-regexp")
import { config, getLocale } from 'utils'
import Error from '../pages/404'
import styles from './PrimaryLayout.less'
import store from 'store'
@@ -56,7 +56,7 @@ class PrimaryLayout extends PureComponent {
// Localized route name.
const lang = langFromPath(location.pathname)
const lang = getLocale()
const newRouteList =
lang !== 'en'
? routeList.map(item => {
@@ -70,7 +70,7 @@ class PrimaryLayout extends PureComponent {
// Find a route that matches the pathname.
const currentRoute = newRouteList.find(
_ => _.route && pathMatchRegexp(_.route, location.pathname)
_ => _.route && pathToRegexp(_.route).exec(location.pathname)
)
// Query whether you have permission to enter this page
+11 -9
View File
@@ -1,8 +1,9 @@
import React, { Component } from 'react'
import withRouter from 'umi/withRouter'
import { LocaleProvider } from 'antd'
import { withRouter } from 'umi'
import { ConfigProvider } from 'antd'
import { I18nProvider } from '@lingui/react'
import { langFromPath, defaultLanguage } from 'utils'
import { getLocale } from 'utils'
const { i18n } = require('../../src/utils/config')
import zh_CN from 'antd/lib/locale-provider/zh_CN'
import en_US from 'antd/lib/locale-provider/en_US'
import pt_BR from 'antd/lib/locale-provider/pt_BR'
@@ -14,6 +15,7 @@ const languages = {
en: en_US,
'pt-br': pt_BR,
}
const { defaultLanguage } = i18n
@withRouter
class Layout extends Component {
@@ -24,13 +26,13 @@ class Layout extends Component {
language = defaultLanguage
componentDidMount() {
const language = langFromPath(this.props.location.pathname)
const language = getLocale()
this.language = language
language && this.loadCatalog(language)
}
shouldComponentUpdate(nextProps, nextState) {
const language = langFromPath(nextProps.location.pathname)
const language = getLocale()
const preLanguage = this.language
const { catalogs } = nextState
@@ -59,19 +61,19 @@ class Layout extends Component {
}
render() {
const { location, children } = this.props
const { children } = this.props
const { catalogs } = this.state
let language = langFromPath(location.pathname)
let language = getLocale()
// If the language pack is not loaded or is loading, use the default language
if (!catalogs[language]) language = defaultLanguage
return (
<LocaleProvider locale={languages[language]}>
<ConfigProvider locale={languages[language]}>
<I18nProvider language={language} catalogs={catalogs}>
<BaseLayout>{children}</BaseLayout>
</I18nProvider>
</LocaleProvider>
</ConfigProvider>
)
}
}
+6 -5
View File
@@ -1,10 +1,11 @@
/* global window */
import { router } from 'utils'
import { history } from 'umi'
import { stringify } from 'qs'
import store from 'store'
const { pathToRegexp } = require("path-to-regexp")
import { ROLE_TYPE } from 'utils/constant'
import { queryLayout, pathMatchRegexp } from 'utils'
import { queryLayout } from 'utils'
import { CANCEL_REQUEST_MESSAGE } from 'utils/constant'
import api from 'api'
import config from 'config'
@@ -12,8 +13,8 @@ import config from 'config'
const { queryRouteList, logoutUser, queryUserInfo } = api
const goDashboard = () => {
if (pathMatchRegexp(['/', '/login'], window.location.pathname)) {
router.push({
if (pathToRegexp(['/', '/login']).exec(window.location.pathname)) {
history.push({
pathname: '/dashboard',
})
}
@@ -112,7 +113,7 @@ export default {
store.set('isInit', true)
goDashboard()
} else if (queryLayout(config.layouts, locationPathname) !== 'public') {
router.push({
history.push({
pathname: '/login',
search: stringify({
from: locationPathname,
+2 -2
View File
@@ -1,12 +1,12 @@
import React from 'react'
import { Icon } from 'antd'
import { FrownOutlined } from '@ant-design/icons'
import { Page } from 'components'
import styles from './404.less'
const Error = () => (
<Page inner>
<div className={styles.error}>
<Icon type="frown-o" />
<FrownOutlined />
<h1>404 Not Found</h1>
</div>
</Page>
-27
View File
@@ -1,27 +0,0 @@
import React from 'react'
import PropTypes from 'prop-types'
import { ResponsiveContainer } from 'recharts'
import styles from './Container.less'
const Container = ({
children,
ratio = 5 / 2,
minHeight = 250,
maxHeight = 350,
}) => (
<div className={styles.container} style={{ minHeight, maxHeight }}>
<div style={{ marginTop: `${100 / ratio}%` || '100%' }} />
<div className={styles.content} style={{ minHeight, maxHeight }}>
<ResponsiveContainer>{children}</ResponsiveContainer>
</div>
</div>
)
Container.propTypes = {
children: PropTypes.element.isRequired,
ratio: PropTypes.number,
minHeight: PropTypes.number,
maxHeight: PropTypes.number,
}
export default Container
-20
View File
@@ -1,20 +0,0 @@
.container {
width: 100%;
position: relative;
display: inline-block;
:global {
.recharts-responsive-container {
width: e('calc(100% + 56px)') !important;
margin-left: -32px;
}
}
}
.content {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
+1 -1
View File
@@ -1,6 +1,6 @@
import React from 'react'
import AdSense from 'react-adsense'
import { Link } from 'react-router'
import { Link } from 'umi'
import DynamicChartComponent from './DynamicChartComponent.js'
const MainPageComponent = () => {
+1 -1
View File
@@ -38,7 +38,7 @@ function Browser({ data }) {
pagination={false}
showHeader={false}
columns={columns}
rowKey={(record, key) => key}
rowKey='name'
dataSource={data}
/>
)
+1 -1
View File
@@ -54,7 +54,7 @@ function Comments({ data }) {
pagination={false}
showHeader={false}
columns={columns}
rowKey={(record, key) => key}
rowKey='avatar'
dataSource={data.filter((item, key) => key < 3)}
/>
</div>
+6 -2
View File
@@ -1,9 +1,11 @@
import React from 'react'
import PropTypes from 'prop-types'
import { Icon, Card } from 'antd'
import { Card } from 'antd'
import CountUp from 'react-countup'
import iconMap from 'utils/iconMap'
import styles from './numberCard.less'
function NumberCard({ icon, color, title, number, countUp }) {
return (
<Card
@@ -11,7 +13,9 @@ function NumberCard({ icon, color, title, number, countUp }) {
bordered={false}
bodyStyle={{ padding: 10 }}
>
<Icon className={styles.iconWarp} style={{ color }} type={icon} />
<span className={styles.iconWarp} style={{ color }}>
{iconMap[icon]}
</span>
<div className={styles.content}>
<p className={styles.title}>{title || 'No Title'}</p>
<p className={styles.number}>
@@ -53,7 +53,7 @@ function RecentSales({ data }) {
<Table
pagination={false}
columns={columns}
rowKey={(record, key) => key}
rowKey='id'
dataSource={data.filter((item, key) => key < 5)}
/>
</div>
+1 -1
View File
@@ -1,6 +1,6 @@
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'dva'
import { connect } from 'umi'
import { Row, Col, Card } from 'antd'
import { Color } from 'utils'
import { Page, ScrollBar } from 'components'
+8 -9
View File
@@ -1,10 +1,11 @@
import { parse } from 'qs'
import modelExtend from 'dva-model-extend'
import api from 'api'
import { pathMatchRegexp } from 'utils'
const { pathToRegexp } = require("path-to-regexp")
import { model } from 'utils/model'
const { queryDashboard, queryWeather } = api
const avatar = '//cdn.antd-admin.zuiidea.com/bc442cf0cc6f7940dcc567e465048d1a8d634493198c4-sPx5BR_fw236.jpeg'
export default modelExtend(model, {
namespace: 'dashboard',
@@ -13,12 +14,11 @@ export default modelExtend(model, {
city: '深圳',
temperature: '30',
name: '晴',
icon: '//s5.sencdn.com/web/icons/3d_50/2.png',
icon: '//cdn.antd-admin.zuiidea.com/sun.png',
},
sales: [],
quote: {
avatar:
'http://img.hb.aicdn.com/bc442cf0cc6f7940dcc567e465048d1a8d634493198c4-sPx5BR_fw236',
avatar,
},
numbers: [],
recentSales: [],
@@ -27,16 +27,15 @@ export default modelExtend(model, {
browser: [],
cpu: {},
user: {
avatar:
'http://img.hb.aicdn.com/bc442cf0cc6f7940dcc567e465048d1a8d634493198c4-sPx5BR_fw236',
avatar,
},
},
subscriptions: {
setup({ dispatch, history }) {
history.listen(({ pathname }) => {
if (
pathMatchRegexp('/dashboard', pathname) ||
pathMatchRegexp('/', pathname)
pathToRegexp('/dashboard').exec(pathname) ||
pathToRegexp('/').exec(pathname)
) {
dispatch({ type: 'query' })
dispatch({ type: 'queryWeather' })
@@ -62,7 +61,7 @@ export default modelExtend(model, {
city: data.location.name,
temperature: data.now.temperature,
name: data.now.text,
icon: `//s5.sencdn.com/web/icons/3d_50/${data.now.code}.png`,
icon: `//cdn.antd-admin.zuiidea.com/web/icons/3d_50/${data.now.code}.png`,
}
yield put({
type: 'updateState',
@@ -1,11 +1,11 @@
import React from 'react'
import { Editor } from 'components'
import { Component } from 'react'
import { Editor, Page } from 'components'
import { convertToRaw } from 'draft-js'
import { Row, Col, Card } from 'antd'
import draftToHtml from 'draftjs-to-html'
import draftToMarkdown from 'draftjs-to-markdown'
export default class EditorPage extends React.Component {
export default class EditorPage extends Component {
constructor(props) {
super(props)
this.state = {
@@ -26,17 +26,18 @@ export default class EditorPage extends React.Component {
md: 24,
style: {
marginBottom: 32,
},
}
}
const textareaStyle = {
minHeight: 496,
width: '100%',
background: '#f7f7f7',
borderColor: '#F1F1F1',
padding: '16px 8px',
padding: '16px 8px'
}
return (
<div className="content-inner">
<Page inner>
<Row gutter={32}>
<Col {...colProps}>
<Card title="Editor" style={{ overflow: 'visible' }}>
@@ -98,7 +99,7 @@ export default class EditorPage extends React.Component {
</Card>
</Col>
</Row>
</div>
</Page>
)
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
import React, { PureComponent } from 'react'
import Redirect from 'umi/redirect'
import { Redirect } from 'umi'
import { withI18n } from '@lingui/react'
@withI18n()
+22 -43
View File
@@ -1,38 +1,31 @@
import React, { PureComponent, Fragment } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'dva'
import { Button, Row, Form, Icon, Input } from 'antd'
import { GlobalFooter } from 'ant-design-pro'
import { connect } from 'umi'
import { Button, Row, Input, Form } from 'antd'
import { GlobalFooter } from 'components'
import { GithubOutlined } from '@ant-design/icons'
import { Trans, withI18n } from '@lingui/react'
import { setLocale } from 'utils'
import config from 'utils/config'
import styles from './index.less'
const FormItem = Form.Item
@withI18n()
@connect(({ loading }) => ({ loading }))
@Form.create()
@connect(({ loading, dispatch }) => ({ loading, dispatch }))
class Login extends PureComponent {
handleOk = () => {
const { dispatch, form } = this.props
const { validateFieldsAndScroll } = form
validateFieldsAndScroll((errors, values) => {
if (errors) {
return
}
dispatch({ type: 'login/login', payload: values })
})
}
render() {
const { loading, form, i18n } = this.props
const { getFieldDecorator } = form
const { dispatch, loading, i18n } = this.props
const handleOk = values => {
dispatch({ type: 'login/login', payload: values })
}
let footerLinks = [
{
key: 'github',
title: <Icon type="github" />,
title: <GithubOutlined />,
href: 'https://github.com/zuiidea/antd-admin',
blankTarget: true,
},
@@ -56,46 +49,32 @@ class Login extends PureComponent {
<img alt="logo" src={config.logoPath} />
<span>{config.siteName}</span>
</div>
<form>
<FormItem hasFeedback>
{getFieldDecorator('username', {
rules: [
{
required: true,
},
],
})(
<Form
onFinish={handleOk}
>
<FormItem name="username"
rules={[{ required: true }]} hasFeedback>
<Input
onPressEnter={this.handleOk}
placeholder={i18n.t`Username`}
/>
)}
</FormItem>
<FormItem hasFeedback>
{getFieldDecorator('password', {
rules: [
{
required: true,
},
],
})(
<FormItem name="password"
rules={[{ required: true }]} hasFeedback>
<Input
type="password"
onPressEnter={this.handleOk}
placeholder={i18n.t`Password`}
/>
)}
</FormItem>
<Row>
<Button
type="primary"
onClick={this.handleOk}
htmlType="submit"
loading={loading.effects.login}
>
<Trans>Sign in</Trans>
</Button>
<p>
<span>
<span className="margin-right">
<Trans>Username</Trans>
:guest
</span>
@@ -105,7 +84,7 @@ class Login extends PureComponent {
</span>
</p>
</Row>
</form>
</Form>
</div>
<div className={styles.footer}>
<GlobalFooter links={footerLinks} copyright={config.copyright} />
+14 -6
View File
@@ -1,4 +1,5 @@
import { router, pathMatchRegexp } from 'utils'
import { history } from 'umi'
const { pathToRegexp } = require("path-to-regexp")
import api from 'api'
const { loginUser } = api
@@ -7,7 +8,14 @@ export default {
namespace: 'login',
state: {},
// subscriptions: {
// setup({ dispatch, history }) {
// history.listen(location => {
// if (pathToRegexp('/login').exec(location.pathname)) {
// }
// })
// },
// },
effects: {
*login({ payload }, { put, call, select }) {
const data = yield call(loginUser, payload)
@@ -15,11 +23,11 @@ export default {
if (data.success) {
const { from } = locationQuery
yield put({ type: 'app/query' })
if (!pathMatchRegexp('/login', from)) {
if (['', '/'].includes(from)) router.push('/dashboard')
else router.push(from)
if (!pathToRegexp('/login').exec(from)) {
if (['', '/'].includes(from)) history.push('/dashboard')
else history.push(from)
} else {
router.push('/dashboard')
history.push('/dashboard')
}
} else {
throw data
+1 -1
View File
@@ -1,7 +1,7 @@
import React, { PureComponent } from 'react'
import { Table, Avatar } from 'antd'
import { withI18n } from '@lingui/react'
import { Ellipsis } from 'ant-design-pro'
import { Ellipsis } from 'components'
import styles from './List.less'
@withI18n()
+4 -4
View File
@@ -1,8 +1,8 @@
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'dva'
import { connect } from 'umi'
import { Tabs } from 'antd'
import { router } from 'utils'
import { history } from 'umi'
import { stringify } from 'qs'
import { withI18n } from '@lingui/react'
import { Page } from 'components'
@@ -21,7 +21,7 @@ class Post extends PureComponent {
handleTabClick = key => {
const { pathname } = this.props.location
router.push({
history.push({
pathname,
search: stringify({
status: key,
@@ -39,7 +39,7 @@ class Post extends PureComponent {
dataSource: list,
loading: loading.effects['post/query'],
onChange(page) {
router.push({
history.push({
pathname,
search: stringify({
...query,
+2 -2
View File
@@ -1,6 +1,6 @@
import modelExtend from 'dva-model-extend'
import api from 'api'
import { pathMatchRegexp } from 'utils'
const { pathToRegexp } = require("path-to-regexp")
import { pageModel } from 'utils/model'
const { queryPostList } = api
@@ -11,7 +11,7 @@ export default modelExtend(pageModel, {
subscriptions: {
setup({ dispatch, history }) {
history.listen(location => {
if (pathMatchRegexp('/post', location.pathname)) {
if (pathToRegexp('/post').exec(location.pathname)) {
dispatch({
type: 'query',
payload: {
+73 -69
View File
@@ -1,19 +1,9 @@
import React from 'react'
import { request } from 'utils'
import { apiPrefix } from 'utils/config'
import {
Row,
Col,
Select,
Input,
Button,
List,
Tag,
Form,
Icon,
Checkbox,
} from 'antd'
import { Row, Col, Select, Form, Input, Button, List, Tag, Checkbox } from 'antd'
import classnames from 'classnames'
import { CloseOutlined } from '@ant-design/icons'
import { Trans } from '@lingui/react'
import api from '@/services/api'
import { Page } from 'components'
@@ -46,8 +36,8 @@ const requests = Object.values(api).map(item => {
})
let uuid = 2
@Form.create()
class RequestPage extends React.Component {
formRef = React.createRef()
constructor(props) {
super(props)
this.state = {
@@ -62,15 +52,17 @@ class RequestPage extends React.Component {
handleRequest = () => {
const { method, url } = this.state
this.props.form.validateFields((err, values) => {
if (!err) {
this.formRef.current.validateFields()
.then(values => {
// values: { check[1]: true, key[1]: 'username', value[1]: 'admin' }
const params = {}
if (values.key) {
values.key.forEach((item, index) => {
if (item && values.check[index]) {
params[item] = values.value[index]
}
})
for (let i in values) {
if (i.startsWith('check')) {
const index = i.match(/check\[(\d+)\]/)[1]
const key = values[`key[${index}]`]
params[key] = values[`value[${index}]`]
}
}
request({ method, url, data: params }).then(data => {
@@ -78,8 +70,23 @@ class RequestPage extends React.Component {
result: JSON.stringify(data),
})
})
}
})
})
.catch(errorInfo => {
console.log(errorInfo)
/*
errorInfo:
{
values: {
username: 'username',
password: 'password',
},
errorFields: [
{ password: ['username'], errors: ['Please input your Password!'] },
],
outOfDate: false,
}
*/
})
}
handleClickListItem = ({ method, url }) => {
@@ -127,7 +134,6 @@ class RequestPage extends React.Component {
render() {
const { result, url, method, keys, visible } = this.state
const { getFieldDecorator } = this.props.form
return (
<Page inner>
@@ -196,53 +202,51 @@ class RequestPage extends React.Component {
<Trans>Send</Trans>
</Button>
</Row>
<Form ref={this.formRef} name="control-ref" >
<div
className={classnames(styles.paramsBlock, {
[styles.hideParams]: !visible,
})}
>
{keys.map((key, index) => (
<Row
gutter={8}
type="flex"
justify="start"
align="middle"
key={key}
>
<Col style={{ marginTop: 8 }}>
<Form.Item name={`check[${key}]`} valuePropName="checked">
<Checkbox defaultChecked />
</Form.Item>
</Col>
<Col style={{ marginTop: 8 }}>
<Form.Item name={`key[${key}]`}>
<Input placeholder="Key" />
</Form.Item>
</Col>
<Col style={{ marginTop: 8 }}>
<Form.Item name={`value[${key}]`}>
<Input placeholder="Value" />
</Form.Item>
</Col>
<Col style={{ marginTop: 8 }}>
<CloseOutlined
onClick={this.handleRemoveField.bind(this, key)}
style={{ cursor: 'pointer' }}
/>
</Col>
</Row>
))}
<div
className={classnames(styles.paramsBlock, {
[styles.hideParams]: !visible,
})}
>
{keys.map((key, index) => (
<Row
gutter={8}
type="flex"
justify="start"
align="middle"
key={key}
>
<Col style={{ marginTop: 8 }}>
{getFieldDecorator(`check[${key}]`, {
initialValue: true,
})(<Checkbox defaultChecked />)}
</Col>
<Col style={{ marginTop: 8 }}>
{getFieldDecorator(`key[${key}]`)(
<Input placeholder="Key" />
)}
</Col>
<Col style={{ marginTop: 8 }}>
{getFieldDecorator(`value[${key}]`)(
<Input placeholder="Value" />
)}
</Col>
<Col style={{ marginTop: 8 }}>
<Icon
onClick={this.handleRemoveField.bind(this, key)}
style={{ cursor: 'pointer' }}
type="close"
theme="outlined"
/>
</Col>
<Row style={{ marginTop: 8 }}>
<Button onClick={this.handleAddField}>
<Trans>Add Param</Trans>
</Button>
</Row>
))}
<Row style={{ marginTop: 8 }}>
<Button onClick={this.handleAddField}>
<Trans>Add Param</Trans>
</Button>
</Row>
</div>
</div>
</Form>
<div className={styles.result}>{result}</div>
</Col>
</Row>
@@ -1,6 +1,6 @@
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'dva'
import { connect } from 'umi'
import { Page } from 'components'
import styles from './index.less'
@@ -1,4 +1,4 @@
import { pathMatchRegexp } from 'utils'
const { pathToRegexp } = require("path-to-regexp")
import api from 'api'
const { queryUser } = api
@@ -13,7 +13,7 @@ export default {
subscriptions: {
setup({ dispatch, history }) {
history.listen(({ pathname }) => {
const match = pathMatchRegexp('/user/:id', pathname)
const match = pathToRegexp('/user/:id').exec(pathname)
if (match) {
dispatch({ type: 'query', payload: { id: match[1] } })
}
+77 -94
View File
@@ -1,10 +1,10 @@
/* global document */
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import moment from 'moment'
import { FilterItem } from 'components'
import { Trans, withI18n } from '@lingui/react'
import { Form, Button, Row, Col, DatePicker, Input, Cascader } from 'antd'
import { Trans } from '@lingui/react'
import { Button, Row, Col, DatePicker, Form, Input, Cascader } from 'antd'
import city from 'utils/city'
const { Search } = Input
@@ -23,12 +23,12 @@ const TwoColProps = {
xl: 96,
}
@withI18n()
@Form.create()
class Filter extends Component {
formRef = React.createRef()
handleFields = fields => {
const { createTime } = fields
if (createTime.length) {
if (createTime && createTime.length) {
fields.createTime = [
moment(createTime[0]).format('YYYY-MM-DD'),
moment(createTime[1]).format('YYYY-MM-DD'),
@@ -38,19 +38,14 @@ class Filter extends Component {
}
handleSubmit = () => {
const { onFilterChange, form } = this.props
const { getFieldsValue } = form
let fields = getFieldsValue()
fields = this.handleFields(fields)
const { onFilterChange } = this.props
const values = this.formRef.current.getFieldsValue()
const fields = this.handleFields(values)
onFilterChange(fields)
}
handleReset = () => {
const { form } = this.props
const { getFieldsValue, setFieldsValue } = form
const fields = getFieldsValue()
const fields = this.formRef.current.getFieldsValue()
for (let item in fields) {
if ({}.hasOwnProperty.call(fields, item)) {
if (fields[item] instanceof Array) {
@@ -60,22 +55,19 @@ class Filter extends Component {
}
}
}
setFieldsValue(fields)
this.formRef.current.setFieldsValue(fields)
this.handleSubmit()
}
handleChange = (key, values) => {
const { form, onFilterChange } = this.props
const { getFieldsValue } = form
let fields = getFieldsValue()
const { onFilterChange } = this.props
let fields = this.formRef.current.getFieldsValue()
fields[key] = values
fields = this.handleFields(fields)
onFilterChange(fields)
}
render() {
const { onAdd, filter, form, i18n } = this.props
const { getFieldDecorator } = form
const { onAdd, filter, i18n } = this.props
const { name, address } = filter
let initialCreateTime = []
@@ -87,86 +79,77 @@ class Filter extends Component {
}
return (
<Row gutter={24}>
<Col {...ColProps} xl={{ span: 4 }} md={{ span: 8 }}>
{getFieldDecorator('name', { initialValue: name })(
<Search
placeholder={i18n.t`Search Name`}
onSearch={this.handleSubmit}
/>
)}
</Col>
<Col
{...ColProps}
xl={{ span: 4 }}
md={{ span: 8 }}
id="addressCascader"
>
{getFieldDecorator('address', { initialValue: address })(
<Cascader
style={{ width: '100%' }}
options={city}
placeholder={i18n.t`Please pick an address`}
onChange={this.handleChange.bind(this, 'address')}
getPopupContainer={() =>
document.getElementById('addressCascader')
}
/>
)}
</Col>
<Col
{...ColProps}
xl={{ span: 6 }}
md={{ span: 8 }}
sm={{ span: 12 }}
id="createTimeRangePicker"
>
<FilterItem label={i18n.t`CreateTime`}>
{getFieldDecorator('createTime', {
initialValue: initialCreateTime,
})(
<RangePicker
style={{ width: '100%' }}
onChange={this.handleChange.bind(this, 'createTime')}
getCalendarContainer={() => {
return document.getElementById('createTimeRangePicker')
}}
<Form ref={this.formRef} name="control-ref" initialValues={{ name, address, createTime: initialCreateTime }}>
<Row gutter={24}>
<Col {...ColProps} xl={{ span: 4 }} md={{ span: 8 }}>
<Form.Item name="name">
<Search
placeholder={i18n.t`Search Name`}
onSearch={this.handleSubmit}
/>
)}
</FilterItem>
</Col>
<Col
{...TwoColProps}
xl={{ span: 10 }}
md={{ span: 24 }}
sm={{ span: 24 }}
>
<Row type="flex" align="middle" justify="space-between">
<div>
<Button
type="primary"
className="margin-right"
onClick={this.handleSubmit}
>
<Trans>Search</Trans>
</Form.Item>
</Col>
<Col
{...ColProps}
xl={{ span: 4 }}
md={{ span: 8 }}
id="addressCascader"
>
<Form.Item name="address">
<Cascader
style={{ width: '100%' }}
options={city}
placeholder={i18n.t`Please pick an address`}
/>
</Form.Item>
</Col>
<Col
{...ColProps}
xl={{ span: 6 }}
md={{ span: 8 }}
sm={{ span: 12 }}
id="createTimeRangePicker"
>
<FilterItem label={i18n.t`CreateTime`}>
<Form.Item name="createTime">
<RangePicker
style={{ width: '100%' }}
/>
</Form.Item>
</FilterItem>
</Col>
<Col
{...TwoColProps}
xl={{ span: 10 }}
md={{ span: 24 }}
sm={{ span: 24 }}
>
<Row type="flex" align="middle" justify="space-between">
<div>
<Button
type="primary" htmlType="submit"
className="margin-right"
onClick={this.handleSubmit}
>
<Trans>Search</Trans>
</Button>
<Button onClick={this.handleReset}>
<Trans>Reset</Trans>
</Button>
</div>
<Button type="ghost" onClick={onAdd}>
<Trans>Create</Trans>
</Button>
<Button onClick={this.handleReset}>
<Trans>Reset</Trans>
</Button>
</div>
<Button type="ghost" onClick={onAdd}>
<Trans>Create</Trans>
</Button>
</Row>
</Col>
</Row>
</Row>
</Col>
</Row>
</Form>
)
}
}
Filter.propTypes = {
onAdd: PropTypes.func,
form: PropTypes.object,
filter: PropTypes.object,
onFilterChange: PropTypes.func,
}
+1 -1
View File
@@ -3,7 +3,7 @@ import PropTypes from 'prop-types'
import { Table, Modal, Avatar } from 'antd'
import { DropOption } from 'components'
import { Trans, withI18n } from '@lingui/react'
import Link from 'umi/link'
import { Link } from 'umi'
import styles from './List.less'
const { confirm } = Modal
+52 -105
View File
@@ -1,7 +1,7 @@
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { Form, Input, InputNumber, Radio, Modal, Cascader } from 'antd'
import { Trans, withI18n } from '@lingui/react'
import { Trans } from '@lingui/react'
import city from 'utils/city'
const FormItem = Form.Item
@@ -14,123 +14,70 @@ const formItemLayout = {
span: 14,
},
}
@withI18n()
@Form.create()
class UserModal extends PureComponent {
handleOk = () => {
const { item = {}, onOk, form } = this.props
const { validateFields, getFieldsValue } = form
validateFields(errors => {
if (errors) {
return
}
const data = {
...getFieldsValue(),
key: item.key,
}
data.address = data.address.join(' ')
onOk(data)
})
class UserModal extends PureComponent {
formRef = React.createRef()
handleOk = () => {
const { item = {}, onOk } = this.props
this.formRef.current.validateFields()
.then(values => {
const data = {
...values,
key: item.key,
}
data.address = data.address.join(' ')
onOk(data)
})
.catch(errorInfo => {
console.log(errorInfo)
})
}
render() {
const { item = {}, onOk, form, i18n, ...modalProps } = this.props
const { getFieldDecorator } = form
const { i18n, item = {}, onOk, form, ...modalProps } = this.props
return (
<Modal {...modalProps} onOk={this.handleOk}>
<Form layout="horizontal">
<FormItem label={i18n.t`Name`} hasFeedback {...formItemLayout}>
{getFieldDecorator('name', {
initialValue: item.name,
rules: [
{
required: true,
},
],
})(<Input />)}
<Form ref={this.formRef} name="control-ref" initialValues={{ ...item, address: item.address && item.address.split(' ') }} layout="horizontal">
<FormItem name='name' rules={[{ required: true }]}
label={i18n.t`Name`} hasFeedback {...formItemLayout}>
<Input />
</FormItem>
<FormItem label={i18n.t`NickName`} hasFeedback {...formItemLayout}>
{getFieldDecorator('nickName', {
initialValue: item.nickName,
rules: [
{
required: true,
},
],
})(<Input />)}
<FormItem name='nickName' rules={[{ required: true }]}
label={i18n.t`NickName`} hasFeedback {...formItemLayout}>
<Input />
</FormItem>
<FormItem label={i18n.t`Gender`} hasFeedback {...formItemLayout}>
{getFieldDecorator('isMale', {
initialValue: item.isMale,
rules: [
{
required: true,
type: 'boolean',
},
],
})(
<Radio.Group>
<Radio value>
<Trans>Male</Trans>
</Radio>
<Radio value={false}>
<Trans>Female</Trans>
</Radio>
</Radio.Group>
)}
<FormItem name='isMale' rules={[{ required: true }]}
label={i18n.t`Gender`} hasFeedback {...formItemLayout}>
<Radio.Group>
<Radio value>
<Trans>Male</Trans>
</Radio>
<Radio value={false}>
<Trans>Female</Trans>
</Radio>
</Radio.Group>
</FormItem>
<FormItem label={i18n.t`Age`} hasFeedback {...formItemLayout}>
{getFieldDecorator('age', {
initialValue: item.age,
rules: [
{
required: true,
type: 'number',
},
],
})(<InputNumber min={18} max={100} />)}
<FormItem name='age' label={i18n.t`Age`} hasFeedback {...formItemLayout}>
<InputNumber min={18} max={100} />
</FormItem>
<FormItem label={i18n.t`Phone`} hasFeedback {...formItemLayout}>
{getFieldDecorator('phone', {
initialValue: item.phone,
rules: [
{
required: true,
pattern: /^1[34578]\d{9}$/,
message: i18n.t`The input is not valid phone!`,
},
],
})(<Input />)}
<FormItem name='phone' rules={[{ required: true, pattern: /^1[34578]\d{9}$/, message: i18n.t`The input is not valid phone!`, }]}
label={i18n.t`Phone`} hasFeedback {...formItemLayout}>
<Input />
</FormItem>
<FormItem label={i18n.t`Email`} hasFeedback {...formItemLayout}>
{getFieldDecorator('email', {
initialValue: item.email,
rules: [
{
required: true,
pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/,
message: i18n.t`The input is not valid E-mail!`,
},
],
})(<Input />)}
<FormItem name='email' rules={[{ required: true, pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/, message: i18n.t`The input is not valid E-mail!`, }]}
label={i18n.t`Email`} hasFeedback {...formItemLayout}>
<Input />
</FormItem>
<FormItem label={i18n.t`Address`} hasFeedback {...formItemLayout}>
{getFieldDecorator('address', {
initialValue: item.address && item.address.split(' '),
rules: [
{
required: true,
},
],
})(
<Cascader
style={{ width: '100%' }}
options={city}
placeholder={i18n.t`Pick an address`}
/>
)}
<FormItem name='address' rules={[{ required: true, }]}
label={i18n.t`Address`} hasFeedback {...formItemLayout}>
<Cascader
style={{ width: '100%' }}
options={city}
placeholder={i18n.t`Pick an address`}
/>
</FormItem>
</Form>
</Modal>
+6 -4
View File
@@ -1,7 +1,7 @@
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { router } from 'utils'
import { connect } from 'dva'
import { history } from 'umi'
import { connect } from 'umi'
import { Row, Col, Button, Popconfirm } from 'antd'
import { withI18n } from '@lingui/react'
import { Page } from 'components'
@@ -17,7 +17,7 @@ class User extends PureComponent {
const { location } = this.props
const { query, pathname } = location
router.push({
history.push({
pathname,
search: stringify(
{
@@ -53,6 +53,7 @@ class User extends PureComponent {
const { currentItem, modalVisible, modalType } = user
return {
i18n,
item: modalType === 'create' ? {} : currentItem,
visible: modalVisible,
destroyOnClose: true,
@@ -129,10 +130,11 @@ class User extends PureComponent {
}
get filterProps() {
const { location, dispatch } = this.props
const { location, dispatch, i18n } = this.props
const { query } = location
return {
i18n,
filter: {
...query,
},
+2 -2
View File
@@ -1,5 +1,5 @@
import modelExtend from 'dva-model-extend'
import { pathMatchRegexp } from 'utils'
const { pathToRegexp } = require("path-to-regexp")
import api from 'api'
import { pageModel } from 'utils/model'
@@ -24,7 +24,7 @@ export default modelExtend(pageModel, {
subscriptions: {
setup({ dispatch, history }) {
history.listen(location => {
if (pathMatchRegexp('/user', location.pathname)) {
if (pathToRegexp('/user').exec(location.pathname)) {
const payload = location.query || { page: 1, pageSize: 10 }
dispatch({
type: 'query',
+4 -4
View File
@@ -15,6 +15,10 @@ body {
height: 8px;
}
.margin-right {
margin-right: 16px;
}
:global {
.ant-breadcrumb {
& > span {
@@ -79,10 +83,6 @@ body {
padding: 12px 16px !important;
}
.margin-right {
margin-right: 16px;
}
a:focus {
text-decoration: none;
}
+1 -1
View File
@@ -1,6 +1,6 @@
module.exports = {
siteName: 'AntD Admin',
copyright: 'Ant Design Admin ©2019 zuiidea',
copyright: 'Ant Design Admin ©2020 zuiidea',
logoPath: '/logo.svg',
apiPrefix: '/api/v1',
fixedHeader: true, // sticky primary layout header
+31
View File
@@ -0,0 +1,31 @@
import {
PayCircleOutlined,
ShoppingCartOutlined,
MessageOutlined,
TeamOutlined,
UserOutlined,
DashboardOutlined,
ApiOutlined,
CameraOutlined,
EditOutlined,
CodeOutlined,
LineOutlined,
BarChartOutlined,
AreaChartOutlined,
} from '@ant-design/icons'
export default {
'pay-circle-o': <PayCircleOutlined />,
'shopping-cart': <ShoppingCartOutlined />,
'camera-o': <CameraOutlined />,
'line-chart': <LineOutlined />,
'code-o': <CodeOutlined />,
'area-chart': <AreaChartOutlined />,
'bar-chart': <BarChartOutlined />,
message: <MessageOutlined />,
team: <TeamOutlined />,
dashboard: <DashboardOutlined />,
user: <UserOutlined />,
api: <ApiOutlined />,
edit: <EditOutlined />,
}
+10 -112
View File
@@ -1,17 +1,15 @@
import { cloneDeep, isString, flow, curry } from 'lodash'
import umiRouter from 'umi/router'
import pathToRegexp from 'path-to-regexp'
import { i18n } from './config'
import { cloneDeep } from 'lodash'
const { pathToRegexp } = require("path-to-regexp")
import moment from 'moment'
import 'moment/locale/zh-cn'
import store from 'store'
import { i18n } from './config'
export classnames from 'classnames'
export config from './config'
export request from './request'
export { Color } from './theme'
// export const { defaultLanguage } = i18n
// export const languages = i18n.languages.map(item => item.key)
export const languages = i18n ? i18n.languages.map(item => item.key) : []
export const defaultLanguage = i18n ? i18n.defaultLanguage : ''
@@ -63,106 +61,7 @@ export function arrayToTree(
return result
}
// export const langFromPath = curry(
// /**
// * Query language from pathname.
// * @param {array} languages Specify which languages are currently available.
// * @param {string} defaultLanguage Specify the default language.
// * @param {string} pathname Pathname to be queried.
// * @return {string} Return the queryed language.
// */
// (languages, defaultLanguage, pathname) => {
// for (const item of languages) {
// if (pathname.startsWith(`/${item}/`)) {
// return item
// }
// }
// return defaultLanguage
// }
// )(languages)(defaultLanguage)
export const langFromPath = pathname => {
for (const item of languages) {
if (pathname.startsWith(`/${item}/`)) {
return item
}
}
return defaultLanguage
}
export const deLangPrefix = curry(
/**
* Remove the language prefix in pathname.
* @param {array} languages Specify which languages are currently available.
* @param {string} pathname Remove the language prefix in the pathname.
* @return {string} Return the pathname after removing the language prefix.
*/
(languages, pathname) => {
if (!pathname) {
return
}
for (const item of languages) {
if (pathname.startsWith(`/${item}/`)) {
return pathname.replace(`/${item}/`, '/')
}
}
return pathname
}
)(languages)
/**
* Add the language prefix in pathname.
* @param {string} pathname Add the language prefix in the pathname.
* @return {string} Return the pathname after adding the language prefix.
*/
export function addLangPrefix(pathname) {
if (!i18n) {
return pathname
}
const prefix = langFromPath(window.location.pathname)
return `/${prefix}${deLangPrefix(pathname)}`
}
const routerAddLangPrefix = params => {
if (!i18n) {
return params
}
if (isString(params)) {
params = addLangPrefix(params)
} else {
params.pathname = addLangPrefix(params.pathname)
}
return params
}
/**
* Adjust the router to automatically add the current language prefix before the pathname in push and replace.
*/
const myRouter = { ...umiRouter }
myRouter.push = flow(
routerAddLangPrefix,
umiRouter.push
)
myRouter.replace = flow(
routerAddLangPrefix,
myRouter.replace
)
export const router = myRouter
/**
* Whether the path matches the regexp if the language prefix is ignored, https://github.com/pillarjs/path-to-regexp.
* @param {string|regexp|array} regexp Specify a string, array of strings, or a regular expression.
* @param {string} pathname Specify the pathname to match.
* @return {array|null} Return the result of the match or null.
*/
export function pathMatchRegexp(regexp, pathname) {
return pathToRegexp(regexp).exec(deLangPrefix(pathname))
}
/**
* In an array object, traverse all parent IDs based on the value of an object.
@@ -226,7 +125,7 @@ export function queryLayout(layouts, pathname) {
const isMatch = regepx => {
return regepx instanceof RegExp
? regepx.test(pathname)
: pathMatchRegexp(regepx, pathname)
: pathToRegexp(regepx).exec(pathname)
}
for (const item of layouts) {
@@ -259,16 +158,15 @@ export function queryLayout(layouts, pathname) {
return result
}
export function getLocale() {
return langFromPath(window.location.pathname)
return store.get('locale') || defaultLanguage
}
export function setLocale(language) {
if (getLocale() !== language) {
moment.locale(language === 'zh' ? 'zh-cn' : language)
umiRouter.push({
pathname: `/${language}${deLangPrefix(window.location.pathname)}`,
search: window.location.search,
})
store.set('locale', language)
window.location.reload()
}
}
}
+6 -7
View File
@@ -1,19 +1,18 @@
import { pathMatchRegexp } from './index'
import pathToRegexp from 'path-to-regexp'
const { pathToRegexp } = require("path-to-regexp")
describe('test pathMatchRegexp', () => {
describe('test pathToRegexp', () => {
it('get right', () => {
expect(pathMatchRegexp('/user', '/zh/user')).toEqual(
expect(pathToRegexp('/user').exec('/zh/user')).toEqual(
pathToRegexp('/user').exec('/user')
)
expect(pathMatchRegexp('/user', '/user')).toEqual(
expect(pathToRegexp('/user').exec('/user')).toEqual(
pathToRegexp('/user').exec('/user')
)
expect(pathMatchRegexp('/user/:id', '/zh/user/1')).toEqual(
expect(pathToRegexp('/user/:id').exec('/zh/user/1')).toEqual(
pathToRegexp('/user/:id').exec('/user/1')
)
expect(pathMatchRegexp('/user/:id', '/user/1')).toEqual(
expect(pathToRegexp('/user/:id').exec('/user/1')).toEqual(
pathToRegexp('/user/:id').exec('/user/1')
)
})
+3 -4
View File
@@ -1,9 +1,8 @@
import axios from 'axios'
import { cloneDeep, isEmpty } from 'lodash'
import pathToRegexp from 'path-to-regexp'
const { parse, compile } = require("path-to-regexp")
import { message } from 'antd'
import { CANCEL_REQUEST_MESSAGE } from 'utils/constant'
import qs from 'qs'
const { CancelToken } = axios
window.cancelRequest = new Map()
@@ -20,8 +19,8 @@ export default function request(options) {
url = url.slice(domain.length)
}
const match = pathToRegexp.parse(url)
url = pathToRegexp.compile(url)(data)
const match = parse(url)
url = compile(url)(data)
for (const item of match) {
if (item instanceof Object && item.name in cloneData) {