Commit 3c02868d authored by duanledexianxianxian's avatar duanledexianxianxian

sync code

parent 979e44d2
......@@ -5,6 +5,18 @@ module.exports = {
rules: {
...fabric.default.rules,
},
settings: {
...fabric.default.settings,
// support import modules from TypeScript files in JavaScript files
'import/resolver': {
node: { extensions: ['.js', '.ts', '.tsx'] },
alias: {
map: [['@', './src'], ['utils', './src/utils'], ['config', './config']],
extensions: ['.ts', '.js', '.jsx', '.json'],
},
},
},
globals: {
ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION: true,
page: true,
......
......@@ -2,6 +2,7 @@ import { IConfig, IPlugin } from 'umi-types';
import defaultSettings from './defaultSettings'; // https://umijs.org/config/
import slash from 'slash2';
import webpackPlugin from './plugin.config';
import theme from './theme.config';
const path = require('path');
const { pwa } = defaultSettings; // preview.pro.ant.design only do not use in your production ;
......@@ -325,17 +326,6 @@ export default {
// Theme for antd
// https://ant.design/docs/react/customize-theme-cn
theme,
// proxy: {
// '/server/api/': {
// target: 'https://preview.pro.ant.design/',
// changeOrigin: true,
// pathRewrite: { '^/server': '' },
// },
// },
// Theme for antd: https://ant.design/docs/react/customize-theme-cn
theme: {
'primary-color': primaryColor,
},
define: {
ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION:
ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION || '', // preview.pro.ant.design only do not use in your production ; preview.pro.ant.design 专用环境变量,请不要在你的项目中使用它。
......@@ -379,7 +369,6 @@ export default {
manifest: {
basePath: '/',
},
uglifyJSOptions,
chainWebpack: webpackPlugin,
// 配置 webpack 的 resolve.alias 属性 默认src=>@
alias: {
......
......@@ -34,7 +34,6 @@
},
"husky": {
"hooks": {
"pre-commit": "npm run lint-staged"
}
},
"lint-staged": {
......@@ -90,7 +89,9 @@
"umi-plugin-ga": "^1.1.3",
"umi-plugin-pro-block": "^1.3.2",
"umi-plugin-react": "^1.8.2",
"umi-request": "^1.0.7"
"axios":"^0.19.0",
"query-string":"^6.8.1",
"store":"^2.0.12"
},
"devDependencies": {
"@ant-design/colors": "^3.1.0",
......@@ -105,7 +106,6 @@
"@types/react": "^16.8.19",
"@types/react-document-title": "^2.0.3",
"@types/react-dom": "^16.8.4",
"@types/numeral":"^0.0.25",
"babel-eslint": "^10.0.1",
"chalk": "^2.4.2",
"check-prettier": "^1.0.3",
......@@ -131,7 +131,7 @@
"stylelint": "^10.1.0",
"webpack-theme-color-replacer": "^1.1.5",
"mockjs": "^1.0.1-beta3",
"@types/mockjs":"^1.0.2"
"eslint-import-resolver-alias": "^1.1.2"
},
"optionalDependencies": {
"puppeteer": "^1.17.0"
......
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>
);
}
}
.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;
}
// import store from './utils/store';
export default {
baseUrl: 'http://platform.kuopu.net/9080',
storeNameSpace: 'kim',
headers: () => ({
Authorization:
'eyJhbGciOiJIUzI1NiJ9.eyJ1aWQiOjMzLCJ1c24iOiLmrKfpmLPljZrlrofmrKfpmLPljZrlrofmrKfpmLPljZrlrofmrKfpmLPljZrlrofmrKfpmLPljZrlrofmrKfpmLPljZrlrofmrKfpmLPljZrlrociLCJzdGEiOjE1NjEzMzQ2MDkwMTEsImxpZCI6Im91eWFuZ2JveXUifQ.eriHWClI-ST9CuEJuoU608KTKxIhf4XUxOSslzwT6K8',
}),
};
import request from 'umi-request';
import { get } from '@/utils/request';
export async function queryCurrent() {
return request('/api/currentUser');
return get('/api/currentUser');
}
export async function queryFakeList(params: { count: number }) {
return request('/api/fake_list', {
return get('/api/fake_list', {
params,
});
}
import request from 'umi-request';
import { get } from '@/utils/request';
export async function queryCurrent() {
return request('/api/currentUser');
return get('/api/currentUser');
}
export async function queryProvince() {
return request('/api/geographic/province');
return get('/api/geographic/province');
}
export async function queryCity(province: string) {
return request(`/api/geographic/city/${province}`);
return get(`/api/geographic/city/${province}`);
}
export async function query() {
return request('/api/users');
return get('/api/users');
}
import request from 'umi-request';
import { get } from '@/utils/request';
export async function fakeChartData() {
return request('/api/fake_chart_data');
return get('/api/fake_chart_data');
}
import request from 'umi-request';
import { get } from '@/utils/request';
export async function queryTags() {
return request('/api/tags');
return get('/api/tags');
}
import request from 'umi-request';
import { get } from '@/utils/request';
export async function queryProjectNotice() {
return request('/api/project/notice');
return get('/api/project/notice');
}
export async function queryActivities() {
return request('/api/activities');
return get('/api/activities');
}
export async function fakeChartData() {
return request('/api/fake_chart_data');
return get('/api/fake_chart_data');
}
export async function queryCurrent() {
return request('/api/currentUser');
return get('/api/currentUser');
}
import request from 'umi-request';
import { get } from '@/utils/request';
export async function fakeSubmitForm(params: any) {
return request('/api/forms', {
return get('/api/forms', {
method: 'POST',
data: params,
});
......
import request from 'umi-request';
import { get } from '@/utils/request';
export async function fakeSubmitForm(params: any) {
return request('/api/forms', {
return get('/api/forms', {
method: 'POST',
data: params,
});
......
import request from 'umi-request';
import { get } from '@/utils/request';
export async function fakeSubmitForm(params: any) {
return request('/api/forms', {
return get('/api/forms', {
method: 'POST',
data: params,
});
......
import request from 'umi-request';
import { get } from '@/utils/request';
import { BasicListItemDataType } from './data.d';
interface ParamsType extends Partial<BasicListItemDataType> {
......@@ -6,14 +6,14 @@ interface ParamsType extends Partial<BasicListItemDataType> {
}
export async function queryFakeList(params: ParamsType) {
return request('/api/fake_list', {
return get('/api/fake_list', {
params,
});
}
export async function removeFakeList(params: ParamsType) {
const { count = 5, ...restParams } = params;
return request('/api/fake_list', {
return get('/api/fake_list', {
method: 'POST',
params: {
count,
......@@ -27,7 +27,7 @@ export async function removeFakeList(params: ParamsType) {
export async function addFakeList(params: ParamsType) {
const { count = 5, ...restParams } = params;
return request('/api/fake_list', {
return get('/api/fake_list', {
method: 'POST',
params: {
count,
......@@ -41,7 +41,7 @@ export async function addFakeList(params: ParamsType) {
export async function updateFakeList(params: ParamsType) {
const { count = 5, ...restParams } = params;
return request('/api/fake_list', {
return get('/api/fake_list', {
method: 'POST',
params: {
count,
......
import request from 'umi-request';
import { get } from '@/utils/request';
export async function queryFakeList(params: { count: number }) {
return request('/api/fake_list', {
return get('/api/fake_list', {
params,
});
}
import request from 'umi-request';
import { get } from 'utils/request';
import { ListItemDataType } from './data.d';
export async function queryFakeList(params: ListItemDataType) {
return request('/api/fake_list', {
return get('/api/fake_list', {
params,
});
}
import request from 'umi-request';
import { get } from '@/utils/request';
import { ListItemDataType } from './data.d';
export async function queryFakeList(params: ListItemDataType) {
return request('/api/fake_list', {
return get('/api/fake_list', {
params,
});
}
import request from 'umi-request';
import { get } from '@/utils/request';
export async function queryFakeList(params: { count: number }) {
return request('/api/fake_list', {
return get('/api/fake_list', {
params,
});
}
import request from 'umi-request';
import { get } from '@/utils/request';
import { TableListParams } from './data.d';
export async function queryRule(params: TableListParams) {
return request('/api/rule', {
return get('/api/rule', {
params,
});
}
export async function removeRule(params: TableListParams) {
return request('/api/rule', {
return get('/api/rule', {
method: 'POST',
data: {
...params,
......@@ -18,7 +18,7 @@ export async function removeRule(params: TableListParams) {
}
export async function addRule(params: TableListParams) {
return request('/api/rule', {
return get('/api/rule', {
method: 'POST',
data: {
...params,
......@@ -28,7 +28,7 @@ export async function addRule(params: TableListParams) {
}
export async function updateRule(params: TableListParams) {
return request('/api/rule', {
return get('/api/rule', {
method: 'POST',
data: {
...params,
......
import request from 'umi-request';
import { get } from '@/utils/request';
export async function queryAdvancedProfile() {
return request('/api/profile/advanced');
return get('/api/profile/advanced');
}
import request from 'umi-request';
import { get } from '@/utils/request';
export async function queryBasicProfile() {
return request('/api/profile/basic');
return get('/api/profile/basic');
}
@import "~@/themes/vars.less";
.root {
margin-left: -@space-lg;
margin-right: -@space-lg;
margin-bottom: @space-lg;
margin-left: -@space-lg;
// padding: 0 @space-lg;
.left {
padding: 0 @space-lg;
......@@ -17,8 +17,8 @@
}
}
.right {
padding: 0 @space-lg;
display: flex;
justify-content: flex-end;
padding: 0 @space-lg;
}
}
@import "~@/themes/vars.less";
.root {
}
@import '~@/themes/vars.less';
@import "~@/themes/vars.less";
.root {
margin-left: -@space-lg;
margin-right: -@space-lg;
margin-left: -@space-lg;
:global {
.ant-form-item {
display: flex;
padding: 0 @space-lg;
margin: 0 0 @space-lg / 3 0;
padding: 0 @space-lg;
.ant-form-item-label {
width: auto;
min-width: 80px;
......
@import "~@/themes/vars.less";
.root {
margin-left: -@space-lg;
margin-right: -@space-lg;
margin-bottom: @space-lg;
margin-left: -@space-lg;
// padding: 0 @space-lg;
.left {
padding: 0 @space-lg;
......@@ -17,8 +17,8 @@
}
}
.right {
padding: 0 @space-lg;
display: flex;
justify-content: flex-end;
padding: 0 @space-lg;
}
}
@import "~@/themes/vars.less";
.root {
}
@import '~@/themes/vars.less';
@import "~@/themes/vars.less";
.root {
margin-left: -@space-lg;
margin-right: -@space-lg;
margin-left: -@space-lg;
:global {
.ant-form-item {
display: flex;
padding: 0 @space-lg;
margin: 0 0 @space-lg / 3 0;
padding: 0 @space-lg;
.ant-form-item-label {
width: auto;
min-width: 80px;
......
......@@ -5,6 +5,7 @@ const FormItem = Form.Item;
export const EditableContext = React.createContext();
// eslint-disable-next-line react/prefer-stateless-function
export class EditableCell extends React.Component {
render() {
const {
......
......@@ -6,8 +6,8 @@
}
.editable-row .ant-form-explain {
position: absolute;
font-size: 12px;
margin-top: -4px;
font-size: 12px;
}
.fixedWidthTable {
table {
......
@import "~@/themes/vars.less";
.root {
background-color: #fff;
min-height: calc(100vh - 100px);
padding: 16px 24px;
background-color: #fff;
border-radius: 4px;
min-height: calc(100vh - 100px);
}
......@@ -19,6 +19,7 @@ export default {
},
) {
list.forEach(element => {
// eslint-disable-next-line no-param-reassign
element.key = element.paramId;
});
return {
......
......@@ -19,6 +19,7 @@ export default {
},
) {
list.forEach(item => {
// eslint-disable-next-line no-param-reassign
item.key = item.paramId;
});
return {
......
import request from 'umi-request';
import { get } from '@/utils/request';
import { FromDataType } from './index';
export async function fakeAccountLogin(params: FromDataType) {
return request('/api/login/account', {
return get('/api/login/account', {
method: 'POST',
data: params,
});
}
export async function getFakeCaptcha(mobile: string) {
return request(`/api/login/captcha?mobile=${mobile}`);
return get(`/api/login/captcha?mobile=${mobile}`);
}
import request from 'umi-request';
import { get } from '@/utils/request';
import { UserRegisterParams } from './index';
export async function fakeRegister(params: UserRegisterParams) {
return request('/api/register', {
return get('/api/register', {
method: 'POST',
data: params,
});
......
/**
* author: liu.yang
* date: 2018-08-22 09:09:23
* 一下内容请不要随意覆盖
*/
// 字色
//3a73e9
//43CEC4
@color-primary: #43cec4; // 主色
@color-primary-active: #43cec4; // 主色
@color-primary-disable: #bec5d4; // 主色
@color-primary-sup: #374583; // 图标色
@color-border: #e3e7ef; // 边框
@color-background: #f4f5f7; // 背景颜色
@color-success: #3cd99d; // 辅助色-成功
@color-error: #ff5c6a; // 辅助色-异常
@color-warning: #ffbc19; // 辅助色-警告
@text-title-color: #202f75; // 标题颜色
@text-content-color: #374583; // 正文颜色
@text-prompt-color: #b3b9c4; // 提示颜色
@table-background-color: #f4f5f7; // 表单背景
@table--active-color: #e3effd; // 表单选中
// 字号
@font-size-xlg: 2.2rem; // 大标题
@font-size-lg: 2rem; // 标题
@font-size-xmd: 1.6rem; // 副标题
@font-size-md: 1.4rem; // 主字体
@font-size-sm: 1.2rem; // 说明 描述
@font-size-zs: 1rem; // 说明 描述
// 圆角
@radius-sm: 0.22rem;
@radius-md: 0.4rem;
@radius-lg: 0.8rem;
// 间距
@space-lg: 24px;
@space-xmd: 22px;
@space-md: 20px;
@space-sm: 16px;
@space-xs: 14px;
@space-xxs: 12px;
.baseBorder(@radius: 4px) {
border: 1px solid @color-border;
border-radius: @radius-sm;
}
......@@ -22,11 +22,11 @@ declare module 'webpack-theme-color-replacer';
declare module 'webpack-theme-color-replacer/client';
// src/typings.d.ts
declare module 'umi-plugin-react/locale' {
export default interface MessageDescriptor {
id: string;
} /* eslint-disable-line */
}
// declare module 'umi-plugin-react/locale' {
// export default interface MessageDescriptor {
// id: string;
// } /* eslint-disable-line */
// }
declare let ga: Function;
......
// eslint-disable-next-line eslint-comments/disable-enable-pair
/* eslint-disable no-bitwise */
// 工具类已经转移到solomon-utils下,如果需要添加工具部分,请先考虑是否需要添加到solomon-utils下
import pathToRegexp from 'path-to-regexp';
export const generateUUID = () => {
let d = new Date().getTime();
const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
const r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
});
return uuid;
};
/**
* 检查是否为正确的移动的电话号码
*/
export const checkMobilePhone = mobilePhone => {
if (!/^1(3|4|5|7|8)\d{9}$/.test(mobilePhone)) {
return false;
}
return true;
};
/**
* 检查是否为正确的邮箱
*/
export const checkEmail = mobilePhone => {
const reg = new RegExp(
'^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$',
);
if (!reg.test(mobilePhone)) {
return false;
}
return true;
};
/**
* 检查是否为正确的密码
* @param {*} password
*/
export const checkPassword = password => {
const reg = new RegExp(/^(\w){6,20}$/);
if (!reg.test(password)) {
return false;
}
return true;
};
/**
* 转换后端返回的表格数据成前端使用的表格数据
* @param {object} data 后端数据
* @param {object} option
* @param {string} option.keyCode 指定唯一标识字段
* @param {function} option.onChange 分页回调
*/
export const trimTableData = (data = {}, option = {}) => {
const { records = [], current = 1, pageSize = 1, total = 1 } = data;
const { keyCode, onChange } = option;
let tableData = records;
const pageData = {
current,
pageSize,
total,
};
if (keyCode) {
tableData = records.map(item => ({ key: item[keyCode], ...item }));
}
if (typeof onChange === 'function') {
pageData.onChange = onChange;
}
return {
tableData,
pageData,
};
};
/**
* 转换后端返回的静态数据为key、value格式
* @param {object} staticData 后端静态数据
* @param {string} staticKey 需要处理的静态数据唯一ID
*/
export const trimStaticData = (staticData = {}, staticKey) =>
(staticData[staticKey] || [])
// .filter(item => item.paramLocale === "zh_CN")
.map(item => ({
key: item.paramValue,
value: item.paramName,
}));
/**
* 处理后端返回的组织数据为供Select组件使用的带结构数据
* @param {object} data
*/
export const trimOrgaData = data => {
const trimData = clone(
data.map(item => ({
...item,
title: item.orgName,
value: item.orgId,
key: item.orgId,
})),
);
const orgaData = trimData.filter(item => item.orgType === 1);
const depaData = trimData.filter(item => item.orgType === 2);
// 处理部门数据
depaData.forEach(item => {
const orgaKey = orgaData.findIndex(orgaItem => orgaItem.orgId === item.parentOrgId);
if (orgaKey > -1) {
const children = orgaData[orgaKey].children || [];
children.push(item);
orgaData[orgaKey].children = [...children];
}
});
// 处理公司数据
// 目前只支持两层数据
return orgaData.reduce((container, item) => {
const orgaKey = container.findIndex(orgaItem => orgaItem.orgId === item.parentOrgId);
if (orgaKey > -1) {
const children = container[orgaKey].children || [];
children.push(item);
container[orgaKey].children = [...children];
} else {
container.push(item);
}
return container;
}, []);
};
export const treeDataTransform = (data = [], key = 'id', parentKey = 'parendId', rootPid = -1) => {
const midObj = {};
const arr = [];
data.sort((a, b) => b[parentKey] - a[parentKey]);
// eslint-disable-next-line
const translator = data => {
if (!data || !data.length) {
return data;
}
data.forEach((item, index) => {
const nowPid = item[parentKey];
const nowId = item[key];
if (nowPid !== rootPid) {
translator(item);
delete data[index];
}
// 建立当前节点的父节点的children 数组
if (midObj[nowPid]) {
midObj[nowPid].push(item);
} else {
midObj[nowPid] = [];
midObj[nowPid].push(item);
}
// 将children 放入合适的位置
if (midObj[nowId]) {
item.children = midObj[nowId];
delete midObj[nowId];
if (item && data[index]) {
arr.push(item);
}
}
});
};
translator(data);
return arr;
};
export const treeTransform1 = (data = [], key = 'id', parentKey = 'parendId', rootPid = -1) => {
const parents = data.filter(
item => item[parentKey] === rootPid || item[parentKey] === 'undefined',
);
const children = data.filter(
item => item[parentKey] !== rootPid && item[parentKey] !== 'undefined',
);
// eslint-disable-next-line
const translator = (parents, children) => {
parents.forEach(parent => {
children.forEach((current, index) => {
if (current[parentKey] !== parent[key]) {
return;
}
const temp = JSON.parse(JSON.stringify(children));
temp.splice(index, 1);
if (typeof parent.children !== 'undefined') {
parent.children.push(current);
} else {
parent.children = [current];
}
return translator([current], temp);
});
});
};
translator(parents, children);
return parents;
};
/**
* 平级数组菜单列表转成树形菜单列表
* @param {平级数组菜单列表} flatMenuList
*/
export const toTreeMenuList = (flatMenuList = []) => {
const tree = [];
const key = 'menuId';
const pKey = 'pMenuId';
const topFlag = 0;
if (flatMenuList) {
const dict = {};
// add rood node
flatMenuList.forEach(item => {
dict[item[key]] = item;
if (equals(item[pKey], topFlag) || item[pKey] === '') {
item.level = 0;
item.key = String(item[key]);
item.icon = item.menuIcon;
item.link = item.menuUrl;
item.title = item.menuName;
tree[tree.length] = item; // 添加根节点,可能有多个节点
}
});
flatMenuList.forEach(item => {
const child = item;
if (equals(child[pKey], topFlag) || child[pKey] === '') {
return;
}
const parent = dict[child[pKey]];
if (parent) {
// child.parent = parent;
if (!parent.children) {
parent.children = [];
}
child.key = String(child[key]);
child.level = parent.level + 1;
child.icon = child.menuIcon;
child.link = child.menuUrl;
child.title = child.menuName;
parent.children[parent.children.length] = child;
}
});
return tree;
}
};
/**
* 平级组织部门转换成树形组织部门
* @param {*} flatList
*/
export const toDepaTree = (flatList = []) =>
flatListToTree(flatList, 'orgId', 'parentOrgId', 0, {
title: 'orgName',
value: 'orgId',
});
/**
* 平级数组部门-组织列表转成树形部门-组织列表
* @param {评级列表} flatList
* @param {*} key
* @param {*} pKey
* @param {*} topFlag
* @param {*} extentProcess
*/
export const flatListToTree = (
flatList = [],
key = 'id',
pKey = 'pId',
topFlag = 0,
mappingData = {},
) => {
const tree = [];
if (flatList) {
const dict = {};
// add rood node
flatList.forEach(item => {
dict[item[key]] = item;
if (equals(item[pKey], topFlag) || item[pKey] === '') {
item.level = 0;
item.key = String(item[key]);
Object.keys(mappingData).forEach(k => {
item[k] = item[mappingData[k]];
});
tree[tree.length] = item; // 添加根节点,可能有多个节点
}
});
flatList.forEach(item => {
const child = item;
if (equals(child[pKey], topFlag) || child[pKey] === '') {
return;
}
const parent = dict[child[pKey]];
if (parent) {
// child.parent = parent;
if (!parent.children) {
parent.children = [];
}
child.key = String(child[key]);
child.level = parent.level + 1;
Object.keys(mappingData).forEach(k => {
child[k] = child[mappingData[k]];
});
parent.children[parent.children.length] = child;
}
});
return tree;
}
};
/**
* url转成数组
* /userinfo/2144/id => ['/userinfo','/useinfo/2144,'/userindo/2144/id']
* @param {url} url
*/
export function urlToList(url) {
const urllist = url.split('/').filter(i => i);
return urllist.map((urlItem, index) => `/${urllist.slice(0, index + 1).join('/')}`);
}
/**
* 判断路径是否匹配了菜单旅游业经
* @param {*} flatMenuList
* @param {*} path
*/
export const getMenuMatches = (flatMenuList, path) =>
flatMenuList.filter(item => {
if (item.menuUrl) {
return pathToRegexp(item.menuUrl).test(path);
}
return false;
});
/**
* 获得当前选中的菜单key
* @param {*} flatMenuList
* @param {*} path
*/
export const getSelectedkey = (flatMenuList = [], pathname) => {
const items = urlToList(pathname)
.map(item => getMenuMatches(flatMenuList, item)[0])
.filter(item => item);
return items && items.length > 0 ? String(items[items.length - 1].menuId) : '';
};
export const getDefaultOpenKeys = (flatMenuList = [], pathname) => {
const openKeys = [];
const topFlag = 0;
if (flatMenuList.length > 0) {
const key = getSelectedkey(flatMenuList, pathname);
const menuIdMap = {};
const pMenuIdMap = {};
flatMenuList.forEach(item => {
menuIdMap[item.menuId] = item;
pMenuIdMap[item.pMenuId] = item;
});
if (key === '') {
openKeys.push(String(pMenuIdMap[topFlag].menuId));
} else {
let t = key;
for (let i = 0; i < flatMenuList.length; i += 1) {
if (equals(t, topFlag)) {
break;
}
if (menuIdMap[t]) {
openKeys.push(String(menuIdMap[t].menuId));
t = menuIdMap[t].pMenuId;
}
}
}
}
return openKeys;
};
/**
* 文件下载
* @param {*} url
* @param {*} fileNames
* @param {...any} params
*/
export async function downloadFile(url, params) {
const token = storage.get('token');
const formEle = document.createElement('form');
formEle.method = 'get';
formEle.style = 'display:none;';
formEle.action = url;
const tokenEle = document.createElement('input');
tokenEle.type = 'hidden';
tokenEle.name = 'token';
tokenEle.value = token;
formEle.appendChild(tokenEle);
for (const key in params) {
if (key && params[key]) {
const paramsEle = document.createElement('input');
paramsEle.type = 'hidden';
paramsEle.name = key;
paramsEle.value = params[key];
formEle.appendChild(paramsEle);
}
}
document.body.appendChild(formEle);
formEle.submit();
document.body.removeChild(formEle);
}
/**
* request 网络请求工具
* 更详细的 api 文档: https://github.com/umijs/umi-request
*/
import { extend } from 'umi-request';
import { notification } from 'antd';
import axios from 'axios';
const codeMessage = {
200: '服务器成功返回请求的数据。',
......@@ -23,28 +18,76 @@ const codeMessage = {
504: '网关超时。',
};
/**
* 异常处理程序
*/
const errorHandler = (error: { response: Response }): void => {
const { response } = error;
if (response && response.status) {
const errorText = codeMessage[response.status] || response.statusText;
const { status, url } = response;
class HttpRequest {
constructor(options) {
this.options = options;
this.queues = {};
}
notification.error({
message: `请求错误 ${status}: ${url}`,
description: errorText,
});
getInsideConfig() {
const config = {
baseURL: this.options.baseUrl,
headers: {
'x-requested-with': 'XMLHttpRequest',
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
Accept: 'application/json',
withCredentials: false, // default
timeout: 10000,
responseType: 'json',
...this.options.headers,
},
};
return config;
}
destroy(url) {
delete this.queues[url];
}
};
/**
* 配置request请求时的默认参数
*/
const request = extend({
errorHandler, // 默认错误处理
credentials: 'include', // 默认请求是否带上cookie
});
interceptors(instance, url, options) {
// 请求拦截
instance.interceptors.request.use(
config => {
this.queues[url] = true;
if (options.beforeRequest instanceof Function) {
options.beforeRequest({ queues: this.queues, config, options });
}
return config;
},
error => Promise.reject(error),
);
// 响应拦截
instance.interceptors.response.use(
res => {
this.destroy(url);
const { data, status } = res;
return { data, status, statusText: codeMessage[status] };
},
error => {
this.destroy(url);
const errorResult = JSON.parse(JSON.stringify(error));
const errorInfo = error.response;
if (!errorInfo) {
const {
request: { status },
} = errorResult;
errorResult.statusText = codeMessage[status];
if (options.errorHandler instanceof Function) {
options.errorHandler({ queues: this.queues, error, options });
}
}
export default request;
return Promise.reject(errorResult);
},
);
}
request(options) {
const instance = axios.create();
const ops = Object.assign(this.getInsideConfig(), options);
this.interceptors(instance, ops.url, ops);
return instance(ops);
}
}
export default HttpRequest;
import { notification } from 'antd';
import HttpRequest from './kim-request';
import config from '@/config';
const { baseUrl, apiPrefix, headers } = config;
/**
* 异常处理程序
*/
const errorHandler = error => {
const { response } = error;
if (response && response.status) {
const errorText = response.statusText;
const { status, url, code } = response;
notification.error({
key: `notification_${code}`,
message: `请求错误 ${status}: ${url}`,
description: errorText,
});
}
};
const axios = new HttpRequest({
baseUrl,
headers: headers() || {},
errorHandler,
});
const mergeApi = (url, more) => {
if (more && more.apiPrefix && typeof more.apiPrefix === 'string') {
return `${config.apiPrefix}${url}`;
}
if (apiPrefix && typeof apiPrefix === 'string') {
return `${config.apiPrefix}${url}`;
}
return url;
};
const get = (url, data, more = {}) =>
axios.request({
method: 'get', // default
url: `${mergeApi(url, more)}`,
params: data,
...more,
});
const post = (url, data, more = {}) =>
axios.request({
method: 'post', // default
url: `${mergeApi(url, more)}`,
data,
...more,
});
const put = (url, data, more = {}) =>
axios.request({
method: 'put', // default
url: `${mergeApi(url, more)}`,
data,
...more,
});
const del = (url, data, more = {}) =>
axios.request({
method: 'delete', // default
url: `${mergeApi(url, more)}`,
data,
...more,
});
const patch = (url, data, more = {}) =>
axios.request({
method: 'patch', // default
url: `${mergeApi(url, more)}`,
data,
...more,
});
const formDataUpload = (url, data, more = {}) => {
const formData = new FormData();
if (data) {
Object.keys(data).forEach(key => {
formData.append(key, data[key]);
});
}
axios.request({
method: 'post', // default
url: `${mergeApi(url, more)}`,
data: formData,
headers: {
'Content-Type': 'multipart/form-data',
},
...more,
});
};
const uploadFile = (url, data, type = 'formData', more = {}) => {
if (type === 'formData') {
formDataUpload(url, data, more);
}
};
export { axios as request, get, post, put, del, patch, uploadFile };
import config from '@/config';
import engine from 'store/src/store-engine';
import localStorage from 'store/storages/localStorage';
import defaults from 'store/plugins/defaults';
import expire from 'store/plugins/expire';
console.log(config);
const { storeNameSpace } = config;
const storages = [localStorage];
const plugins = [defaults, expire];
if (window && !window.localStorage) {
// eslint-disable-next-line no-console
console.error('localStorage对象不存在');
}
export default engine.createStore(storages, plugins, storeNameSpace);
......@@ -29,6 +29,7 @@
"jest",
"src/setupTests.ts",
"tslint:latest",
"tslint-config-prettier"
"tslint-config-prettier",
"./src/pages/system/*"
]
}
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