Commit 27bbd531 authored by 愚道's avatar 愚道 Committed by Yu

use ant-design-pro components replace @/components

parent bdc92d5c
import React, { Component } from 'react'; import React, { Component } from 'react';
import { MiniArea } from '../Charts'; import { MiniArea } from 'ant-design-pro/lib/Charts';
import NumberInfo from '../NumberInfo'; import NumberInfo from 'ant-design-pro/lib/NumberInfo';
import styles from './index.less'; import styles from './index.less';
......
import CheckPermissions from './CheckPermissions';
const Authorized = ({ children, authority, noMatch = null }) => {
const childrenRender = typeof children === 'undefined' ? null : children;
return CheckPermissions(authority, childrenRender, noMatch);
};
export default Authorized;
import * as React from 'react';
import { RouteProps } from 'react-router';
type authorityFN = (currentAuthority?: string) => boolean;
type authority = string | string[] | authorityFN | Promise<any>;
export interface IAuthorizedRouteProps extends RouteProps {
authority: authority;
}
export { authority };
export class AuthorizedRoute extends React.Component<IAuthorizedRouteProps, any> {}
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import Authorized from './Authorized';
// TODO: umi只会返回render和rest
const AuthorizedRoute = ({ component: Component, render, authority, redirectPath, ...rest }) => (
<Authorized
authority={authority}
noMatch={<Route {...rest} render={() => <Redirect to={{ pathname: redirectPath }} />} />}
>
<Route {...rest} render={props => (Component ? <Component {...props} /> : render(props))} />
</Authorized>
);
export default AuthorizedRoute;
import React from 'react';
import PromiseRender from './PromiseRender';
import { CURRENT } from './renderAuthorize';
function isPromise(obj) {
return (
!!obj &&
(typeof obj === 'object' || typeof obj === 'function') &&
typeof obj.then === 'function'
);
}
/**
* 通用权限检查方法
* Common check permissions method
* @param { 权限判定 Permission judgment type string |array | Promise | Function } authority
* @param { 你的权限 Your permission description type:string} currentAuthority
* @param { 通过的组件 Passing components } target
* @param { 未通过的组件 no pass components } Exception
*/
const checkPermissions = (authority, currentAuthority, target, Exception) => {
// 没有判定权限.默认查看所有
// Retirement authority, return target;
if (!authority) {
return target;
}
// 数组处理
if (Array.isArray(authority)) {
if (authority.indexOf(currentAuthority) >= 0) {
return target;
}
if (Array.isArray(currentAuthority)) {
for (let i = 0; i < currentAuthority.length; i += 1) {
const element = currentAuthority[i];
if (authority.indexOf(element) >= 0) {
return target;
}
}
}
return Exception;
}
// string 处理
if (typeof authority === 'string') {
if (authority === currentAuthority) {
return target;
}
if (Array.isArray(currentAuthority)) {
for (let i = 0; i < currentAuthority.length; i += 1) {
const element = currentAuthority[i];
if (authority === element) {
return target;
}
}
}
return Exception;
}
// Promise 处理
if (isPromise(authority)) {
return <PromiseRender ok={target} error={Exception} promise={authority} />;
}
// Function 处理
if (typeof authority === 'function') {
try {
const bool = authority(currentAuthority);
// 函数执行后返回值是 Promise
if (isPromise(bool)) {
return <PromiseRender ok={target} error={Exception} promise={bool} />;
}
if (bool) {
return target;
}
return Exception;
} catch (error) {
throw error;
}
}
throw new Error('unsupported parameters');
};
export { checkPermissions };
const check = (authority, target, Exception) =>
checkPermissions(authority, CURRENT, target, Exception);
export default check;
import { checkPermissions } from './CheckPermissions';
const target = 'ok';
const error = 'error';
describe('test CheckPermissions', () => {
it('Correct string permission authentication', () => {
expect(checkPermissions('user', 'user', target, error)).toEqual('ok');
});
it('Correct string permission authentication', () => {
expect(checkPermissions('user', 'NULL', target, error)).toEqual('error');
});
it('authority is undefined , return ok', () => {
expect(checkPermissions(null, 'NULL', target, error)).toEqual('ok');
});
it('currentAuthority is undefined , return error', () => {
expect(checkPermissions('admin', null, target, error)).toEqual('error');
});
it('Wrong string permission authentication', () => {
expect(checkPermissions('admin', 'user', target, error)).toEqual('error');
});
it('Correct Array permission authentication', () => {
expect(checkPermissions(['user', 'admin'], 'user', target, error)).toEqual('ok');
});
it('Wrong Array permission authentication,currentAuthority error', () => {
expect(checkPermissions(['user', 'admin'], 'user,admin', target, error)).toEqual('error');
});
it('Wrong Array permission authentication', () => {
expect(checkPermissions(['user', 'admin'], 'guest', target, error)).toEqual('error');
});
it('Wrong Function permission authentication', () => {
expect(checkPermissions(() => false, 'guest', target, error)).toEqual('error');
});
it('Correct Function permission authentication', () => {
expect(checkPermissions(() => true, 'guest', target, error)).toEqual('ok');
});
it('authority is string, currentAuthority is array, return ok', () => {
expect(checkPermissions('user', ['user'], target, error)).toEqual('ok');
});
it('authority is string, currentAuthority is array, return ok', () => {
expect(checkPermissions('user', ['user', 'admin'], target, error)).toEqual('ok');
});
it('authority is array, currentAuthority is array, return ok', () => {
expect(checkPermissions(['user', 'admin'], ['user', 'admin'], target, error)).toEqual('ok');
});
it('Wrong Function permission authentication', () => {
expect(checkPermissions(() => false, ['user'], target, error)).toEqual('error');
});
it('Correct Function permission authentication', () => {
expect(checkPermissions(() => true, ['user'], target, error)).toEqual('ok');
});
it('authority is undefined , return ok', () => {
expect(checkPermissions(null, ['user'], target, error)).toEqual('ok');
});
});
import React from 'react';
import { Spin } from 'antd';
export default class PromiseRender extends React.PureComponent {
state = {
component: null,
};
componentDidMount() {
this.setRenderComponent(this.props);
}
componentDidUpdate(nextProps) {
// new Props enter
this.setRenderComponent(nextProps);
}
// set render Component : ok or error
setRenderComponent(props) {
const ok = this.checkIsInstantiation(props.ok);
const error = this.checkIsInstantiation(props.error);
props.promise
.then(() => {
this.setState({
component: ok,
});
})
.catch(() => {
this.setState({
component: error,
});
});
}
// Determine whether the incoming component has been instantiated
// AuthorizedRoute is already instantiated
// Authorized render is already instantiated, children is no instantiated
// Secured is not instantiated
checkIsInstantiation = target => {
if (!React.isValidElement(target)) {
return target;
}
return () => target;
};
render() {
const { component: Component } = this.state;
const { ok, error, promise, ...rest } = this.props;
return Component ? (
<Component {...rest} />
) : (
<div
style={{
width: '100%',
height: '100%',
margin: 'auto',
paddingTop: 50,
textAlign: 'center',
}}
>
<Spin size="large" />
</div>
);
}
}
import React from 'react';
import Exception from '../Exception';
import CheckPermissions from './CheckPermissions';
/**
* 默认不能访问任何页面
* default is "NULL"
*/
const Exception403 = () => <Exception type="403" />;
// Determine whether the incoming component has been instantiated
// AuthorizedRoute is already instantiated
// Authorized render is already instantiated, children is no instantiated
// Secured is not instantiated
const checkIsInstantiation = target => {
if (!React.isValidElement(target)) {
return target;
}
return () => target;
};
/**
* 用于判断是否拥有权限访问此view权限
* authority 支持传入 string, function:()=>boolean|Promise
* e.g. 'user' 只有user用户能访问
* e.g. 'user,admin' user和 admin 都能访问
* e.g. ()=>boolean 返回true能访问,返回false不能访问
* e.g. Promise then 能访问 catch不能访问
* e.g. authority support incoming string, function: () => boolean | Promise
* e.g. 'user' only user user can access
* e.g. 'user, admin' user and admin can access
* e.g. () => boolean true to be able to visit, return false can not be accessed
* e.g. Promise then can not access the visit to catch
* @param {string | function | Promise} authority
* @param {ReactNode} error 非必需参数
*/
const authorize = (authority, error) => {
/**
* conversion into a class
* 防止传入字符串时找不到staticContext造成报错
* String parameters can cause staticContext not found error
*/
let classError = false;
if (error) {
classError = () => error;
}
if (!authority) {
throw new Error('authority is required');
}
return function decideAuthority(target) {
const component = CheckPermissions(authority, target, classError || Exception403);
return checkIsInstantiation(component);
};
};
export default authorize;
---
order: 1
title:
zh-CN: 使用数组作为参数
en-US: Use Array as a parameter
---
Use Array as a parameter
```jsx
import RenderAuthorized from 'ant-design-pro/lib/Authorized';
import { Alert } from 'antd';
const Authorized = RenderAuthorized('user');
const noMatch = <Alert message="No permission." type="error" showIcon />;
ReactDOM.render(
<Authorized authority={['user', 'admin']} noMatch={noMatch}>
<Alert message="Use Array as a parameter passed!" type="success" showIcon />
</Authorized>,
mountNode,
);
```
---
order: 2
title:
zh-CN: 使用方法作为参数
en-US: Use function as a parameter
---
Use Function as a parameter
```jsx
import RenderAuthorized from 'ant-design-pro/lib/Authorized';
import { Alert } from 'antd';
const Authorized = RenderAuthorized('user');
const noMatch = <Alert message="No permission." type="error" showIcon />;
const havePermission = () => {
return false;
};
ReactDOM.render(
<Authorized authority={havePermission} noMatch={noMatch}>
<Alert
message="Use Function as a parameter passed!"
type="success"
showIcon
/>
</Authorized>,
mountNode,
);
```
---
order: 0
title:
zh-CN: 基本使用
en-US: Basic use
---
Basic use
```jsx
import RenderAuthorized from 'ant-design-pro/lib/Authorized';
import { Alert } from 'antd';
const Authorized = RenderAuthorized('user');
const noMatch = <Alert message="No permission." type="error" showIcon />;
ReactDOM.render(
<div>
<Authorized authority="admin" noMatch={noMatch}>
<Alert message="user Passed!" type="success" showIcon />
</Authorized>
</div>,
mountNode,
);
```
---
order: 3
title:
zh-CN: 注解基本使用
en-US: Basic use secured
---
secured demo used
```jsx
import RenderAuthorized from 'ant-design-pro/lib/Authorized';
import { Alert } from 'antd';
const { Secured } = RenderAuthorized('user');
@Secured('admin')
class TestSecuredString extends React.Component {
render() {
<Alert message="user Passed!" type="success" showIcon />;
}
}
ReactDOM.render(
<div>
<TestSecuredString />
</div>,
mountNode,
);
```
import * as React from 'react';
import AuthorizedRoute, { authority } from './AuthorizedRoute';
export type IReactComponent<P = any> =
| React.StatelessComponent<P>
| React.ComponentClass<P>
| React.ClassicComponentClass<P>;
type Secured = (
authority: authority,
error?: React.ReactNode
) => <T extends IReactComponent>(target: T) => T;
type check = <T extends IReactComponent, S extends IReactComponent>(
authority: authority,
target: T,
Exception: S
) => T | S;
export interface IAuthorizedProps {
authority: authority;
noMatch?: React.ReactNode;
}
export class Authorized extends React.Component<IAuthorizedProps, any> {
public static Secured: Secured;
public static AuthorizedRoute: typeof AuthorizedRoute;
public static check: check;
}
declare function renderAuthorize(currentAuthority: string): typeof Authorized;
export default renderAuthorize;
import Authorized from './Authorized';
import AuthorizedRoute from './AuthorizedRoute';
import Secured from './Secured';
import check from './CheckPermissions';
import renderAuthorize from './renderAuthorize';
Authorized.Secured = Secured;
Authorized.AuthorizedRoute = AuthorizedRoute;
Authorized.check = check;
export default renderAuthorize(Authorized);
---
title:
en-US: Authorized
zh-CN: Authorized
subtitle: 权限
cols: 1
order: 15
---
权限组件,通过比对现有权限与准入权限,决定相关元素的展示。
## API
### RenderAuthorized
`RenderAuthorized: (currentAuthority: string | () => string) => Authorized`
权限组件默认 export RenderAuthorized 函数,它接收当前权限作为参数,返回一个权限对象,该对象提供以下几种使用方式。
### Authorized
最基础的权限控制。
| 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------|
| children | 正常渲染的元素,权限判断通过时展示 | ReactNode | - |
| authority | 准入权限/权限判断 | `string | array | Promise | (currentAuthority) => boolean | Promise` | - |
| noMatch | 权限异常渲染元素,权限判断不通过时展示 | ReactNode | - |
### Authorized.AuthorizedRoute
| 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------|
| authority | 准入权限/权限判断 | `string | array | Promise | (currentAuthority) => boolean | Promise` | - |
| redirectPath | 权限异常时重定向的页面路由 | string | - |
其余参数与 `Route` 相同。
### Authorized.Secured
注解方式,`@Authorized.Secured(authority, error)`
| 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------|
| authority | 准入权限/权限判断 | `string | Promise | (currentAuthority) => boolean | Promise` | - |
| error | 权限异常时渲染元素 | ReactNode | <Exception type="403" /> |
### Authorized.check
函数形式的 Authorized,用于某些不能被 HOC 包裹的组件。 `Authorized.check(authority, target, Exception)`
注意:传入一个 Promise 时,无论正确还是错误返回的都是一个 ReactClass。
| 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------|
| authority | 准入权限/权限判断 | `string | Promise | (currentAuthority) => boolean | Promise` | - |
| target | 权限判断通过时渲染的元素 | ReactNode | - |
| Exception | 权限异常时渲染元素 | ReactNode | - |
/* eslint-disable import/no-mutable-exports */
let CURRENT = 'NULL';
/**
* use authority or getAuthority
* @param {string|()=>String} currentAuthority
*/
const renderAuthorize = Authorized => currentAuthority => {
if (currentAuthority) {
if (typeof currentAuthority === 'function') {
CURRENT = currentAuthority();
}
if (
Object.prototype.toString.call(currentAuthority) === '[object String]' ||
Array.isArray(currentAuthority)
) {
CURRENT = currentAuthority;
}
} else {
CURRENT = 'NULL';
}
return Authorized;
};
export { CURRENT };
export default Authorized => renderAuthorize(Authorized);
import * as React from 'react';
export interface IAvatarItemProps {
tips: React.ReactNode;
src: string;
style?: React.CSSProperties;
}
export default class AvatarItem extends React.Component<IAvatarItemProps, any> {
constructor(props: IAvatarItemProps);
}
---
order: 0
title:
zh-CN: 要显示的最大项目
en-US: Max Items to Show
---
`maxLength` attribute specifies the maximum number of items to show while `excessItemsStyle` style the excess
item component.
````jsx
import AvatarList from 'ant-design-pro/lib/AvatarList';
ReactDOM.render(
<AvatarList size="mini" maxLength={3} excessItemsStyle={{ color: '#f56a00', backgroundColor: '#fde3cf' }}>
<AvatarList.Item tips="Jake" src="https://gw.alipayobjects.com/zos/rmsportal/zOsKZmFRdUtvpqCImOVY.png" />
<AvatarList.Item tips="Andy" src="https://gw.alipayobjects.com/zos/rmsportal/sfjbOqnsXXJgNCjCzDBL.png" />
<AvatarList.Item tips="Niko" src="https://gw.alipayobjects.com/zos/rmsportal/kZzEzemZyKLKFsojXItE.png" />
<AvatarList.Item tips="Niko" src="https://gw.alipayobjects.com/zos/rmsportal/kZzEzemZyKLKFsojXItE.png" />
<AvatarList.Item tips="Niko" src="https://gw.alipayobjects.com/zos/rmsportal/kZzEzemZyKLKFsojXItE.png" />
<AvatarList.Item tips="Niko" src="https://gw.alipayobjects.com/zos/rmsportal/kZzEzemZyKLKFsojXItE.png" />
</AvatarList>
, mountNode);
````
---
order: 0
title:
zh-CN: 基础样例
en-US: Basic Usage
---
Simplest of usage.
````jsx
import AvatarList from 'ant-design-pro/lib/AvatarList';
ReactDOM.render(
<AvatarList size="mini">
<AvatarList.Item tips="Jake" src="https://gw.alipayobjects.com/zos/rmsportal/zOsKZmFRdUtvpqCImOVY.png" />
<AvatarList.Item tips="Andy" src="https://gw.alipayobjects.com/zos/rmsportal/sfjbOqnsXXJgNCjCzDBL.png" />
<AvatarList.Item tips="Niko" src="https://gw.alipayobjects.com/zos/rmsportal/kZzEzemZyKLKFsojXItE.png" />
</AvatarList>
, mountNode);
````
import * as React from 'react';
import AvatarItem from './AvatarItem';
export interface IAvatarListProps {
size?: 'large' | 'small' | 'mini' | 'default';
maxLength?: number;
excessItemsStyle?: React.CSSProperties;
style?: React.CSSProperties;
children: React.ReactElement<AvatarItem> | Array<React.ReactElement<AvatarItem>>;
}
export default class AvatarList extends React.Component<IAvatarListProps, any> {
public static Item: typeof AvatarItem;
}
---
title: AvatarList
order: 1
cols: 1
---
A list of user's avatar for project or group member list frequently. If a large or small AvatarList is desired, set the `size` property to either `large` or `small` and `mini` respectively. Omit the `size` property for a AvatarList with the default size.
## API
### AvatarList
| Property | Description | Type | Default |
| ---------------- | --------------------- | ---------------------------------- | --------- |
| size | size of list | `large``small``mini`, `default` | `default` |
| maxLength | max items to show | number | - |
| excessItemsStyle | the excess item style | CSSProperties | - |
### AvatarList.Item
| Property | Description | Type | Default |
| -------- | -------------------------------------------- | --------- | ------- |
| tips | title tips for avatar item | ReactNode | - |
| src | the address of the image for an image avatar | string | - |
import React from 'react';
import { Tooltip, Avatar } from 'antd';
import classNames from 'classnames';
import styles from './index.less';
const avatarSizeToClassName = size =>
classNames(styles.avatarItem, {
[styles.avatarItemLarge]: size === 'large',
[styles.avatarItemSmall]: size === 'small',
[styles.avatarItemMini]: size === 'mini',
});
const AvatarList = ({ children, size, maxLength, excessItemsStyle, ...other }) => {
const numOfChildren = React.Children.count(children);
const numToShow = maxLength >= numOfChildren ? numOfChildren : maxLength;
const childrenWithProps = React.Children.toArray(children)
.slice(0, numToShow)
.map(child =>
React.cloneElement(child, {
size,
})
);
if (numToShow < numOfChildren) {
const cls = avatarSizeToClassName(size);
childrenWithProps.push(
<li key="exceed" className={cls}>
<Avatar size={size} style={excessItemsStyle}>{`+${numOfChildren - maxLength}`}</Avatar>
</li>
);
}
return (
<div {...other} className={styles.avatarList}>
<ul> {childrenWithProps} </ul>
</div>
);
};
const Item = ({ src, size, tips, onClick = () => {} }) => {
const cls = avatarSizeToClassName(size);
return (
<li className={cls} onClick={onClick}>
{tips ? (
<Tooltip title={tips}>
<Avatar src={src} size={size} style={{ cursor: 'pointer' }} />
</Tooltip>
) : (
<Avatar src={src} size={size} />
)}
</li>
);
};
AvatarList.Item = Item;
export default AvatarList;
@import '~antd/lib/style/themes/default.less';
.avatarList {
display: inline-block;
ul {
display: inline-block;
margin-left: 8px;
font-size: 0;
}
}
.avatarItem {
display: inline-block;
font-size: @font-size-base;
margin-left: -8px;
width: @avatar-size-base;
height: @avatar-size-base;
:global {
.ant-avatar {
border: 1px solid #fff;
}
}
}
.avatarItemLarge {
width: @avatar-size-lg;
height: @avatar-size-lg;
}
.avatarItemSmall {
width: @avatar-size-sm;
height: @avatar-size-sm;
}
.avatarItemMini {
width: 20px;
height: 20px;
:global {
.ant-avatar {
width: 20px;
height: 20px;
line-height: 20px;
.ant-avatar-string {
font-size: 12px;
line-height: 18px;
}
}
}
}
import React from 'react';
import range from 'lodash/range';
import { mount } from 'enzyme';
import AvatarList from './index';
const renderItems = numItems =>
range(numItems).map(i => (
<AvatarList.Item
key={i}
tips="Jake"
src="https://gw.alipayobjects.com/zos/rmsportal/zOsKZmFRdUtvpqCImOVY.png"
/>
));
describe('AvatarList', () => {
it('renders all items', () => {
const wrapper = mount(<AvatarList>{renderItems(4)}</AvatarList>);
expect(wrapper.find('AvatarList').length).toBe(1);
expect(wrapper.find('Item').length).toBe(4);
expect(wrapper.findWhere(node => node.key() === 'exceed').length).toBe(0);
});
it('renders max of 3 items', () => {
const wrapper = mount(<AvatarList maxLength={3}>{renderItems(4)}</AvatarList>);
expect(wrapper.find('AvatarList').length).toBe(1);
expect(wrapper.find('Item').length).toBe(3);
expect(wrapper.findWhere(node => node.key() === 'exceed').length).toBe(1);
});
});
---
title: AvatarList
subtitle: 用户头像列表
order: 1
cols: 1
---
一组用户头像,常用在项目/团队成员列表。可通过设置 `size` 属性来指定头像大小。
## API
### AvatarList
| 参数 | 说明 | 类型 | 默认值 |
| ---------------- | -------- | ---------------------------------- | --------- |
| size | 头像大小 | `large``small``mini`, `default` | `default` |
| maxLength | 要显示的最大项目 | number | - |
| excessItemsStyle | 多余的项目风格 | CSSProperties | - |
### AvatarList.Item
| 参数 | 说明 | 类型 | 默认值 |
| ---- | ------ | --------- | --- |
| tips | 头像展示文案 | ReactNode | - |
| src | 头像图片连接 | string | - |
import * as React from 'react';
export interface IBarProps {
title: React.ReactNode;
color?: string;
padding?: [number, number, number, number];
height: number;
data: Array<{
x: string;
y: number;
}>;
autoLabel?: boolean;
style?: React.CSSProperties;
}
export default class Bar extends React.Component<IBarProps, any> {}
import React, { Component } from 'react';
import { Chart, Axis, Tooltip, Geom } from 'bizcharts';
import Debounce from 'lodash-decorators/debounce';
import Bind from 'lodash-decorators/bind';
import autoHeight from '../autoHeight';
import styles from '../index.less';
@autoHeight()
class Bar extends Component {
state = {
autoHideXLabels: false,
};
componentDidMount() {
window.addEventListener('resize', this.resize, { passive: true });
}
componentWillUnmount() {
window.removeEventListener('resize', this.resize);
}
handleRoot = n => {
this.root = n;
};
handleRef = n => {
this.node = n;
};
@Bind()
@Debounce(400)
resize() {
if (!this.node) {
return;
}
const canvasWidth = this.node.parentNode.clientWidth;
const { data = [], autoLabel = true } = this.props;
if (!autoLabel) {
return;
}
const minWidth = data.length * 30;
const { autoHideXLabels } = this.state;
if (canvasWidth <= minWidth) {
if (!autoHideXLabels) {
this.setState({
autoHideXLabels: true,
});
}
} else if (autoHideXLabels) {
this.setState({
autoHideXLabels: false,
});
}
}
render() {
const {
height,
title,
forceFit = true,
data,
color = 'rgba(24, 144, 255, 0.85)',
padding,
} = this.props;
const { autoHideXLabels } = this.state;
const scale = {
x: {
type: 'cat',
},
y: {
min: 0,
},
};
const tooltip = [
'x*y',
(x, y) => ({
name: x,
value: y,
}),
];
return (
<div className={styles.chart} style={{ height }} ref={this.handleRoot}>
<div ref={this.handleRef}>
{title && <h4 style={{ marginBottom: 20 }}>{title}</h4>}
<Chart
scale={scale}
height={title ? height - 41 : height}
forceFit={forceFit}
data={data}
padding={padding || 'auto'}
>
<Axis
name="x"
title={false}
label={autoHideXLabels ? false : {}}
tickLine={autoHideXLabels ? false : {}}
/>
<Axis name="y" min={0} />
<Tooltip showTitle={false} crosshairs={false} />
<Geom type="interval" position="x*y" color={color} tooltip={tooltip} />
</Chart>
</div>
</div>
);
}
}
export default Bar;
import { CardProps } from 'antd/lib/card';
import * as React from 'react';
export interface IChartCardProps extends CardProps {
title: React.ReactNode;
action?: React.ReactNode;
total?: React.ReactNode | number | (() => React.ReactNode | number);
footer?: React.ReactNode;
contentHeight?: number;
avatar?: React.ReactNode;
style?: React.CSSProperties;
}
export default class ChartCard extends React.Component<IChartCardProps, any> {}
import React from 'react';
import { Card } from 'antd';
import classNames from 'classnames';
import styles from './index.less';
const renderTotal = total => {
let totalDom;
switch (typeof total) {
case 'undefined':
totalDom = null;
break;
case 'function':
totalDom = <div className={styles.total}>{total()}</div>;
break;
default:
totalDom = <div className={styles.total}>{total}</div>;
}
return totalDom;
};
class ChartCard extends React.PureComponent {
renderConnet = () => {
const { contentHeight, title, avatar, action, total, footer, children, loading } = this.props;
if (loading) {
return false;
}
return (
<div className={styles.chartCard}>
<div
className={classNames(styles.chartTop, {
[styles.chartTopMargin]: !children && !footer,
})}
>
<div className={styles.avatar}>{avatar}</div>
<div className={styles.metaWrap}>
<div className={styles.meta}>
<span className={styles.title}>{title}</span>
<span className={styles.action}>{action}</span>
</div>
{renderTotal(total)}
</div>
</div>
{children && (
<div className={styles.content} style={{ height: contentHeight || 'auto' }}>
<div className={contentHeight && styles.contentFixed}>{children}</div>
</div>
)}
{footer && (
<div
className={classNames(styles.footer, {
[styles.footerMargin]: !children,
})}
>
{footer}
</div>
)}
</div>
);
};
render() {
const {
loading = false,
contentHeight,
title,
avatar,
action,
total,
footer,
children,
...rest
} = this.props;
return (
<Card loading={loading} bodyStyle={{ padding: '20px 24px 8px 24px' }} {...rest}>
{this.renderConnet()}
</Card>
);
}
}
export default ChartCard;
@import '~antd/lib/style/themes/default.less';
.chartCard {
position: relative;
.chartTop {
position: relative;
overflow: hidden;
width: 100%;
}
.chartTopMargin {
margin-bottom: 12px;
}
.chartTopHasMargin {
margin-bottom: 20px;
}
.metaWrap {
float: left;
}
.avatar {
position: relative;
top: 4px;
float: left;
margin-right: 20px;
img {
border-radius: 100%;
}
}
.meta {
color: @text-color-secondary;
font-size: @font-size-base;
line-height: 22px;
height: 22px;
}
.action {
cursor: pointer;
position: absolute;
top: 4px;
right: 0;
line-height: 1;
}
.total {
overflow: hidden;
text-overflow: ellipsis;
word-break: break-all;
white-space: nowrap;
color: @heading-color;
margin-top: 4px;
margin-bottom: 0;
font-size: 30px;
line-height: 38px;
height: 38px;
}
.content {
margin-bottom: 12px;
position: relative;
width: 100%;
}
.contentFixed {
position: absolute;
left: 0;
bottom: 0;
width: 100%;
}
.footer {
border-top: 1px solid @border-color-split;
padding-top: 9px;
margin-top: 8px;
& > * {
position: relative;
}
}
.footerMargin {
margin-top: 20px;
}
}
import * as React from 'react';
export interface IFieldProps {
label: React.ReactNode;
value: React.ReactNode;
style?: React.CSSProperties;
}
export default class Field extends React.Component<IFieldProps, any> {}
import React from 'react';
import styles from './index.less';
const Field = ({ label, value, ...rest }) => (
<div className={styles.field} {...rest}>
<span className={styles.label}>{label}</span>
<span className={styles.number}>{value}</span>
</div>
);
export default Field;
@import '~antd/lib/style/themes/default.less';
.field {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
margin: 0;
.label,
.number {
font-size: @font-size-base;
line-height: 22px;
}
.number {
color: @heading-color;
margin-left: 8px;
}
}
import * as React from 'react';
export interface IGaugeProps {
title: React.ReactNode;
color?: string;
height: number;
bgColor?: number;
percent: number;
style?: React.CSSProperties;
}
export default class Gauge extends React.Component<IGaugeProps, any> {}
import React from 'react';
import { Chart, Geom, Axis, Coord, Guide, Shape } from 'bizcharts';
import autoHeight from '../autoHeight';
const { Arc, Html, Line } = Guide;
const defaultFormatter = val => {
switch (val) {
case '2':
return '';
case '4':
return '';
case '6':
return '';
case '8':
return '';
default:
return '';
}
};
Shape.registerShape('point', 'pointer', {
drawShape(cfg, group) {
let point = cfg.points[0];
point = this.parsePoint(point);
const center = this.parsePoint({
x: 0,
y: 0,
});
group.addShape('line', {
attrs: {
x1: center.x,
y1: center.y,
x2: point.x,
y2: point.y,
stroke: cfg.color,
lineWidth: 2,
lineCap: 'round',
},
});
return group.addShape('circle', {
attrs: {
x: center.x,
y: center.y,
r: 6,
stroke: cfg.color,
lineWidth: 3,
fill: '#fff',
},
});
},
});
@autoHeight()
class Gauge extends React.Component {
render() {
const {
title,
height,
percent,
forceFit = true,
formatter = defaultFormatter,
color = '#2F9CFF',
bgColor = '#F0F2F5',
} = this.props;
const cols = {
value: {
type: 'linear',
min: 0,
max: 10,
tickCount: 6,
nice: true,
},
};
const data = [{ value: percent / 10 }];
return (
<Chart height={height} data={data} scale={cols} padding={[-16, 0, 16, 0]} forceFit={forceFit}>
<Coord type="polar" startAngle={-1.25 * Math.PI} endAngle={0.25 * Math.PI} radius={0.8} />
<Axis name="1" line={null} />
<Axis
line={null}
tickLine={null}
subTickLine={null}
name="value"
zIndex={2}
gird={null}
label={{
offset: -12,
formatter,
textStyle: {
fontSize: 12,
fill: 'rgba(0, 0, 0, 0.65)',
textAlign: 'center',
},
}}
/>
<Guide>
<Line
start={[3, 0.905]}
end={[3, 0.85]}
lineStyle={{
stroke: color,
lineDash: null,
lineWidth: 2,
}}
/>
<Line
start={[5, 0.905]}
end={[5, 0.85]}
lineStyle={{
stroke: color,
lineDash: null,
lineWidth: 3,
}}
/>
<Line
start={[7, 0.905]}
end={[7, 0.85]}
lineStyle={{
stroke: color,
lineDash: null,
lineWidth: 3,
}}
/>
<Arc
zIndex={0}
start={[0, 0.965]}
end={[10, 0.965]}
style={{
stroke: bgColor,
lineWidth: 10,
}}
/>
<Arc
zIndex={1}
start={[0, 0.965]}
end={[data[0].value, 0.965]}
style={{
stroke: color,
lineWidth: 10,
}}
/>
<Html
position={['50%', '95%']}
html={() => `
<div style="width: 300px;text-align: center;font-size: 12px!important;">
<p style="font-size: 14px; color: rgba(0,0,0,0.43);margin: 0;">${title}</p>
<p style="font-size: 24px;color: rgba(0,0,0,0.85);margin: 0;">
${data[0].value * 10}%
</p>
</div>`}
/>
</Guide>
<Geom
line={false}
type="point"
position="value*1"
shape="pointer"
color={color}
active={false}
/>
</Chart>
);
}
}
export default Gauge;
import * as React from 'react';
// g2已经更新到3.0
// 不带的写了
export interface IAxis {
title: any;
line: any;
gridAlign: any;
labels: any;
tickLine: any;
grid: any;
}
export interface IMiniAreaProps {
color?: string;
height: number;
borderColor?: string;
line?: boolean;
animate?: boolean;
xAxis?: IAxis;
yAxis?: IAxis;
data: Array<{
x: number | string;
y: number;
}>;
}
export default class MiniArea extends React.Component<IMiniAreaProps, any> {}
import React from 'react';
import { Chart, Axis, Tooltip, Geom } from 'bizcharts';
import autoHeight from '../autoHeight';
import styles from '../index.less';
@autoHeight()
class MiniArea extends React.PureComponent {
render() {
const {
height,
data = [],
forceFit = true,
color = 'rgba(24, 144, 255, 0.2)',
borderColor = '#1089ff',
scale = {},
borderWidth = 2,
line,
xAxis,
yAxis,
animate = true,
} = this.props;
const padding = [36, 5, 30, 5];
const scaleProps = {
x: {
type: 'cat',
range: [0, 1],
...scale.x,
},
y: {
min: 0,
...scale.y,
},
};
const tooltip = [
'x*y',
(x, y) => ({
name: x,
value: y,
}),
];
const chartHeight = height + 54;
return (
<div className={styles.miniChart} style={{ height }}>
<div className={styles.chartContent}>
{height > 0 && (
<Chart
animate={animate}
scale={scaleProps}
height={chartHeight}
forceFit={forceFit}
data={data}
padding={padding}
>
<Axis
key="axis-x"
name="x"
label={false}
line={false}
tickLine={false}
grid={false}
{...xAxis}
/>
<Axis
key="axis-y"
name="y"
label={false}
line={false}
tickLine={false}
grid={false}
{...yAxis}
/>
<Tooltip showTitle={false} crosshairs={false} />
<Geom
type="area"
position="x*y"
color={color}
tooltip={tooltip}
shape="smooth"
style={{
fillOpacity: 1,
}}
/>
{line ? (
<Geom
type="line"
position="x*y"
shape="smooth"
color={borderColor}
size={borderWidth}
tooltip={false}
/>
) : (
<span style={{ display: 'none' }} />
)}
</Chart>
)}
</div>
</div>
);
}
}
export default MiniArea;
import * as React from 'react';
export interface IMiniBarProps {
color?: string;
height: number;
data: Array<{
x: number | string;
y: number;
}>;
style?: React.CSSProperties;
}
export default class MiniBar extends React.Component<IMiniBarProps, any> {}
import React from 'react';
import { Chart, Tooltip, Geom } from 'bizcharts';
import autoHeight from '../autoHeight';
import styles from '../index.less';
@autoHeight()
class MiniBar extends React.Component {
render() {
const { height, forceFit = true, color = '#1890FF', data = [] } = this.props;
const scale = {
x: {
type: 'cat',
},
y: {
min: 0,
},
};
const padding = [36, 5, 30, 5];
const tooltip = [
'x*y',
(x, y) => ({
name: x,
value: y,
}),
];
// for tooltip not to be hide
const chartHeight = height + 54;
return (
<div className={styles.miniChart} style={{ height }}>
<div className={styles.chartContent}>
<Chart
scale={scale}
height={chartHeight}
forceFit={forceFit}
data={data}
padding={padding}
>
<Tooltip showTitle={false} crosshairs={false} />
<Geom type="interval" position="x*y" color={color} tooltip={tooltip} />
</Chart>
</div>
</div>
);
}
}
export default MiniBar;
import * as React from 'react';
export interface IMiniProgressProps {
target: number;
color?: string;
strokeWidth?: number;
percent?: number;
style?: React.CSSProperties;
}
export default class MiniProgress extends React.Component<IMiniProgressProps, any> {}
import React from 'react';
import { Tooltip } from 'antd';
import styles from './index.less';
const MiniProgress = ({ target, color = 'rgb(19, 194, 194)', strokeWidth, percent }) => (
<div className={styles.miniProgress}>
<Tooltip title={`目标值: ${target}%`}>
<div className={styles.target} style={{ left: target ? `${target}%` : null }}>
<span style={{ backgroundColor: color || null }} />
<span style={{ backgroundColor: color || null }} />
</div>
</Tooltip>
<div className={styles.progressWrap}>
<div
className={styles.progress}
style={{
backgroundColor: color || null,
width: percent ? `${percent}%` : null,
height: strokeWidth || null,
}}
/>
</div>
</div>
);
export default MiniProgress;
@import '~antd/lib/style/themes/default.less';
.miniProgress {
padding: 5px 0;
position: relative;
width: 100%;
.progressWrap {
background-color: @background-color-base;
position: relative;
}
.progress {
transition: all 0.4s cubic-bezier(0.08, 0.82, 0.17, 1) 0s;
border-radius: 1px 0 0 1px;
background-color: @primary-color;
width: 0;
height: 100%;
}
.target {
position: absolute;
top: 0;
bottom: 0;
span {
border-radius: 100px;
position: absolute;
top: 0;
left: 0;
height: 4px;
width: 2px;
}
span:last-child {
top: auto;
bottom: 0;
}
}
}
import * as React from 'react';
export interface IPieProps {
animate?: boolean;
color?: string;
colors?: string[];
height: number;
hasLegend?: boolean;
padding?: [number, number, number, number];
percent?: number;
data?: Array<{
x: string | string;
y: number;
}>;
total?: React.ReactNode | number | (() => React.ReactNode | number);
title?: React.ReactNode;
tooltip?: boolean;
valueFormat?: (value: string) => string | React.ReactNode;
subTitle?: React.ReactNode;
}
export default class Pie extends React.Component<IPieProps, any> {}
import React, { Component } from 'react';
import { Chart, Tooltip, Geom, Coord } from 'bizcharts';
import { DataView } from '@antv/data-set';
import { Divider } from 'antd';
import classNames from 'classnames';
import ReactFitText from 'react-fittext';
import Debounce from 'lodash-decorators/debounce';
import Bind from 'lodash-decorators/bind';
import autoHeight from '../autoHeight';
import styles from './index.less';
/* eslint react/no-danger:0 */
@autoHeight()
class Pie extends Component {
state = {
legendData: [],
legendBlock: false,
};
componentDidMount() {
window.addEventListener(
'resize',
() => {
this.requestRef = requestAnimationFrame(() => this.resize());
},
{ passive: true }
);
}
componentDidUpdate(preProps) {
const { data } = this.props;
if (data !== preProps.data) {
// because of charts data create when rendered
// so there is a trick for get rendered time
this.getLegendData();
}
}
componentWillUnmount() {
window.cancelAnimationFrame(this.requestRef);
window.removeEventListener('resize', this.resize);
this.resize.cancel();
}
getG2Instance = chart => {
this.chart = chart;
requestAnimationFrame(() => {
this.getLegendData();
this.resize();
});
};
// for custom lengend view
getLegendData = () => {
if (!this.chart) return;
const geom = this.chart.getAllGeoms()[0]; // 获取所有的图形
if (!geom) return;
const items = geom.get('dataArray') || []; // 获取图形对应的
const legendData = items.map(item => {
/* eslint no-underscore-dangle:0 */
const origin = item[0]._origin;
origin.color = item[0].color;
origin.checked = true;
return origin;
});
this.setState({
legendData,
});
};
handleRoot = n => {
this.root = n;
};
handleLegendClick = (item, i) => {
const newItem = item;
newItem.checked = !newItem.checked;
const { legendData } = this.state;
legendData[i] = newItem;
const filteredLegendData = legendData.filter(l => l.checked).map(l => l.x);
if (this.chart) {
this.chart.filter('x', val => filteredLegendData.indexOf(val) > -1);
}
this.setState({
legendData,
});
};
// for window resize auto responsive legend
@Bind()
@Debounce(300)
resize() {
const { hasLegend } = this.props;
const { legendBlock } = this.state;
if (!hasLegend || !this.root) {
window.removeEventListener('resize', this.resize);
return;
}
if (this.root.parentNode.clientWidth <= 380) {
if (!legendBlock) {
this.setState({
legendBlock: true,
});
}
} else if (legendBlock) {
this.setState({
legendBlock: false,
});
}
}
render() {
const {
valueFormat,
subTitle,
total,
hasLegend = false,
className,
style,
height,
forceFit = true,
percent,
color,
inner = 0.75,
animate = true,
colors,
lineWidth = 1,
} = this.props;
const { legendData, legendBlock } = this.state;
const pieClassName = classNames(styles.pie, className, {
[styles.hasLegend]: !!hasLegend,
[styles.legendBlock]: legendBlock,
});
const {
data: propsData,
selected: propsSelected = true,
tooltip: propsTooltip = true,
} = this.props;
let data = propsData || [];
let selected = propsSelected;
let tooltip = propsTooltip;
const defaultColors = colors;
data = data || [];
selected = selected || true;
tooltip = tooltip || true;
let formatColor;
const scale = {
x: {
type: 'cat',
range: [0, 1],
},
y: {
min: 0,
},
};
if (percent || percent === 0) {
selected = false;
tooltip = false;
formatColor = value => {
if (value === '占比') {
return color || 'rgba(24, 144, 255, 0.85)';
}
return '#F0F2F5';
};
data = [
{
x: '占比',
y: parseFloat(percent),
},
{
x: '反比',
y: 100 - parseFloat(percent),
},
];
}
const tooltipFormat = [
'x*percent',
(x, p) => ({
name: x,
value: `${(p * 100).toFixed(2)}%`,
}),
];
const padding = [12, 0, 12, 0];
const dv = new DataView();
dv.source(data).transform({
type: 'percent',
field: 'y',
dimension: 'x',
as: 'percent',
});
return (
<div ref={this.handleRoot} className={pieClassName} style={style}>
<ReactFitText maxFontSize={25}>
<div className={styles.chart}>
<Chart
scale={scale}
height={height}
forceFit={forceFit}
data={dv}
padding={padding}
animate={animate}
onGetG2Instance={this.getG2Instance}
>
{!!tooltip && <Tooltip showTitle={false} />}
<Coord type="theta" innerRadius={inner} />
<Geom
style={{ lineWidth, stroke: '#fff' }}
tooltip={tooltip && tooltipFormat}
type="intervalStack"
position="percent"
color={['x', percent || percent === 0 ? formatColor : defaultColors]}
selected={selected}
/>
</Chart>
{(subTitle || total) && (
<div className={styles.total}>
{subTitle && <h4 className="pie-sub-title">{subTitle}</h4>}
{/* eslint-disable-next-line */}
{total && (
<div className="pie-stat">{typeof total === 'function' ? total() : total}</div>
)}
</div>
)}
</div>
</ReactFitText>
{hasLegend && (
<ul className={styles.legend}>
{legendData.map((item, i) => (
<li key={item.x} onClick={() => this.handleLegendClick(item, i)}>
<span
className={styles.dot}
style={{
backgroundColor: !item.checked ? '#aaa' : item.color,
}}
/>
<span className={styles.legendTitle}>{item.x}</span>
<Divider type="vertical" />
<span className={styles.percent}>
{`${(Number.isNaN(item.percent) ? 0 : item.percent * 100).toFixed(2)}%`}
</span>
<span className={styles.value}>{valueFormat ? valueFormat(item.y) : item.y}</span>
</li>
))}
</ul>
)}
</div>
);
}
}
export default Pie;
@import '~antd/lib/style/themes/default.less';
.pie {
position: relative;
.chart {
position: relative;
}
&.hasLegend .chart {
width: ~'calc(100% - 240px)';
}
.legend {
position: absolute;
right: 0;
min-width: 200px;
top: 50%;
transform: translateY(-50%);
margin: 0 20px;
list-style: none;
padding: 0;
li {
cursor: pointer;
margin-bottom: 16px;
height: 22px;
line-height: 22px;
&:last-child {
margin-bottom: 0;
}
}
}
.dot {
border-radius: 8px;
display: inline-block;
margin-right: 8px;
position: relative;
top: -1px;
height: 8px;
width: 8px;
}
.line {
background-color: @border-color-split;
display: inline-block;
margin-right: 8px;
width: 1px;
height: 16px;
}
.legendTitle {
color: @text-color;
}
.percent {
color: @text-color-secondary;
}
.value {
position: absolute;
right: 0;
}
.title {
margin-bottom: 8px;
}
.total {
position: absolute;
left: 50%;
top: 50%;
text-align: center;
max-height: 62px;
transform: translate(-50%, -50%);
& > h4 {
color: @text-color-secondary;
font-size: 14px;
line-height: 22px;
height: 22px;
margin-bottom: 8px;
font-weight: normal;
}
& > p {
color: @heading-color;
display: block;
font-size: 1.2em;
height: 32px;
line-height: 32px;
white-space: nowrap;
}
}
}
.legendBlock {
&.hasLegend .chart {
width: 100%;
margin: 0 0 32px 0;
}
.legend {
position: relative;
transform: none;
}
}
import * as React from 'react';
export interface IRadarProps {
title?: React.ReactNode;
height: number;
padding?: [number, number, number, number];
hasLegend?: boolean;
data: Array<{
name: string;
label: string;
value: string;
}>;
style?: React.CSSProperties;
}
export default class Radar extends React.Component<IRadarProps, any> {}
import React, { Component } from 'react';
import { Chart, Tooltip, Geom, Coord, Axis } from 'bizcharts';
import { Row, Col } from 'antd';
import autoHeight from '../autoHeight';
import styles from './index.less';
/* eslint react/no-danger:0 */
@autoHeight()
class Radar extends Component {
state = {
legendData: [],
};
componentDidMount() {
this.getLegendData();
}
componentDidUpdate(preProps) {
const { data } = this.props;
if (data !== preProps.data) {
this.getLegendData();
}
}
getG2Instance = chart => {
this.chart = chart;
};
// for custom lengend view
getLegendData = () => {
if (!this.chart) return;
const geom = this.chart.getAllGeoms()[0]; // 获取所有的图形
if (!geom) return;
const items = geom.get('dataArray') || []; // 获取图形对应的
const legendData = items.map(item => {
// eslint-disable-next-line
const origins = item.map(t => t._origin);
const result = {
name: origins[0].name,
color: item[0].color,
checked: true,
value: origins.reduce((p, n) => p + n.value, 0),
};
return result;
});
this.setState({
legendData,
});
};
handleRef = n => {
this.node = n;
};
handleLegendClick = (item, i) => {
const newItem = item;
newItem.checked = !newItem.checked;
const { legendData } = this.state;
legendData[i] = newItem;
const filteredLegendData = legendData.filter(l => l.checked).map(l => l.name);
if (this.chart) {
this.chart.filter('name', val => filteredLegendData.indexOf(val) > -1);
this.chart.repaint();
}
this.setState({
legendData,
});
};
render() {
const defaultColors = [
'#1890FF',
'#FACC14',
'#2FC25B',
'#8543E0',
'#F04864',
'#13C2C2',
'#fa8c16',
'#a0d911',
];
const {
data = [],
height = 0,
title,
hasLegend = false,
forceFit = true,
tickCount = 5,
padding = [35, 30, 16, 30],
animate = true,
colors = defaultColors,
} = this.props;
const { legendData } = this.state;
const scale = {
value: {
min: 0,
tickCount,
},
};
const chartHeight = height - (hasLegend ? 80 : 22);
return (
<div className={styles.radar} style={{ height }}>
{title && <h4>{title}</h4>}
<Chart
scale={scale}
height={chartHeight}
forceFit={forceFit}
data={data}
padding={padding}
animate={animate}
onGetG2Instance={this.getG2Instance}
>
<Tooltip />
<Coord type="polar" />
<Axis
name="label"
line={null}
tickLine={null}
grid={{
lineStyle: {
lineDash: null,
},
hideFirstLine: false,
}}
/>
<Axis
name="value"
grid={{
type: 'polygon',
lineStyle: {
lineDash: null,
},
}}
/>
<Geom type="line" position="label*value" color={['name', colors]} size={1} />
<Geom
type="point"
position="label*value"
color={['name', colors]}
shape="circle"
size={3}
/>
</Chart>
{hasLegend && (
<Row className={styles.legend}>
{legendData.map((item, i) => (
<Col
span={24 / legendData.length}
key={item.name}
onClick={() => this.handleLegendClick(item, i)}
>
<div className={styles.legendItem}>
<p>
<span
className={styles.dot}
style={{
backgroundColor: !item.checked ? '#aaa' : item.color,
}}
/>
<span>{item.name}</span>
</p>
<h6>{item.value}</h6>
</div>
</Col>
))}
</Row>
)}
</div>
);
}
}
export default Radar;
@import '~antd/lib/style/themes/default.less';
.radar {
.legend {
margin-top: 16px;
.legendItem {
position: relative;
text-align: center;
cursor: pointer;
color: @text-color-secondary;
line-height: 22px;
p {
margin: 0;
}
h6 {
color: @heading-color;
padding-left: 16px;
font-size: 24px;
line-height: 32px;
margin-top: 4px;
margin-bottom: 0;
}
&:after {
background-color: @border-color-split;
position: absolute;
top: 8px;
right: 0;
height: 40px;
width: 1px;
content: '';
}
}
> :last-child .legendItem:after {
display: none;
}
.dot {
border-radius: 6px;
display: inline-block;
margin-right: 6px;
position: relative;
top: -1px;
height: 6px;
width: 6px;
}
}
}
import * as React from 'react';
export interface ITagCloudProps {
data: Array<{
name: string;
value: number;
}>;
height: number;
style?: React.CSSProperties;
}
export default class TagCloud extends React.Component<ITagCloudProps, any> {}
import React, { Component } from 'react';
import { Chart, Geom, Coord, Shape, Tooltip } from 'bizcharts';
import DataSet from '@antv/data-set';
import Debounce from 'lodash-decorators/debounce';
import Bind from 'lodash-decorators/bind';
import classNames from 'classnames';
import autoHeight from '../autoHeight';
import styles from './index.less';
/* eslint no-underscore-dangle: 0 */
/* eslint no-param-reassign: 0 */
const imgUrl = 'https://gw.alipayobjects.com/zos/rmsportal/gWyeGLCdFFRavBGIDzWk.png';
@autoHeight()
class TagCloud extends Component {
state = {
dv: null,
};
componentDidMount() {
requestAnimationFrame(() => {
this.initTagCloud();
this.renderChart();
});
window.addEventListener('resize', this.resize, { passive: true });
}
componentDidUpdate(preProps) {
const { data } = this.props;
if (JSON.stringify(preProps.data) !== JSON.stringify(data)) {
this.renderChart(this.props);
}
}
componentWillUnmount() {
this.isUnmount = true;
window.cancelAnimationFrame(this.requestRef);
window.removeEventListener('resize', this.resize);
}
resize = () => {
this.requestRef = requestAnimationFrame(() => {
this.renderChart();
});
};
saveRootRef = node => {
this.root = node;
};
initTagCloud = () => {
function getTextAttrs(cfg) {
return Object.assign(
{},
{
fillOpacity: cfg.opacity,
fontSize: cfg.origin._origin.size,
rotate: cfg.origin._origin.rotate,
text: cfg.origin._origin.text,
textAlign: 'center',
fontFamily: cfg.origin._origin.font,
fill: cfg.color,
textBaseline: 'Alphabetic',
},
cfg.style
);
}
// 给point注册一个词云的shape
Shape.registerShape('point', 'cloud', {
drawShape(cfg, container) {
const attrs = getTextAttrs(cfg);
return container.addShape('text', {
attrs: Object.assign(attrs, {
x: cfg.x,
y: cfg.y,
}),
});
},
});
};
@Bind()
@Debounce(500)
renderChart(nextProps) {
// const colors = ['#1890FF', '#41D9C7', '#2FC25B', '#FACC14', '#9AE65C'];
const { data, height } = nextProps || this.props;
if (data.length < 1 || !this.root) {
return;
}
const h = height;
const w = this.root.offsetWidth;
const onload = () => {
const dv = new DataSet.View().source(data);
const range = dv.range('value');
const [min, max] = range;
dv.transform({
type: 'tag-cloud',
fields: ['name', 'value'],
imageMask: this.imageMask,
font: 'Verdana',
size: [w, h], // 宽高设置最好根据 imageMask 做调整
padding: 0,
timeInterval: 5000, // max execute time
rotate() {
return 0;
},
fontSize(d) {
// eslint-disable-next-line
return Math.pow((d.value - min) / (max - min), 2) * (17.5 - 5) + 5;
},
});
if (this.isUnmount) {
return;
}
this.setState({
dv,
w,
h,
});
};
if (!this.imageMask) {
this.imageMask = new Image();
this.imageMask.crossOrigin = '';
this.imageMask.src = imgUrl;
this.imageMask.onload = onload;
} else {
onload();
}
}
render() {
const { className, height } = this.props;
const { dv, w, h } = this.state;
return (
<div
className={classNames(styles.tagCloud, className)}
style={{ width: '100%', height }}
ref={this.saveRootRef}
>
{dv && (
<Chart
width={w}
height={h}
data={dv}
padding={0}
scale={{
x: { nice: false },
y: { nice: false },
}}
>
<Tooltip showTitle={false} />
<Coord reflect="y" />
<Geom
type="point"
position="x*y"
color="text"
shape="cloud"
tooltip={[
'text*value',
function trans(text, value) {
return { name: text, value };
},
]}
/>
</Chart>
)}
</div>
);
}
}
export default TagCloud;
.tagCloud {
overflow: hidden;
canvas {
transform-origin: 0 0;
}
}
import * as React from 'react';
export interface ITimelineChartProps {
data: Array<{
x: number;
y1: number;
y2?: number;
}>;
titleMap: { y1: string; y2?: string };
padding?: [number, number, number, number];
height?: number;
style?: React.CSSProperties;
}
export default class TimelineChart extends React.Component<ITimelineChartProps, any> {}
import React from 'react';
import { Chart, Tooltip, Geom, Legend, Axis } from 'bizcharts';
import DataSet from '@antv/data-set';
import Slider from 'bizcharts-plugin-slider';
import autoHeight from '../autoHeight';
import styles from './index.less';
@autoHeight()
class TimelineChart extends React.Component {
render() {
const {
title,
height = 400,
padding = [60, 20, 40, 40],
titleMap = {
y1: 'y1',
y2: 'y2',
},
borderWidth = 2,
data: sourceData,
} = this.props;
const data = Array.isArray(sourceData) ? sourceData : [{ x: 0, y1: 0, y2: 0 }];
data.sort((a, b) => a.x - b.x);
let max;
if (data[0] && data[0].y1 && data[0].y2) {
max = Math.max(
[...data].sort((a, b) => b.y1 - a.y1)[0].y1,
[...data].sort((a, b) => b.y2 - a.y2)[0].y2
);
}
const ds = new DataSet({
state: {
start: data[0].x,
end: data[data.length - 1].x,
},
});
const dv = ds.createView();
dv.source(data)
.transform({
type: 'filter',
callback: obj => {
const date = obj.x;
return date <= ds.state.end && date >= ds.state.start;
},
})
.transform({
type: 'map',
callback(row) {
const newRow = { ...row };
newRow[titleMap.y1] = row.y1;
newRow[titleMap.y2] = row.y2;
return newRow;
},
})
.transform({
type: 'fold',
fields: [titleMap.y1, titleMap.y2], // 展开字段集
key: 'key', // key字段
value: 'value', // value字段
});
const timeScale = {
type: 'time',
tickInterval: 60 * 60 * 1000,
mask: 'HH:mm',
range: [0, 1],
};
const cols = {
x: timeScale,
value: {
max,
min: 0,
},
};
const SliderGen = () => (
<Slider
padding={[0, padding[1] + 20, 0, padding[3]]}
width="auto"
height={26}
xAxis="x"
yAxis="y1"
scales={{ x: timeScale }}
data={data}
start={ds.state.start}
end={ds.state.end}
backgroundChart={{ type: 'line' }}
onChange={({ startValue, endValue }) => {
ds.setState('start', startValue);
ds.setState('end', endValue);
}}
/>
);
return (
<div className={styles.timelineChart} style={{ height: height + 30 }}>
<div>
{title && <h4>{title}</h4>}
<Chart height={height} padding={padding} data={dv} scale={cols} forceFit>
<Axis name="x" />
<Tooltip />
<Legend name="key" position="top" />
<Geom type="line" position="x*value" size={borderWidth} color="key" />
</Chart>
<div style={{ marginRight: -20 }}>
<SliderGen />
</div>
</div>
</div>
);
}
}
export default TimelineChart;
import * as React from 'react';
export interface IWaterWaveProps {
title: React.ReactNode;
color?: string;
height: number;
percent: number;
style?: React.CSSProperties;
}
export default class WaterWave extends React.Component<IWaterWaveProps, any> {}
import React, { PureComponent } from 'react';
import autoHeight from '../autoHeight';
import styles from './index.less';
/* eslint no-return-assign: 0 */
/* eslint no-mixed-operators: 0 */
// riddle: https://riddle.alibaba-inc.com/riddles/2d9a4b90
@autoHeight()
class WaterWave extends PureComponent {
state = {
radio: 1,
};
componentDidMount() {
this.renderChart();
this.resize();
window.addEventListener(
'resize',
() => {
requestAnimationFrame(() => this.resize());
},
{ passive: true }
);
}
componentDidUpdate(props) {
const { percent } = this.props;
if (props.percent !== percent) {
// 不加这个会造成绘制缓慢
this.renderChart('update');
}
}
componentWillUnmount() {
cancelAnimationFrame(this.timer);
if (this.node) {
this.node.innerHTML = '';
}
window.removeEventListener('resize', this.resize);
}
resize = () => {
if (this.root) {
const { height } = this.props;
const { offsetWidth } = this.root.parentNode;
this.setState({
radio: offsetWidth < height ? offsetWidth / height : 1,
});
}
};
renderChart(type) {
const { percent, color = '#1890FF' } = this.props;
const data = percent / 100;
const self = this;
cancelAnimationFrame(this.timer);
if (!this.node || (data !== 0 && !data)) {
return;
}
const canvas = this.node;
const ctx = canvas.getContext('2d');
const canvasWidth = canvas.width;
const canvasHeight = canvas.height;
const radius = canvasWidth / 2;
const lineWidth = 2;
const cR = radius - lineWidth;
ctx.beginPath();
ctx.lineWidth = lineWidth * 2;
const axisLength = canvasWidth - lineWidth;
const unit = axisLength / 8;
const range = 0.2; // 振幅
let currRange = range;
const xOffset = lineWidth;
let sp = 0; // 周期偏移量
let currData = 0;
const waveupsp = 0.005; // 水波上涨速度
let arcStack = [];
const bR = radius - lineWidth;
const circleOffset = -(Math.PI / 2);
let circleLock = true;
for (let i = circleOffset; i < circleOffset + 2 * Math.PI; i += 1 / (8 * Math.PI)) {
arcStack.push([radius + bR * Math.cos(i), radius + bR * Math.sin(i)]);
}
const cStartPoint = arcStack.shift();
ctx.strokeStyle = color;
ctx.moveTo(cStartPoint[0], cStartPoint[1]);
function drawSin() {
ctx.beginPath();
ctx.save();
const sinStack = [];
for (let i = xOffset; i <= xOffset + axisLength; i += 20 / axisLength) {
const x = sp + (xOffset + i) / unit;
const y = Math.sin(x) * currRange;
const dx = i;
const dy = 2 * cR * (1 - currData) + (radius - cR) - unit * y;
ctx.lineTo(dx, dy);
sinStack.push([dx, dy]);
}
const startPoint = sinStack.shift();
ctx.lineTo(xOffset + axisLength, canvasHeight);
ctx.lineTo(xOffset, canvasHeight);
ctx.lineTo(startPoint[0], startPoint[1]);
const gradient = ctx.createLinearGradient(0, 0, 0, canvasHeight);
gradient.addColorStop(0, '#ffffff');
gradient.addColorStop(1, color);
ctx.fillStyle = gradient;
ctx.fill();
ctx.restore();
}
function render() {
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
if (circleLock && type !== 'update') {
if (arcStack.length) {
const temp = arcStack.shift();
ctx.lineTo(temp[0], temp[1]);
ctx.stroke();
} else {
circleLock = false;
ctx.lineTo(cStartPoint[0], cStartPoint[1]);
ctx.stroke();
arcStack = null;
ctx.globalCompositeOperation = 'destination-over';
ctx.beginPath();
ctx.lineWidth = lineWidth;
ctx.arc(radius, radius, bR, 0, 2 * Math.PI, 1);
ctx.beginPath();
ctx.save();
ctx.arc(radius, radius, radius - 3 * lineWidth, 0, 2 * Math.PI, 1);
ctx.restore();
ctx.clip();
ctx.fillStyle = color;
}
} else {
if (data >= 0.85) {
if (currRange > range / 4) {
const t = range * 0.01;
currRange -= t;
}
} else if (data <= 0.1) {
if (currRange < range * 1.5) {
const t = range * 0.01;
currRange += t;
}
} else {
if (currRange <= range) {
const t = range * 0.01;
currRange += t;
}
if (currRange >= range) {
const t = range * 0.01;
currRange -= t;
}
}
if (data - currData > 0) {
currData += waveupsp;
}
if (data - currData < 0) {
currData -= waveupsp;
}
sp += 0.07;
drawSin();
}
self.timer = requestAnimationFrame(render);
}
render();
}
render() {
const { radio } = this.state;
const { percent, title, height } = this.props;
return (
<div
className={styles.waterWave}
ref={n => (this.root = n)}
style={{ transform: `scale(${radio})` }}
>
<div style={{ width: height, height, overflow: 'hidden' }}>
<canvas
className={styles.waterWaveCanvasWrapper}
ref={n => (this.node = n)}
width={height * 2}
height={height * 2}
/>
</div>
<div className={styles.text} style={{ width: height }}>
{title && <span>{title}</span>}
<h4>{percent}%</h4>
</div>
</div>
);
}
}
export default WaterWave;
@import '~antd/lib/style/themes/default.less';
.waterWave {
display: inline-block;
position: relative;
transform-origin: left;
.text {
position: absolute;
left: 0;
top: 32px;
text-align: center;
width: 100%;
span {
color: @text-color-secondary;
font-size: 14px;
line-height: 22px;
}
h4 {
color: @heading-color;
line-height: 32px;
font-size: 24px;
}
}
.waterWaveCanvasWrapper {
transform: scale(0.5);
transform-origin: 0 0;
}
}
/* eslint eqeqeq: 0 */
import React from 'react';
function computeHeight(node) {
const totalHeight = parseInt(getComputedStyle(node).height, 10);
const padding =
parseInt(getComputedStyle(node).paddingTop, 10) +
parseInt(getComputedStyle(node).paddingBottom, 10);
return totalHeight - padding;
}
function getAutoHeight(n) {
if (!n) {
return 0;
}
let node = n;
let height = computeHeight(node);
while (!height) {
node = node.parentNode;
if (node) {
height = computeHeight(node);
} else {
break;
}
}
return height;
}
const autoHeight = () => WrappedComponent =>
class extends React.Component {
state = {
computedHeight: 0,
};
componentDidMount() {
const { height } = this.props;
if (!height) {
const h = getAutoHeight(this.root);
// eslint-disable-next-line
this.setState({ computedHeight: h });
}
}
handleRoot = node => {
this.root = node;
};
render() {
const { height } = this.props;
const { computedHeight } = this.state;
const h = height || computedHeight;
return (
<div ref={this.handleRoot}>{h > 0 && <WrappedComponent {...this.props} height={h} />}</div>
);
}
};
export default autoHeight;
import * as BizChart from 'bizcharts';
export = BizChart;
import * as BizChart from 'bizcharts';
export default BizChart;
---
order: 4
title: 柱状图
---
通过设置 `x``y` 属性,可以快速的构建出一个漂亮的柱状图,各种纬度的关系则是通过自定义的数据展现。
````jsx
import { Bar } from 'ant-design-pro/lib/Charts';
const salesData = [];
for (let i = 0; i < 12; i += 1) {
salesData.push({
x: `${i + 1}月`,
y: Math.floor(Math.random() * 1000) + 200,
});
}
ReactDOM.render(
<Bar
height={200}
title="销售额趋势"
data={salesData}
/>
, mountNode);
````
---
order: 1
title: 图表卡片
---
用于展示图表的卡片容器,可以方便的配合其它图表套件展示丰富信息。
```jsx
import { ChartCard, yuan, Field } from 'ant-design-pro/lib/Charts';
import Trend from 'ant-design-pro/lib/Trend';
import { Row, Col, Icon, Tooltip } from 'antd';
import numeral from 'numeral';
ReactDOM.render(
<Row>
<Col span={24}>
<ChartCard
title="销售额"
action={
<Tooltip title="指标说明">
<Icon type="info-circle-o" />
</Tooltip>
}
total={() => (
<span dangerouslySetInnerHTML={{ __html: yuan(126560) }} />
)}
footer={
<Field label="日均销售额" value={numeral(12423).format("0,0")} />
}
contentHeight={46}
>
<span>
周同比
<Trend flag="up" style={{ marginLeft: 8, color: "rgba(0,0,0,.85)" }}>
12%
</Trend>
</span>
<span style={{ marginLeft: 16 }}>
日环比
<Trend
flag="down"
style={{ marginLeft: 8, color: "rgba(0,0,0,.85)" }}
>
11%
</Trend>
</span>
</ChartCard>
</Col>
<Col span={24} style={{ marginTop: 24 }}>
<ChartCard
title="移动指标"
avatar={
<img
style={{ width: 56, height: 56 }}
src="https://gw.alipayobjects.com/zos/rmsportal/sfjbOqnsXXJgNCjCzDBL.png"
alt="indicator"
/>
}
action={
<Tooltip title="指标说明">
<Icon type="info-circle-o" />
</Tooltip>
}
total={() => (
<span dangerouslySetInnerHTML={{ __html: yuan(126560) }} />
)}
footer={
<Field label="日均销售额" value={numeral(12423).format("0,0")} />
}
/>
</Col>
<Col span={24} style={{ marginTop: 24 }}>
<ChartCard
title="移动指标"
avatar={
<img
alt="indicator"
style={{ width: 56, height: 56 }}
src="https://gw.alipayobjects.com/zos/rmsportal/dURIMkkrRFpPgTuzkwnB.png"
/>
}
action={
<Tooltip title="指标说明">
<Icon type="info-circle-o" />
</Tooltip>
}
total={() => (
<span dangerouslySetInnerHTML={{ __html: yuan(126560) }} />
)}
/>
</Col>
</Row>,
mountNode,
);
```
---
order: 7
title: 仪表盘
---
仪表盘是一种进度展示方式,可以更直观的展示当前的进展情况,通常也可表示占比。
````jsx
import { Gauge } from 'ant-design-pro/lib/Charts';
ReactDOM.render(
<Gauge
title="核销率"
height={164}
percent={87}
/>
, mountNode);
````
---
order: 2
col: 2
title: 迷你区域图
---
````jsx
import { MiniArea } from 'ant-design-pro/lib/Charts';
import moment from 'moment';
const visitData = [];
const beginDay = new Date().getTime();
for (let i = 0; i < 20; i += 1) {
visitData.push({
x: moment(new Date(beginDay + (1000 * 60 * 60 * 24 * i))).format('YYYY-MM-DD'),
y: Math.floor(Math.random() * 100) + 10,
});
}
ReactDOM.render(
<MiniArea
line
color="#cceafe"
height={45}
data={visitData}
/>
, mountNode);
````
---
order: 2
col: 2
title: 迷你柱状图
---
迷你柱状图更适合展示简单的区间数据,简洁的表现方式可以很好的减少大数据量的视觉展现压力。
````jsx
import { MiniBar } from 'ant-design-pro/lib/Charts';
import moment from 'moment';
const visitData = [];
const beginDay = new Date().getTime();
for (let i = 0; i < 20; i += 1) {
visitData.push({
x: moment(new Date(beginDay + (1000 * 60 * 60 * 24 * i))).format('YYYY-MM-DD'),
y: Math.floor(Math.random() * 100) + 10,
});
}
ReactDOM.render(
<MiniBar
height={45}
data={visitData}
/>
, mountNode);
````
---
order: 6
title: 迷你饼状图
---
通过简化 `Pie` 属性的设置,可以快速的实现极简的饼状图,可配合 `ChartCard` 组合展
现更多业务场景。
```jsx
import { Pie } from 'ant-design-pro/lib/Charts';
ReactDOM.render(
<Pie percent={28} subTitle="中式快餐" total="28%" height={140} />,
mountNode
);
```
---
order: 3
title: 迷你进度条
---
````jsx
import { MiniProgress } from 'ant-design-pro/lib/Charts';
ReactDOM.render(
<MiniProgress percent={78} strokeWidth={8} target={80} />
, mountNode);
````
---
order: 0
title: 图表套件组合展示
---
利用 Ant Design Pro 提供的图表套件,可以灵活组合符合设计规范的图表来满足复杂的业务需求。
````jsx
import { ChartCard, Field, MiniArea, MiniBar, MiniProgress } from 'ant-design-pro/lib/Charts';
import Trend from 'ant-design-pro/lib/Trend';
import NumberInfo from 'ant-design-pro/lib/NumberInfo';
import { Row, Col, Icon, Tooltip } from 'antd';
import numeral from 'numeral';
import moment from 'moment';
const visitData = [];
const beginDay = new Date().getTime();
for (let i = 0; i < 20; i += 1) {
visitData.push({
x: moment(new Date(beginDay + (1000 * 60 * 60 * 24 * i))).format('YYYY-MM-DD'),
y: Math.floor(Math.random() * 100) + 10,
});
}
ReactDOM.render(
<Row>
<Col span={24}>
<ChartCard
title="搜索用户数量"
total={numeral(8846).format('0,0')}
contentHeight={134}
>
<NumberInfo
subTitle={<span>本周访问</span>}
total={numeral(12321).format('0,0')}
status="up"
subTotal={17.1}
/>
<MiniArea
line
height={45}
data={visitData}
/>
</ChartCard>
</Col>
<Col span={24} style={{ marginTop: 24 }}>
<ChartCard
title="访问量"
action={<Tooltip title="指标说明"><Icon type="info-circle-o" /></Tooltip>}
total={numeral(8846).format('0,0')}
footer={<Field label="日访问量" value={numeral(1234).format('0,0')} />}
contentHeight={46}
>
<MiniBar
height={46}
data={visitData}
/>
</ChartCard>
</Col>
<Col span={24} style={{ marginTop: 24 }}>
<ChartCard
title="线上购物转化率"
action={<Tooltip title="指标说明"><Icon type="info-circle-o" /></Tooltip>}
total="78%"
footer={
<div>
<span>
周同比
<Trend flag="up" style={{ marginLeft: 8, color: 'rgba(0,0,0,.85)' }}>12%</Trend>
</span>
<span style={{ marginLeft: 16 }}>
日环比
<Trend flag="down" style={{ marginLeft: 8, color: 'rgba(0,0,0,.85)' }}>11%</Trend>
</span>
</div>
}
contentHeight={46}
>
<MiniProgress percent={78} strokeWidth={8} target={80} />
</ChartCard>
</Col>
</Row>
, mountNode);
````
---
order: 5
title: 饼状图
---
```jsx
import { Pie, yuan } from 'ant-design-pro/lib/Charts';
const salesPieData = [
{
x: '家用电器',
y: 4544,
},
{
x: '食用酒水',
y: 3321,
},
{
x: '个护健康',
y: 3113,
},
{
x: '服饰箱包',
y: 2341,
},
{
x: '母婴产品',
y: 1231,
},
{
x: '其他',
y: 1231,
},
];
ReactDOM.render(
<Pie
hasLegend
title="销售额"
subTitle="销售额"
total={() => (
<span
dangerouslySetInnerHTML={{
__html: yuan(salesPieData.reduce((pre, now) => now.y + pre, 0))
}}
/>
)}
data={salesPieData}
valueFormat={val => <span dangerouslySetInnerHTML={{ __html: yuan(val) }} />}
height={294}
/>,
mountNode,
);
```
---
order: 7
title: 雷达图
---
````jsx
import { Radar, ChartCard } from 'ant-design-pro/lib/Charts';
const radarOriginData = [
{
name: '个人',
ref: 10,
koubei: 8,
output: 4,
contribute: 5,
hot: 7,
},
{
name: '团队',
ref: 3,
koubei: 9,
output: 6,
contribute: 3,
hot: 1,
},
{
name: '部门',
ref: 4,
koubei: 1,
output: 6,
contribute: 5,
hot: 7,
},
];
const radarData = [];
const radarTitleMap = {
ref: '引用',
koubei: '口碑',
output: '产量',
contribute: '贡献',
hot: '热度',
};
radarOriginData.forEach((item) => {
Object.keys(item).forEach((key) => {
if (key !== 'name') {
radarData.push({
name: item.name,
label: radarTitleMap[key],
value: item[key],
});
}
});
});
ReactDOM.render(
<ChartCard title="数据比例">
<Radar
hasLegend
height={286}
data={radarData}
/>
</ChartCard>
, mountNode);
````
---
order: 9
title: 标签云
---
标签云是一套相关的标签以及与此相应的权重展示方式,一般典型的标签云有 30 至 150 个标签,而权重影响使用的字体大小或其他视觉效果。
````jsx
import { TagCloud } from 'ant-design-pro/lib/Charts';
const tags = [];
for (let i = 0; i < 50; i += 1) {
tags.push({
name: `TagClout-Title-${i}`,
value: Math.floor((Math.random() * 50)) + 20,
});
}
ReactDOM.render(
<TagCloud
data={tags}
height={200}
/>
, mountNode);
````
---
order: 9
title: 带有时间轴的图表
---
使用 `TimelineChart` 组件可以实现带有时间轴的柱状图展现,而其中的 `x` 属性,则是时间值的指向,默认最多支持同时展现两个指标,分别是 `y1``y2`
````jsx
import { TimelineChart } from 'ant-design-pro/lib/Charts';
const chartData = [];
for (let i = 0; i < 20; i += 1) {
chartData.push({
x: (new Date().getTime()) + (1000 * 60 * 30 * i),
y1: Math.floor(Math.random() * 100) + 1000,
y2: Math.floor(Math.random() * 100) + 10,
});
}
ReactDOM.render(
<TimelineChart
height={200}
data={chartData}
titleMap={{ y1: '客流量', y2: '支付笔数' }}
/>
, mountNode);
````
---
order: 8
title: 水波图
---
水波图是一种比例的展示方式,可以更直观的展示关键值的占比。
````jsx
import { WaterWave } from 'ant-design-pro/lib/Charts';
ReactDOM.render(
<div style={{ textAlign: 'center' }}>
<WaterWave
height={161}
title="补贴资金剩余"
percent={34}
/>
</div>
, mountNode);
````
// 全局 G2 设置
import { track, setTheme } from 'bizcharts';
track(false);
const config = {
defaultColor: '#1089ff',
shape: {
interval: {
fillOpacity: 1,
},
},
};
setTheme(config);
import * as numeral from 'numeral';
export { default as ChartCard } from './ChartCard';
export { default as Bar } from './Bar';
export { default as Pie } from './Pie';
export { default as Radar } from './Radar';
export { default as Gauge } from './Gauge';
export { default as MiniArea } from './MiniArea';
export { default as MiniBar } from './MiniBar';
export { default as MiniProgress } from './MiniProgress';
export { default as Field } from './Field';
export { default as WaterWave } from './WaterWave';
export { default as TagCloud } from './TagCloud';
export { default as TimelineChart } from './TimelineChart';
declare const yuan: (value: number | string) => string;
export { yuan };
import numeral from 'numeral';
import './g2';
import ChartCard from './ChartCard';
import Bar from './Bar';
import Pie from './Pie';
import Radar from './Radar';
import Gauge from './Gauge';
import MiniArea from './MiniArea';
import MiniBar from './MiniBar';
import MiniProgress from './MiniProgress';
import Field from './Field';
import WaterWave from './WaterWave';
import TagCloud from './TagCloud';
import TimelineChart from './TimelineChart';
const yuan = val => ${numeral(val).format('0,0')}`;
const Charts = {
yuan,
Bar,
Pie,
Gauge,
Radar,
MiniBar,
MiniArea,
MiniProgress,
ChartCard,
Field,
WaterWave,
TagCloud,
TimelineChart,
};
export {
Charts as default,
yuan,
Bar,
Pie,
Gauge,
Radar,
MiniBar,
MiniArea,
MiniProgress,
ChartCard,
Field,
WaterWave,
TagCloud,
TimelineChart,
};
.miniChart {
position: relative;
width: 100%;
.chartContent {
position: absolute;
bottom: -28px;
width: 100%;
> div {
margin: 0 -5px;
overflow: hidden;
}
}
.chartLoading {
position: absolute;
top: 16px;
left: 50%;
margin-left: -7px;
}
}
---
title:
en-US: Charts
zh-CN: Charts
subtitle: 图表
order: 2
cols: 2
---
Ant Design Pro 提供的业务中常用的图表类型,都是基于 [G2](https://antv.alipay.com/g2/doc/index.html) 按照 Ant Design 图表规范封装,需要注意的是 Ant Design Pro 的图表组件以套件形式提供,可以任意组合实现复杂的业务需求。
因为结合了 Ant Design 的标准设计,本着极简的设计思想以及开箱即用的理念,简化了大量 API 配置,所以如果需要灵活定制图表,可以参考 Ant Design Pro 图表实现,自行基于 [G2](https://antv.alipay.com/g2/doc/index.html) 封装图表组件使用。
## API
### ChartCard
| 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------|
| title | 卡片标题 | ReactNode\|string | - |
| action | 卡片操作 | ReactNode | - |
| total | 数据总量 | ReactNode \| number \| function | - |
| footer | 卡片底部 | ReactNode | - |
| contentHeight | 内容区域高度 | number | - |
| avatar | 右侧图标 | React.ReactNode | - |
### MiniBar
| 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------|
| color | 图表颜色 | string | `#1890FF` |
| height | 图表高度 | number | - |
| data | 数据 | array<{x, y}> | - |
### MiniArea
| 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------|
| color | 图表颜色 | string | `rgba(24, 144, 255, 0.2)` |
| borderColor | 图表边颜色 | string | `#1890FF` |
| height | 图表高度 | number | - |
| line | 是否显示描边 | boolean | false |
| animate | 是否显示动画 | boolean | true |
| xAxis | [x 轴配置](http://antvis.github.io/g2/doc/tutorial/start/axis.html) | object | - |
| yAxis | [y 轴配置](http://antvis.github.io/g2/doc/tutorial/start/axis.html) | object | - |
| data | 数据 | array<{x, y}> | - |
### MiniProgress
| 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------|
| target | 目标比例 | number | - |
| color | 进度条颜色 | string | - |
| strokeWidth | 进度条高度 | number | - |
| percent | 进度比例 | number | - |
### Bar
| 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------|
| title | 图表标题 | ReactNode\|string | - |
| color | 图表颜色 | string | `rgba(24, 144, 255, 0.85)` |
| padding | 图表内部间距 | [array](https://github.com/alibaba/BizCharts/blob/master/doc/api/chart.md#7padding-object--number--array-) | `'auto'` |
| height | 图表高度 | number | - |
| data | 数据 | array<{x, y}> | - |
| autoLabel | 在宽度不足时,自动隐藏 x 轴的 label | boolean | `true` |
### Pie
| 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------|
| animate | 是否显示动画 | boolean | true |
| color | 图表颜色 | string | `rgba(24, 144, 255, 0.85)` |
| height | 图表高度 | number | - |
| hasLegend | 是否显示 legend | boolean | `false` |
| padding | 图表内部间距 | [array](https://github.com/alibaba/BizCharts/blob/master/doc/api/chart.md#7padding-object--number--array-) | `'auto'` |
| percent | 占比 | number | - |
| tooltip | 是否显示 tooltip | boolean | true |
| valueFormat | 显示值的格式化函数 | function | - |
| title | 图表标题 | ReactNode\|string | - |
| subTitle | 图表子标题 | ReactNode\|string | - |
| total | 图标中央的总数 | string | function | - |
### Radar
| 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------|
| title | 图表标题 | ReactNode\|string | - |
| height | 图表高度 | number | - |
| hasLegend | 是否显示 legend | boolean | `false` |
| padding | 图表内部间距 | [array](https://github.com/alibaba/BizCharts/blob/master/doc/api/chart.md#7padding-object--number--array-) | `'auto'` |
| data | 图标数据 | array<{name,label,value}> | - |
### Gauge
| 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------|
| title | 图表标题 | ReactNode\|string | - |
| height | 图表高度 | number | - |
| color | 图表颜色 | string | `#2F9CFF` |
| bgColor | 图表背景颜色 | string | `#F0F2F5` |
| percent | 进度比例 | number | - |
### WaterWave
| 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------|
| title | 图表标题 | ReactNode\|string | - |
| height | 图表高度 | number | - |
| color | 图表颜色 | string | `#1890FF` |
| percent | 进度比例 | number | - |
### TagCloud
| 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------|
| data | 标题 | Array<name, value\> | - |
| height | 高度值 | number | - |
### TimelineChart
| 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------|
| data | 标题 | Array<x, y1, y2\> | - |
| titleMap | 指标别名 | Object{y1: '客流量', y2: '支付笔数'} | - |
| height | 高度值 | number | 400 |
### Field
| 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------|
| label | 标题 | ReactNode\|string | - |
| value | 值 | ReactNode\|string | - |
---
order: 0
title:
zh-CN: 基本
en-US: Basic
---
## zh-CN
简单的倒计时组件使用。
## en-US
The simplest usage.
````jsx
import CountDown from 'ant-design-pro/lib/CountDown';
const targetTime = new Date().getTime() + 3900000;
ReactDOM.render(
<CountDown style={{ fontSize: 20 }} target={targetTime} />
, mountNode);
````
import * as React from 'react';
export interface ICountDownProps {
format?: (time: number) => void;
target: Date | number;
onEnd?: () => void;
style?: React.CSSProperties;
}
export default class CountDown extends React.Component<ICountDownProps, any> {}
---
title: CountDown
cols: 1
order: 3
---
Simple CountDown Component.
## API
| Property | Description | Type | Default |
|----------|------------------------------------------|-------------|-------|
| format | Formatter of time | Function(time) | |
| target | Target time | Date | - |
| onEnd | Countdown to the end callback | funtion | -|
import React, { Component } from 'react';
function fixedZero(val) {
return val * 1 < 10 ? `0${val}` : val;
}
const initTime = props => {
let lastTime = 0;
let targetTime = 0;
try {
if (Object.prototype.toString.call(props.target) === '[object Date]') {
targetTime = props.target.getTime();
} else {
targetTime = new Date(props.target).getTime();
}
} catch (e) {
throw new Error('invalid target prop', e);
}
lastTime = targetTime - new Date().getTime();
return {
lastTime: lastTime < 0 ? 0 : lastTime,
};
};
class CountDown extends Component {
timer = 0;
interval = 1000;
constructor(props) {
super(props);
const { lastTime } = initTime(props);
this.state = {
lastTime,
};
}
static getDerivedStateFromProps(nextProps, preState) {
const { lastTime } = initTime(nextProps);
if (preState.lastTime !== lastTime) {
return {
lastTime,
};
}
return null;
}
componentDidMount() {
this.tick();
}
componentDidUpdate(prevProps) {
const { target } = this.props;
if (target !== prevProps.target) {
clearTimeout(this.timer);
this.tick();
}
}
componentWillUnmount() {
clearTimeout(this.timer);
}
// defaultFormat = time => (
// <span>{moment(time).format('hh:mm:ss')}</span>
// );
defaultFormat = time => {
const hours = 60 * 60 * 1000;
const minutes = 60 * 1000;
const h = Math.floor(time / hours);
const m = Math.floor((time - h * hours) / minutes);
const s = Math.floor((time - h * hours - m * minutes) / 1000);
return (
<span>
{fixedZero(h)}:{fixedZero(m)}:{fixedZero(s)}
</span>
);
};
tick = () => {
const { onEnd } = this.props;
let { lastTime } = this.state;
this.timer = setTimeout(() => {
if (lastTime < this.interval) {
clearTimeout(this.timer);
this.setState(
{
lastTime: 0,
},
() => {
if (onEnd) {
onEnd();
}
}
);
} else {
lastTime -= this.interval;
this.setState(
{
lastTime,
},
() => {
this.tick();
}
);
}
}, this.interval);
};
render() {
const { format = this.defaultFormat, onEnd, ...rest } = this.props;
const { lastTime } = this.state;
const result = format(lastTime);
return <span {...rest}>{result}</span>;
}
}
export default CountDown;
---
title: CountDown
subtitle: 倒计时
cols: 1
order: 3
---
倒计时组件。
## API
| 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------|
| format | 时间格式化显示 | Function(time) | |
| target | 目标时间 | Date | - |
| onEnd | 倒计时结束回调 | funtion | -|
import * as React from 'react';
export default class Description extends React.Component<
{
term: React.ReactNode;
style?: React.CSSProperties;
},
any
> {}
import React from 'react';
import PropTypes from 'prop-types';
import { Col } from 'antd';
import styles from './index.less';
import responsive from './responsive';
const Description = ({ term, column, children, ...restProps }) => (
<Col {...responsive[column]} {...restProps}>
{term && <div className={styles.term}>{term}</div>}
{children !== null && children !== undefined && <div className={styles.detail}>{children}</div>}
</Col>
);
Description.defaultProps = {
term: '',
};
Description.propTypes = {
term: PropTypes.node,
};
export default Description;
import React from 'react';
import classNames from 'classnames';
import { Row } from 'antd';
import styles from './index.less';
const DescriptionList = ({
className,
title,
col = 3,
layout = 'horizontal',
gutter = 32,
children,
size,
...restProps
}) => {
const clsString = classNames(styles.descriptionList, styles[layout], className, {
[styles.small]: size === 'small',
[styles.large]: size === 'large',
});
const column = col > 4 ? 4 : col;
return (
<div className={clsString} {...restProps}>
{title ? <div className={styles.title}>{title}</div> : null}
<Row gutter={gutter}>
{React.Children.map(children, child =>
child ? React.cloneElement(child, { column }) : child
)}
</Row>
</div>
);
};
export default DescriptionList;
---
order: 0
title:
zh-CN: 基本
en-US: Basic
---
## zh-CN
基本描述列表。
## en-US
Basic DescriptionList.
````jsx
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
const { Description } = DescriptionList;
ReactDOM.render(
<DescriptionList size="large" title="title">
<Description term="Firefox">
A free, open source, cross-platform,
graphical web browser developed by the
Mozilla Corporation and hundreds of
volunteers.
</Description>
<Description term="Firefox">
A free, open source, cross-platform,
graphical web browser developed by the
Mozilla Corporation and hundreds of
volunteers.
</Description>
<Description term="Firefox">
A free, open source, cross-platform,
graphical web browser developed by the
Mozilla Corporation and hundreds of
volunteers.
</Description>
</DescriptionList>
, mountNode);
````
---
order: 1
title:
zh-CN: 垂直型
en-US: Vertical
---
## zh-CN
垂直布局。
## en-US
Vertical layout.
````jsx
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
const { Description } = DescriptionList;
ReactDOM.render(
<DescriptionList size="large" title="title" layout="vertical">
<Description term="Firefox">
A free, open source, cross-platform,
graphical web browser developed by the
Mozilla Corporation and hundreds of
volunteers.
</Description>
<Description term="Firefox">
A free, open source, cross-platform,
graphical web browser developed by the
Mozilla Corporation and hundreds of
volunteers.
</Description>
<Description term="Firefox">
A free, open source, cross-platform,
graphical web browser developed by the
Mozilla Corporation and hundreds of
volunteers.
</Description>
</DescriptionList>
, mountNode);
````
import * as React from 'react';
import Description from './Description';
export interface IDescriptionListProps {
layout?: 'horizontal' | 'vertical';
col?: number;
title: React.ReactNode;
gutter?: number;
size?: 'large' | 'small';
style?: React.CSSProperties;
}
export default class DescriptionList extends React.Component<IDescriptionListProps, any> {
public static Description: typeof Description;
}
---
title: DescriptionList
cols: 1
order: 4
---
Groups display multiple read-only fields, which are common to informational displays on detail pages.
## API
### DescriptionList
| Property | Description | Type | Default |
|----------|------------------------------------------|-------------|---------|
| layout | type of layout | Enum{'horizontal', 'vertical'} | 'horizontal' |
| col | specify the maximum number of columns to display, the final columns number is determined by col setting combined with [Responsive Rules](/components/DescriptionList#Responsive-Rules) | number(0 < col <= 4) | 3 |
| title | title | ReactNode | - |
| gutter | specify the distance between two items, unit is `px` | number | 32 |
| size | size of list | Enum{'large', 'small'} | - |
#### Responsive Rules
| Window Width | Columns Number |
|---------------------|---------------------------------------------|
| `≥768px` | `col` |
| `≥576px` | `col < 2 ? col : 2` |
| `<576px` | `1` |
### DescriptionList.Description
| Property | Description | Type | Default |
|----------|------------------------------------------|-------------|-------|
| term | item title | ReactNode | - |
import DescriptionList from './DescriptionList';
import Description from './Description';
DescriptionList.Description = Description;
export default DescriptionList;
@import '~antd/lib/style/themes/default.less';
.descriptionList {
// offset the padding-bottom of last row
:global {
.ant-row {
margin-bottom: -16px;
overflow: hidden;
}
}
.title {
font-size: 14px;
color: @heading-color;
font-weight: 500;
margin-bottom: 16px;
}
.term {
// Line-height is 22px IE dom height will calculate error
line-height: 20px;
padding-bottom: 16px;
margin-right: 8px;
color: @heading-color;
white-space: nowrap;
display: table-cell;
&:after {
content: ':';
margin: 0 8px 0 2px;
position: relative;
top: -0.5px;
}
}
.detail {
line-height: 20px;
width: 100%;
padding-bottom: 16px;
color: @text-color;
display: table-cell;
}
&.small {
// offset the padding-bottom of last row
:global {
.ant-row {
margin-bottom: -8px;
}
}
.title {
margin-bottom: 12px;
color: @text-color;
}
.term,
.detail {
padding-bottom: 8px;
}
}
&.large {
.title {
font-size: 16px;
}
}
&.vertical {
.term {
padding-bottom: 8px;
display: block;
}
.detail {
display: block;
}
}
}
---
title: DescriptionList
subtitle: 描述列表
cols: 1
order: 4
---
成组展示多个只读字段,常见于详情页的信息展示。
## API
### DescriptionList
| 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------|
| layout | 布局方式 | Enum{'horizontal', 'vertical'} | 'horizontal' |
| col | 指定信息最多分几列展示,最终一行几列由 col 配置结合[响应式规则](/components/DescriptionList#响应式规则)决定 | number(0 < col <= 4) | 3 |
| title | 列表标题 | ReactNode | - |
| gutter | 列表项间距,单位为 `px` | number | 32 |
| size | 列表型号 | Enum{'large', 'small'} | - |
#### 响应式规则
| 窗口宽度 | 展示列数 |
|---------------------|---------------------------------------------|
| `≥768px` | `col` |
| `≥576px` | `col < 2 ? col : 2` |
| `<576px` | `1` |
### DescriptionList.Description
| 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------|
| term | 列表项标题 | ReactNode | - |
export default {
1: { xs: 24 },
2: { xs: 24, sm: 12 },
3: { xs: 24, sm: 12, md: 8 },
4: { xs: 24, sm: 12, md: 6 },
};
---
order: 1
title:
zh-CN: 按照行数省略
en-US: Truncate according to the number of rows
---
## zh-CN
通过设置 `lines` 属性指定最大行数,如果超过这个行数的文本会自动截取。但是在这种模式下所有 `children` 将会被转换成纯文本。
并且注意在这种模式下,外容器需要有指定的宽度(或设置自身宽度)。
## en-US
`lines` attribute specifies the maximum number of rows where the text will automatically be truncated when exceeded. In this mode, all children will be converted to plain text.
Also note that, in this mode, the outer container needs to have a specified width (or set its own width).
````jsx
import Ellipsis from 'ant-design-pro/lib/Ellipsis';
const article = <p>There were injuries alleged in three <a href="#cover">cases in 2015</a>, and a fourth incident in September, according to the safety recall report. After meeting with US regulators in October, the firm decided to issue a voluntary recall.</p>;
ReactDOM.render(
<div style={{ width: 200 }}>
<Ellipsis tooltip lines={3}>{article}</Ellipsis>
</div>
, mountNode);
````
---
order: 0
title:
zh-CN: 按照字符数省略
en-US: Truncate according to the number of character
---
## zh-CN
通过设置 `length` 属性指定文本最长长度,如果超过这个长度会自动截取。
## en-US
`length` attribute specifies the maximum length where the text will automatically be truncated when exceeded.
````jsx
import Ellipsis from 'ant-design-pro/lib/Ellipsis';
const article = 'There were injuries alleged in three cases in 2015, and a fourth incident in September, according to the safety recall report. After meeting with US regulators in October, the firm decided to issue a voluntary recall.';
ReactDOM.render(
<div>
<Ellipsis length={100}>{article}</Ellipsis>
<h4 style={{ marginTop: 24 }}>Show Tooltip</h4>
<Ellipsis length={100} tooltip>{article}</Ellipsis>
</div>
, mountNode);
````
import * as React from 'react';
import { TooltipProps } from 'antd/lib/tooltip';
export interface IEllipsisTooltipProps extends TooltipProps {
title?: undefined;
overlayStyle?: undefined;
}
export interface IEllipsisProps {
tooltip?: boolean | IEllipsisTooltipProps;
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<IEllipsisProps, any> {}
---
title: Ellipsis
cols: 1
order: 10
---
When the text is too long, the Ellipsis automatically shortens it according to its length or the maximum number of lines.
## API
Property | Description | Type | Default
----|------|-----|------
tooltip | tooltip for showing the full text content when hovering over | boolean | -
length | maximum number of characters in the text before being truncated | number | -
lines | maximum number of rows in the text before being truncated | number | `1`
fullWidthRecognition | whether consider full-width character length as 2 when calculate string length | boolean | -
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 {
overflow: hidden;
display: inline-block;
word-break: break-all;
width: 100%;
}
.lines {
position: relative;
.shadow {
display: block;
position: absolute;
color: transparent;
opacity: 0;
z-index: -999;
}
}
.lineClamp {
position: relative;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
}
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');
});
});
---
title: Ellipsis
subtitle: 文本自动省略号
cols: 1
order: 10
---
文本过长自动处理省略号,支持按照文本长度和最大行数两种方式截取。
## API
参数 | 说明 | 类型 | 默认值
----|------|-----|------
tooltip | 移动到文本展示完整内容的提示 | boolean | -
length | 在按照长度截取下的文本最大字符数,超过则截取省略 | number | -
lines | 在按照行数截取下最大的行数,超过则截取省略 | number | `1`
fullWidthRecognition | 是否将全角字符的长度视为2来计算字符串长度 | boolean | -
---
order: 2
title:
zh-CN: 403
en-US: 403
---
## zh-CN
403 页面,配合自定义操作。
## en-US
403 page with custom operations.
````jsx
import Exception from 'ant-design-pro/lib/Exception';
import { Button } from 'antd';
const actions = (
<div>
<Button type="primary">Home</Button>
<Button>Detail</Button>
</div>
);
ReactDOM.render(
<Exception type="403" actions={actions} />
, mountNode);
````
---
order: 0
title:
zh-CN: 404
en-US: 404
---
## zh-CN
404 页面。
## en-US
404 page.
````jsx
import Exception from 'ant-design-pro/lib/Exception';
ReactDOM.render(
<Exception type="404" />
, mountNode);
````
---
order: 1
title:
zh-CN: 500
en-US: 500
---
## zh-CN
500 页面。
## en-US
500 page.
````jsx
import Exception from 'ant-design-pro/lib/Exception';
ReactDOM.render(
<Exception type="500" />
, mountNode);
````
import * as React from 'react';
export interface IExceptionProps {
type?: '403' | '404' | '500';
title?: React.ReactNode;
desc?: React.ReactNode;
img?: string;
actions?: React.ReactNode;
linkElement?: string | React.ComponentType;
style?: React.CSSProperties;
className?: string;
backText?: React.ReactNode;
redirect?: string;
}
export default class Exception extends React.Component<IExceptionProps, any> {}
---
title: Exception
cols: 1
order: 5
---
Exceptions page is used to provide feedback on specific abnormal state. Usually, it contains an explanation of the error status, and provides users with suggestions or operations, to prevent users from feeling lost and confused.
## API
Property | Description | Type | Default
---------|-------------|------|--------
| backText | default return button text | ReactNode | back to home |
type | type of exception, the corresponding default `title`, `desc`, `img` will be given if set, which can be overridden by explicit setting of `title`, `desc`, `img` | Enum {'403', '404', '500'} | -
title | title | ReactNode | -
desc | supplementary description | ReactNode | -
img | the url of background image | string | -
actions | suggested operations, a default 'Home' link will show if not set | ReactNode | -
linkElement | to specify the element of link | string\|ReactElement | 'a'
redirect | redirect path | string | '/'
\ No newline at end of file
import React, { createElement } from 'react';
import classNames from 'classnames';
import { Button } from 'antd';
import config from './typeConfig';
import styles from './index.less';
class Exception extends React.PureComponent {
static defaultProps = {
backText: 'back to home',
redirect: '/',
};
constructor(props) {
super(props);
this.state = {};
}
render() {
const {
className,
backText,
linkElement = 'a',
type,
title,
desc,
img,
actions,
redirect,
...rest
} = this.props;
const pageType = type in config ? type : '404';
const clsString = classNames(styles.exception, className);
return (
<div className={clsString} {...rest}>
<div className={styles.imgBlock}>
<div
className={styles.imgEle}
style={{ backgroundImage: `url(${img || config[pageType].img})` }}
/>
</div>
<div className={styles.content}>
<h1>{title || config[pageType].title}</h1>
<div className={styles.desc}>{desc || config[pageType].desc}</div>
<div className={styles.actions}>
{actions ||
createElement(
linkElement,
{
to: redirect,
href: redirect,
},
<Button type="primary">{backText}</Button>
)}
</div>
</div>
</div>
);
}
}
export default Exception;
@import '~antd/lib/style/themes/default.less';
.exception {
display: flex;
align-items: center;
height: 80%;
min-height: 500px;
.imgBlock {
flex: 0 0 62.5%;
width: 62.5%;
padding-right: 152px;
zoom: 1;
&:before,
&:after {
content: ' ';
display: table;
}
&:after {
clear: both;
visibility: hidden;
font-size: 0;
height: 0;
}
}
.imgEle {
height: 360px;
width: 100%;
max-width: 430px;
float: right;
background-repeat: no-repeat;
background-position: 50% 50%;
background-size: contain;
}
.content {
flex: auto;
h1 {
color: #434e59;
font-size: 72px;
font-weight: 600;
line-height: 72px;
margin-bottom: 24px;
}
.desc {
color: @text-color-secondary;
font-size: 20px;
line-height: 28px;
margin-bottom: 16px;
}
.actions {
button:not(:last-child) {
margin-right: 8px;
}
}
}
}
@media screen and (max-width: @screen-xl) {
.exception {
.imgBlock {
padding-right: 88px;
}
}
}
@media screen and (max-width: @screen-sm) {
.exception {
display: block;
text-align: center;
.imgBlock {
padding-right: 0;
margin: 0 auto 24px;
}
}
}
@media screen and (max-width: @screen-xs) {
.exception {
.imgBlock {
margin-bottom: -24px;
overflow: hidden;
}
}
}
---
title: Exception
subtitle: 异常
cols: 1
order: 5
---
异常页用于对页面特定的异常状态进行反馈。通常,它包含对错误状态的阐述,并向用户提供建议或操作,避免用户感到迷失和困惑。
## API
| 参数 | 说明| 类型 | 默认值 |
|-------------|------------------------------------------|-------------|-------|
| backText| 默认的返回按钮文本 | ReactNode| back to home |
| type| 页面类型,若配置,则自带对应类型默认的 `title``desc``img`,此默认设置可以被 `title``desc``img` 覆盖 | Enum {'403', '404', '500'} | - |
| title | 标题 | ReactNode| -|
| desc| 补充描述| ReactNode| -|
| img | 背景图片地址 | string| -|
| actions | 建议操作,配置此属性时默认的『返回首页』按钮不生效| ReactNode| -|
| linkElement | 定义链接的元素 | string\|ReactElement | 'a' |
| redirect | 返回按钮的跳转地址 | string | '/'
const config = {
403: {
img: 'https://gw.alipayobjects.com/zos/rmsportal/wZcnGqRDyhPOEYFcZDnb.svg',
title: '403',
desc: '抱歉,你无权访问该页面',
},
404: {
img: 'https://gw.alipayobjects.com/zos/rmsportal/KpnpchXsobRgLElEozzI.svg',
title: '404',
desc: '抱歉,你访问的页面不存在',
},
500: {
img: 'https://gw.alipayobjects.com/zos/rmsportal/RVRUAYdCGeYNBWoKiIwB.svg',
title: '500',
desc: '抱歉,服务器出错了',
},
};
export default config;
---
order: 0
title:
zh-CN: 演示
en-US: demo
iframe: 400
---
## zh-CN
浮动固定页脚。
## en-US
Fixed to the footer.
````jsx
import FooterToolbar from 'ant-design-pro/lib/FooterToolbar';
import { Button } from 'antd';
ReactDOM.render(
<div style={{ background: '#f7f7f7', padding: 24 }}>
<p>Content Content Content Content</p>
<p>Content Content Content Content</p>
<p>Content Content Content Content</p>
<p>Content Content Content Content</p>
<p>Content Content Content Content</p>
<p>Content Content Content Content</p>
<p>Content Content Content Content</p>
<p>Content Content Content Content</p>
<p>Content Content Content Content</p>
<p>Content Content Content Content</p>
<p>Content Content Content Content</p>
<p>Content Content Content Content</p>
<p>Content Content Content Content</p>
<p>Content Content Content Content</p>
<p>Content Content Content Content</p>
<FooterToolbar extra="extra information">
<Button>Cancel</Button>
<Button type="primary">Submit</Button>
</FooterToolbar>
</div>
, mountNode);
````
\ No newline at end of file
import * as React from 'react';
export interface IFooterToolbarProps {
extra: React.ReactNode;
style?: React.CSSProperties;
}
export default class FooterToolbar extends React.Component<IFooterToolbarProps, any> {}
---
title: FooterToolbar
cols: 1
order: 6
---
A toolbar fixed at the bottom.
## Usage
It is fixed at the bottom of the content area and does not move along with the scroll bar, which is usually used for data collection and submission for long pages.
## API
Property | Description | Type | Default
---------|-------------|------|--------
children | toolbar content, align to the right | ReactNode | -
extra | extra information, align to the left | ReactNode | -
\ No newline at end of file
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import styles from './index.less';
export default class FooterToolbar extends Component {
static contextTypes = {
isMobile: PropTypes.bool,
};
state = {
width: undefined,
};
componentDidMount() {
window.addEventListener('resize', this.resizeFooterToolbar);
this.resizeFooterToolbar();
}
componentWillUnmount() {
window.removeEventListener('resize', this.resizeFooterToolbar);
}
resizeFooterToolbar = () => {
const sider = document.querySelector('.ant-layout-sider');
if (sider == null) {
return;
}
const { isMobile } = this.context;
const width = isMobile ? null : `calc(100% - ${sider.style.width})`;
const { width: stateWidth } = this.state;
if (stateWidth !== width) {
this.setState({ width });
}
};
render() {
const { children, className, extra, ...restProps } = this.props;
const { width } = this.state;
return (
<div className={classNames(className, styles.toolbar)} style={{ width }} {...restProps}>
<div className={styles.left}>{extra}</div>
<div className={styles.right}>{children}</div>
</div>
);
}
}
@import '~antd/lib/style/themes/default.less';
.toolbar {
position: fixed;
width: 100%;
bottom: 0;
right: 0;
height: 56px;
line-height: 56px;
box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.03);
background: #fff;
border-top: 1px solid @border-color-split;
padding: 0 24px;
z-index: 9;
&:after {
content: '';
display: block;
clear: both;
}
.left {
float: left;
}
.right {
float: right;
}
button + button {
margin-left: 8px;
}
}
---
title: FooterToolbar
subtitle: 底部工具栏
cols: 1
order: 6
---
固定在底部的工具栏。
## 何时使用
固定在内容区域的底部,不随滚动条移动,常用于长页面的数据搜集和提交工作。
## API
参数 | 说明 | 类型 | 默认值
----|------|-----|------
children | 工具栏内容,向右对齐 | ReactNode | -
extra | 额外信息,向左对齐 | ReactNode | -
---
order: 0
title: 演示
iframe: 400
---
基本页脚。
````jsx
import GlobalFooter from 'ant-design-pro/lib/GlobalFooter';
import { Icon } from 'antd';
const links = [{
key: '帮助',
title: '帮助',
href: '',
}, {
key: 'github',
title: <Icon type="github" />,
href: 'https://github.com/ant-design/ant-design-pro',
blankTarget: true,
}, {
key: '条款',
title: '条款',
href: '',
blankTarget: true,
}];
const copyright = <div>Copyright <Icon type="copyright" /> 2017 蚂蚁金服体验技术部出品</div>;
ReactDOM.render(
<div style={{ background: '#f5f5f5', overflow: 'hidden' }}>
<div style={{ height: 280 }} />
<GlobalFooter links={links} copyright={copyright} />
</div>
, mountNode);
````
import * as React from 'react';
export interface IGlobalFooterProps {
links?: Array<{
key?: string;
title: React.ReactNode;
href: string;
blankTarget?: boolean;
}>;
copyright?: React.ReactNode;
style?: React.CSSProperties;
}
export default class GlobalFooter extends React.Component<IGlobalFooterProps, any> {}
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;
@import '~antd/lib/style/themes/default.less';
.globalFooter {
padding: 0 16px;
margin: 48px 0 24px 0;
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;
}
}
---
title:
en-US: GlobalFooter
zh-CN: GlobalFooter
subtitle: 全局页脚
cols: 1
order: 7
---
页脚属于全局导航的一部分,作为对顶部导航的补充,通过传递数据控制展示内容。
## API
参数 | 说明 | 类型 | 默认值
----|------|-----|------
links | 链接数据 | array<{ title: ReactNode, href: string, blankTarget?: boolean }> | -
copyright | 版权信息 | ReactNode | -
...@@ -3,7 +3,7 @@ import { FormattedMessage, formatMessage } from 'umi/locale'; ...@@ -3,7 +3,7 @@ import { FormattedMessage, formatMessage } from 'umi/locale';
import { Spin, Tag, Menu, Icon, Avatar, Tooltip } from 'antd'; import { Spin, Tag, Menu, Icon, Avatar, Tooltip } from 'antd';
import moment from 'moment'; import moment from 'moment';
import groupBy from 'lodash/groupBy'; import groupBy from 'lodash/groupBy';
import NoticeIcon from '../NoticeIcon'; import NoticeIcon from 'ant-design-pro/lib/NoticeIcon';
import HeaderSearch from '../HeaderSearch'; import HeaderSearch from '../HeaderSearch';
import HeaderDropdown from '../HeaderDropdown'; import HeaderDropdown from '../HeaderDropdown';
import SelectLang from '../SelectLang'; import SelectLang from '../SelectLang';
......
import * as React from 'react';
export interface ILoginItemProps {
name?: string;
rules?: any[];
style?: React.CSSProperties;
onGetCaptcha?: () => void;
placeholder?: string;
buttonText?: React.ReactNode;
}
export class LoginItem extends React.Component<ILoginItemProps, any> {}
import React, { Component } from 'react';
import { Form, Input, Button, Row, Col } from 'antd';
import omit from 'omit.js';
import styles from './index.less';
import ItemMap from './map';
import LoginContext from './loginContext';
const FormItem = Form.Item;
class WrapFormItem extends Component {
static defaultProps = {
getCaptchaButtonText: 'captcha',
getCaptchaSecondText: 'second',
};
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
componentDidMount() {
const { updateActive, name } = this.props;
if (updateActive) {
updateActive(name);
}
}
componentWillUnmount() {
clearInterval(this.interval);
}
onGetCaptcha = () => {
const { onGetCaptcha } = this.props;
const result = onGetCaptcha ? onGetCaptcha() : null;
if (result === false) {
return;
}
if (result instanceof Promise) {
result.then(this.runGetCaptchaCountDown);
} else {
this.runGetCaptchaCountDown();
}
};
getFormItemOptions = ({ onChange, defaultValue, customprops, rules }) => {
const options = {
rules: rules || customprops.rules,
};
if (onChange) {
options.onChange = onChange;
}
if (defaultValue) {
options.initialValue = defaultValue;
}
return options;
};
runGetCaptchaCountDown = () => {
const { countDown } = this.props;
let count = countDown || 59;
this.setState({ count });
this.interval = setInterval(() => {
count -= 1;
this.setState({ count });
if (count === 0) {
clearInterval(this.interval);
}
}, 1000);
};
render() {
const { count } = this.state;
const {
form: { getFieldDecorator },
} = this.props;
// 这么写是为了防止restProps中 带入 onChange, defaultValue, rules props
const {
onChange,
customprops,
defaultValue,
rules,
name,
getCaptchaButtonText,
getCaptchaSecondText,
updateActive,
type,
...restProps
} = this.props;
// get getFieldDecorator props
const options = this.getFormItemOptions(this.props);
const otherProps = restProps || {};
if (type === 'Captcha') {
const inputProps = omit(otherProps, ['onGetCaptcha', 'countDown']);
return (
<FormItem>
<Row gutter={8}>
<Col span={16}>
{getFieldDecorator(name, options)(<Input {...customprops} {...inputProps} />)}
</Col>
<Col span={8}>
<Button
disabled={count}
className={styles.getCaptcha}
size="large"
onClick={this.onGetCaptcha}
>
{count ? `${count} ${getCaptchaSecondText}` : getCaptchaButtonText}
</Button>
</Col>
</Row>
</FormItem>
);
}
return (
<FormItem>
{getFieldDecorator(name, options)(<Input {...customprops} {...otherProps} />)}
</FormItem>
);
}
}
const LoginItem = {};
Object.keys(ItemMap).forEach(key => {
const item = ItemMap[key];
LoginItem[key] = props => (
<LoginContext.Consumer>
{context => (
<WrapFormItem
customprops={item.props}
rules={item.rules}
{...props}
type={key}
updateActive={context.updateActive}
form={context.form}
/>
)}
</LoginContext.Consumer>
);
});
export default LoginItem;
import React from 'react';
import classNames from 'classnames';
import { Button, Form } from 'antd';
import styles from './index.less';
const FormItem = Form.Item;
const LoginSubmit = ({ className, ...rest }) => {
const clsString = classNames(styles.submit, className);
return (
<FormItem>
<Button size="large" className={clsString} type="primary" htmlType="submit" {...rest} />
</FormItem>
);
};
export default LoginSubmit;
import * as React from 'react';
export interface ILoginTabProps {
key?: string;
tab?: React.ReactNode;
}
export default class LoginTab extends React.Component<ILoginTabProps, any> {}
import React, { Component } from 'react';
import { Tabs } from 'antd';
import LoginContext from './loginContext';
const { TabPane } = Tabs;
const generateId = (() => {
let i = 0;
return (prefix = '') => {
i += 1;
return `${prefix}${i}`;
};
})();
class LoginTab extends Component {
constructor(props) {
super(props);
this.uniqueId = generateId('login-tab-');
}
componentDidMount() {
const { tabUtil } = this.props;
tabUtil.addTab(this.uniqueId);
}
render() {
const { children } = this.props;
return <TabPane {...this.props}>{children}</TabPane>;
}
}
const wrapContext = props => (
<LoginContext.Consumer>
{value => <LoginTab tabUtil={value.tabUtil} {...props} />}
</LoginContext.Consumer>
);
// 标志位 用来判断是不是自定义组件
wrapContext.typeName = 'LoginTab';
export default wrapContext;
---
order: 0
title:
zh-CN: 标准登录
en-US: Standard Login
---
Support login with account and mobile number.
````jsx
import Login from 'ant-design-pro/lib/Login';
import { Alert, Checkbox } from 'antd';
const { Tab, UserName, Password, Mobile, Captcha, Submit } = Login;
class LoginDemo extends React.Component {
state = {
notice: '',
type: 'tab2',
autoLogin: true,
}
onSubmit = (err, values) => {
console.log('value collected ->', { ...values, autoLogin: this.state.autoLogin });
if (this.state.type === 'tab1') {
this.setState({
notice: '',
}, () => {
if (!err && (values.username !== 'admin' || values.password !== '888888')) {
setTimeout(() => {
this.setState({
notice: 'The combination of username and password is incorrect!',
});
}, 500);
}
});
}
}
onTabChange = (key) => {
this.setState({
type: key,
});
}
changeAutoLogin = (e) => {
this.setState({
autoLogin: e.target.checked,
});
}
render() {
return (
<Login
defaultActiveKey={this.state.type}
onTabChange={this.onTabChange}
onSubmit={this.onSubmit}
>
<Tab key="tab1" tab="Account">
{
this.state.notice &&
<Alert style={{ marginBottom: 24 }} message={this.state.notice} type="error" showIcon closable />
}
<UserName name="username" />
<Password name="password" />
</Tab>
<Tab key="tab2" tab="Mobile">
<Mobile name="mobile" />
<Captcha onGetCaptcha={() => console.log('Get captcha!')} name="captcha" />
</Tab>
<div>
<Checkbox checked={this.state.autoLogin} onChange={this.changeAutoLogin}>Keep me logged in</Checkbox>
<a style={{ float: 'right' }} href="">Forgot password</a>
</div>
<Submit>Login</Submit>
<div>
Other login methods
<span className="icon icon-alipay" />
<span className="icon icon-taobao" />
<span className="icon icon-weibo" />
<a style={{ float: 'right' }} href="">Register</a>
</div>
</Login>
);
}
}
ReactDOM.render(<LoginDemo />, mountNode);
````
<style>
#scaffold-src-components-Login-demo-basic .icon {
display: inline-block;
width: 24px;
height: 24px;
background: url('https://gw.alipayobjects.com/zos/rmsportal/itDzjUnkelhQNsycranf.svg');
margin-left: 16px;
vertical-align: middle;
cursor: pointer;
}
#scaffold-src-components-Login-demo-basic .icon-alipay {
background-position: -24px 0;
}
#scaffold-src-components-Login-demo-basic .icon-alipay:hover {
background-position: 0 0;
}
#scaffold-src-components-Login-demo-basic .icon-taobao {
background-position: -24px -24px;
}
#scaffold-src-components-Login-demo-basic .icon-taobao:hover {
background-position: 0 -24px;
}
#scaffold-src-components-Login-demo-basic .icon-weibo {
background-position: -24px -48px;
}
#scaffold-src-components-Login-demo-basic .icon-weibo:hover {
background-position: 0 -48px;
}
</style>
import Button from 'antd/lib/button';
import * as React from 'react';
import LoginItem from './LoginItem';
import LoginTab from './LoginTab';
export interface ILoginProps {
defaultActiveKey?: string;
onTabChange?: (key: string) => void;
style?: React.CSSProperties;
onSubmit?: (error: any, values: any) => void;
}
export default class Login extends React.Component<ILoginProps, any> {
public static Tab: typeof LoginTab;
public static UserName: typeof LoginItem;
public static Password: typeof LoginItem;
public static Mobile: typeof LoginItem;
public static Captcha: typeof LoginItem;
public static Submit: typeof Button;
}
---
title: Login
cols: 1
order: 15
---
Support multiple common ways of login with built-in controls. You can choose your own combinations and use with your custom controls.
## API
### Login
Property | Description | Type | Default
----|------|-----|------
defaultActiveKey | default key to activate the tab panel | String | -
onTabChange | callback on changing tabs | (key) => void | -
onSubmit | callback on submit | (err, values) => void | -
### Login.Tab
Property | Description | Type | Default
----|------|-----|------
key | key of the tab | String | -
tab | displayed text of the tab | ReactNode | -
### Login.UserName
Property | Description | Type | Default
----|------|-----|------
name | name of the control, also the key of the submitted data | String | -
rules | validation rules, same with [option.rules](getFieldDecorator(id, options)) in Form getFieldDecorator(id, options) | object[] | -
Apart from the above properties, Login.Username also support all properties of antd.Input, together with the default values of basic settings, such as _placeholder_, _size_ and _prefix_. All of these default values can be over-written.
### Login.Password, Login.Mobile are the same as Login.UserName
### Login.Captcha
Property | Description | Type | Default
----|------|-----|------
onGetCaptcha | callback on getting a new Captcha | () => (void \| false \| Promise) | -
countDown | count down | number |-
buttonText | text on getting a new Captcha | ReactNode | '获取验证码'
Apart from the above properties, _Login.Captcha_ support the same properties with _Login.UserName_.
### Login.Submit
Support all properties of _antd.Button_.
\ No newline at end of file
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Form, Tabs } from 'antd';
import classNames from 'classnames';
import LoginItem from './LoginItem';
import LoginTab from './LoginTab';
import LoginSubmit from './LoginSubmit';
import styles from './index.less';
import LoginContext from './loginContext';
class Login extends Component {
static propTypes = {
className: PropTypes.string,
defaultActiveKey: PropTypes.string,
onTabChange: PropTypes.func,
onSubmit: PropTypes.func,
};
static defaultProps = {
className: '',
defaultActiveKey: '',
onTabChange: () => {},
onSubmit: () => {},
};
constructor(props) {
super(props);
this.state = {
type: props.defaultActiveKey,
tabs: [],
active: {},
};
}
onSwitch = type => {
this.setState({
type,
});
const { onTabChange } = this.props;
onTabChange(type);
};
getContext = () => {
const { tabs } = this.state;
const { form } = this.props;
return {
tabUtil: {
addTab: id => {
this.setState({
tabs: [...tabs, id],
});
},
removeTab: id => {
this.setState({
tabs: tabs.filter(currentId => currentId !== id),
});
},
},
form,
updateActive: activeItem => {
const { type, active } = this.state;
if (active[type]) {
active[type].push(activeItem);
} else {
active[type] = [activeItem];
}
this.setState({
active,
});
},
};
};
handleSubmit = e => {
e.preventDefault();
const { active, type } = this.state;
const { form, onSubmit } = this.props;
const activeFileds = active[type];
form.validateFields(activeFileds, { force: true }, (err, values) => {
onSubmit(err, values);
});
};
render() {
const { className, children } = this.props;
const { type, tabs } = this.state;
const TabChildren = [];
const otherChildren = [];
React.Children.forEach(children, item => {
if (!item) {
return;
}
// eslint-disable-next-line
if (item.type.typeName === 'LoginTab') {
TabChildren.push(item);
} else {
otherChildren.push(item);
}
});
return (
<LoginContext.Provider value={this.getContext()}>
<div className={classNames(className, styles.login)}>
<Form onSubmit={this.handleSubmit}>
{tabs.length ? (
<React.Fragment>
<Tabs
animated={false}
className={styles.tabs}
activeKey={type}
onChange={this.onSwitch}
>
{TabChildren}
</Tabs>
{otherChildren}
</React.Fragment>
) : (
children
)}
</Form>
</div>
</LoginContext.Provider>
);
}
}
Login.Tab = LoginTab;
Login.Submit = LoginSubmit;
Object.keys(LoginItem).forEach(item => {
Login[item] = LoginItem[item];
});
export default Form.create()(Login);
@import '~antd/lib/style/themes/default.less';
.login {
:global {
.ant-tabs .ant-tabs-bar {
border-bottom: 0;
margin-bottom: 24px;
text-align: center;
}
.ant-form-item {
margin: 0 2px 24px;
}
}
.getCaptcha {
display: block;
width: 100%;
}
.icon {
font-size: 24px;
color: rgba(0, 0, 0, 0.2);
margin-left: 16px;
vertical-align: middle;
cursor: pointer;
transition: color 0.3s;
&:hover {
color: @primary-color;
}
}
.other {
text-align: left;
margin-top: 24px;
line-height: 22px;
.register {
float: right;
}
}
.prefixIcon {
font-size: @font-size-base;
color: @disabled-color;
}
.submit {
width: 100%;
margin-top: 24px;
}
}
---
title: Login
subtitle: 登录
cols: 1
order: 15
---
支持多种登录方式切换,内置了几种常见的登录控件,可以灵活组合,也支持和自定义控件配合使用。
## API
### Login
参数 | 说明 | 类型 | 默认值
----|------|-----|------
defaultActiveKey | 默认激活 tab 面板的 key | String | -
onTabChange | 切换页签时的回调 | (key) => void | -
onSubmit | 点击提交时的回调 | (err, values) => void | -
### Login.Tab
参数 | 说明 | 类型 | 默认值
----|------|-----|------
key | 对应选项卡的 key | String | -
tab | 选项卡头显示文字 | ReactNode | -
### Login.UserName
参数 | 说明 | 类型 | 默认值
----|------|-----|------
name | 控件标记,提交数据中同样以此为 key | String | -
rules | 校验规则,同 Form getFieldDecorator(id, options) 中 [option.rules 的规则](getFieldDecorator(id, options)) | object[] | -
除上述属性以外,Login.UserName 还支持 antd.Input 的所有属性,并且自带默认的基础配置,包括 `placeholder` `size` `prefix` 等,这些基础配置均可被覆盖。
## Login.Password、Login.Mobile 同 Login.UserName
### Login.Captcha
参数 | 说明 | 类型 | 默认值
----|------|-----|------
onGetCaptcha | 点击获取校验码的回调 | () => (void \| false \| Promise) | -
countDown | 倒计时 | number |-
buttonText | 点击获取校验码的说明文字 | ReactNode | '获取验证码'
除上述属性以外,Login.Captcha 支持的属性与 Login.UserName 相同。
### Login.Submit
支持 antd.Button 的所有属性。
import { createContext } from 'react';
const LoginContext = createContext();
export default LoginContext;
import React from 'react';
import { Icon } from 'antd';
import styles from './index.less';
export default {
UserName: {
props: {
size: 'large',
id: 'userName',
prefix: <Icon type="user" className={styles.prefixIcon} />,
placeholder: 'admin',
},
rules: [
{
required: true,
message: 'Please enter username!',
},
],
},
Password: {
props: {
size: 'large',
prefix: <Icon type="lock" className={styles.prefixIcon} />,
type: 'password',
id: 'password',
placeholder: '888888',
},
rules: [
{
required: true,
message: 'Please enter password!',
},
],
},
Mobile: {
props: {
size: 'large',
prefix: <Icon type="mobile" className={styles.prefixIcon} />,
placeholder: 'mobile number',
},
rules: [
{
required: true,
message: 'Please enter mobile number!',
},
{
pattern: /^1\d{10}$/,
message: 'Wrong mobile number format!',
},
],
},
Captcha: {
props: {
size: 'large',
prefix: <Icon type="mail" className={styles.prefixIcon} />,
placeholder: 'captcha',
},
rules: [
{
required: true,
message: 'Please enter Captcha!',
},
],
},
};
import { SkeletonProps } from 'antd/lib/skeleton';
import * as React from 'react';
export interface INoticeIconData {
avatar?: string | React.ReactNode;
title?: React.ReactNode;
description?: React.ReactNode;
datetime?: React.ReactNode;
extra?: React.ReactNode;
style?: React.CSSProperties;
}
export interface INoticeIconTabProps {
count?: number;
emptyText?: React.ReactNode;
emptyImage?: string;
list?: INoticeIconData[];
loadedAll?: boolean;
loading?: boolean;
name?: string;
showClear?: boolean;
skeletonCount?: number;
skeletonProps?: SkeletonProps;
style?: React.CSSProperties;
title?: string;
}
export default class NoticeIconTab extends React.Component<INoticeIconTabProps, any> {}
import React from 'react';
import { Avatar, List, Skeleton } from 'antd';
import classNames from 'classnames';
import styles from './NoticeList.less';
let ListElement = null;
export default function NoticeList({
data = [],
onClick,
onClear,
title,
locale,
emptyText,
emptyImage,
loading,
onLoadMore,
visible,
loadedAll = true,
scrollToLoad = true,
showClear = true,
skeletonCount = 5,
skeletonProps = {},
}) {
if (data.length === 0) {
return (
<div className={styles.notFound}>
{emptyImage ? <img src={emptyImage} alt="not found" /> : null}
<div>{emptyText || locale.emptyText}</div>
</div>
);
}
const loadingList = Array.from({ length: loading ? skeletonCount : 0 }).map(() => ({ loading }));
const LoadMore = loadedAll ? (
<div className={classNames(styles.loadMore, styles.loadedAll)}>
<span>{locale.loadedAll}</span>
</div>
) : (
<div className={styles.loadMore} onClick={onLoadMore}>
<span>{locale.loadMore}</span>
</div>
);
const onScroll = event => {
if (!scrollToLoad || loading || loadedAll) return;
if (typeof onLoadMore !== 'function') return;
const { currentTarget: t } = event;
if (t.scrollHeight - t.scrollTop - t.clientHeight <= 40) {
onLoadMore(event);
ListElement = t;
}
};
if (!visible && ListElement) {
try {
ListElement.scrollTo(null, 0);
} catch (err) {
ListElement = null;
}
}
return (
<div>
<List className={styles.list} loadMore={LoadMore} onScroll={onScroll}>
{[...data, ...loadingList].map((item, i) => {
const itemCls = classNames(styles.item, {
[styles.read]: item.read,
});
// eslint-disable-next-line no-nested-ternary
const leftIcon = item.avatar ? (
typeof item.avatar === 'string' ? (
<Avatar className={styles.avatar} src={item.avatar} />
) : (
<span className={styles.iconElement}>{item.avatar}</span>
)
) : null;
return (
<List.Item className={itemCls} key={item.key || i} onClick={() => onClick(item)}>
<Skeleton avatar title={false} active {...skeletonProps} loading={item.loading}>
<List.Item.Meta
className={styles.meta}
avatar={leftIcon}
title={
<div className={styles.title}>
{item.title}
<div className={styles.extra}>{item.extra}</div>
</div>
}
description={
<div>
<div className={styles.description} title={item.description}>
{item.description}
</div>
<div className={styles.datetime}>{item.datetime}</div>
</div>
}
/>
</Skeleton>
</List.Item>
);
})}
</List>
{showClear ? (
<div className={styles.clear} onClick={onClear}>
{locale.clear} {title}
</div>
) : null}
</div>
);
}
@import '~antd/lib/style/themes/default.less';
.list {
max-height: 400px;
overflow: auto;
&::-webkit-scrollbar {
display: none;
}
.item {
transition: all 0.3s;
overflow: hidden;
cursor: pointer;
padding-left: 24px;
padding-right: 24px;
.meta {
width: 100%;
}
.avatar {
background: #fff;
margin-top: 4px;
}
.iconElement {
font-size: 32px;
}
&.read {
opacity: 0.4;
}
&:last-child {
border-bottom: 0;
}
&:hover {
background: @primary-1;
}
.title {
font-weight: normal;
margin-bottom: 8px;
}
.description {
font-size: 12px;
line-height: @line-height-base;
}
.datetime {
font-size: 12px;
margin-top: 4px;
line-height: @line-height-base;
}
.extra {
float: right;
color: @text-color-secondary;
font-weight: normal;
margin-right: 0;
margin-top: -1.5px;
}
}
.loadMore {
padding: 8px 0;
cursor: pointer;
color: @primary-6;
text-align: center;
&.loadedAll {
cursor: unset;
color: rgba(0, 0, 0, 0.25);
}
}
}
.notFound {
text-align: center;
padding: 73px 0 88px 0;
color: @text-color-secondary;
img {
display: inline-block;
margin-bottom: 16px;
height: 76px;
}
}
.clear {
height: 46px;
line-height: 46px;
text-align: center;
color: @text-color;
border-radius: 0 0 @border-radius-base @border-radius-base;
border-top: 1px solid @border-color-split;
transition: all 0.3s;
cursor: pointer;
&:hover {
color: @heading-color;
}
}
---
order: 1
title: 通知图标
---
通常用在导航工具栏上。
````jsx
import NoticeIcon from 'ant-design-pro/lib/NoticeIcon';
ReactDOM.render(<NoticeIcon count={5} />, mountNode);
````
---
order: 2
title: 带浮层卡片
---
点击展开通知卡片,展现多种类型的通知,通常放在导航工具栏。
````jsx
import NoticeIcon from 'ant-design-pro/lib/NoticeIcon';
import moment from 'moment';
import groupBy from 'lodash/groupBy';
import { Tag } from 'antd';
const data = [{
id: '000000001',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png',
title: '你收到了 14 份新周报',
datetime: '2017-08-09',
type: '通知',
}, {
id: '000000002',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png',
title: '你推荐的 曲妮妮 已通过第三轮面试',
datetime: '2017-08-08',
type: '通知',
}, {
id: '000000003',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/kISTdvpyTAhtGxpovNWd.png',
title: '这种模板可以区分多种通知类型',
datetime: '2017-08-07',
read: true,
type: '通知',
}, {
id: '000000004',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/GvqBnKhFgObvnSGkDsje.png',
title: '左侧图标用于区分不同的类型',
datetime: '2017-08-07',
type: '通知',
}, {
id: '000000005',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png',
title: '内容不要超过两行字,超出时自动截断',
datetime: '2017-08-07',
type: '通知',
}, {
id: '000000006',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/fcHMVNCjPOsbUGdEduuv.jpeg',
title: '曲丽丽 评论了你',
description: '描述信息描述信息描述信息',
datetime: '2017-08-07',
type: '消息',
clickClose: true,
}, {
id: '000000007',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/fcHMVNCjPOsbUGdEduuv.jpeg',
title: '朱偏右 回复了你',
description: '这种模板用于提醒谁与你发生了互动,左侧放『谁』的头像',
datetime: '2017-08-07',
type: '消息',
clickClose: true,
}, {
id: '000000008',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/fcHMVNCjPOsbUGdEduuv.jpeg',
title: '标题',
description: '这种模板用于提醒谁与你发生了互动,左侧放『谁』的头像',
datetime: '2017-08-07',
type: '消息',
clickClose: true,
}, {
id: '000000009',
title: '任务名称',
description: '任务需要在 2017-01-12 20:00 前启动',
extra: '未开始',
status: 'todo',
type: '待办',
}, {
id: '000000010',
title: '第三方紧急代码变更',
description: '冠霖提交于 2017-01-06,需在 2017-01-07 前完成代码变更任务',
extra: '马上到期',
status: 'urgent',
type: '待办',
}, {
id: '000000011',
title: '信息安全考试',
description: '指派竹尔于 2017-01-09 前完成更新并发布',
extra: '已耗时 8 天',
status: 'doing',
type: '待办',
}, {
id: '000000012',
title: 'ABCD 版本发布',
description: '冠霖提交于 2017-01-06,需在 2017-01-07 前完成代码变更任务',
extra: '进行中',
status: 'processing',
type: '待办',
}];
function onItemClick(item, tabProps) {
console.log(item, tabProps);
}
function onClear(tabTitle) {
console.log(tabTitle);
}
function getNoticeData(notices) {
if (notices.length === 0) {
return {};
}
const newNotices = notices.map((notice) => {
const newNotice = { ...notice };
if (newNotice.datetime) {
newNotice.datetime = moment(notice.datetime).fromNow();
}
// transform id to item key
if (newNotice.id) {
newNotice.key = newNotice.id;
}
if (newNotice.extra && newNotice.status) {
const color = ({
todo: '',
processing: 'blue',
urgent: 'red',
doing: 'gold',
})[newNotice.status];
newNotice.extra = <Tag color={color} style={{ marginRight: 0 }}>{newNotice.extra}</Tag>;
}
return newNotice;
});
return groupBy(newNotices, 'type');
}
const noticeData = getNoticeData(data);
ReactDOM.render(
<div
style={{
textAlign: 'right',
height: '64px',
lineHeight: '64px',
boxShadow: '0 1px 4px rgba(0,21,41,.12)',
padding: '0 32px',
width: '400px',
}}
>
<NoticeIcon
className="notice-icon"
count={5}
onItemClick={onItemClick}
onClear={onClear}
>
<NoticeIcon.Tab
list={noticeData['通知']}
title="通知"
emptyText="你已查看所有通知"
emptyImage="https://gw.alipayobjects.com/zos/rmsportal/wAhyIChODzsoKIOBHcBk.svg"
/>
<NoticeIcon.Tab
list={noticeData['消息']}
title="消息"
emptyText="您已读完所有消息"
emptyImage="https://gw.alipayobjects.com/zos/rmsportal/sAuJeJzSKbUmHfBQRzmZ.svg"
/>
<NoticeIcon.Tab
list={noticeData['待办']}
title="待办"
emptyText="你已完成所有待办"
emptyImage="https://gw.alipayobjects.com/zos/rmsportal/HsIsxMZiWKrNUavQUXqx.svg"
/>
</NoticeIcon>
</div>
, mountNode);
````
```css
```
import * as React from 'react';
import NoticeIconTab, { INoticeIconData } from './NoticeIconTab';
export interface INoticeIconProps {
count?: number;
bell?: React.ReactNode;
className?: string;
loading?: boolean;
onClear?: (tabName: string) => void;
onItemClick?: (item: INoticeIconData, tabProps: INoticeIconProps) => void;
onLoadMore?: (tabProps: INoticeIconProps) => void;
onTabChange?: (tabTile: string) => void;
style?: React.CSSProperties;
onPopupVisibleChange?: (visible: boolean) => void;
popupVisible?: boolean;
locale?: {
emptyText: string;
clear: string;
loadedAll: string;
loadMore: string;
};
clearClose?: boolean;
}
export default class NoticeIcon extends React.Component<INoticeIconProps, any> {
public static Tab: typeof NoticeIconTab;
}
---
title: NoticeIcon
subtitle: Notification Menu
cols: 1
order: 9
---
用在导航工具栏上,作为整个产品统一的通知中心。
## API
Property | Description | Type | Default
----|------|-----|------
count | Total number of messages | number | -
bell | Change the bell Icon | ReactNode | `<Icon type='bell' />`
loading | Popup card loading status | boolean | `false`
onClear | Click to clear button the callback | function(tabName) | -
onItemClick | Click on the list item's callback | function(item, tabProps) | -
onLoadMore | Callback of click for loading more | function(tabProps, event) | -
onPopupVisibleChange | Popup Card Showing or Hiding Callbacks | function(visible) | -
onTabChange | Switching callbacks for tabs | function(tabTitle) | -
popupVisible | Popup card display state | boolean | -
locale | Default message text | Object | `{ emptyText: 'No notifications', clear: 'Clear', loadedAll: 'Loaded', loadMore: 'Loading more' }`
clearClose | Close menu after clear | boolean | `false`
### NoticeIcon.Tab
Property | Description | Type | Default
----|------|-----|------
count | Unread messages count of this tab | number | list.length
emptyText | Message text when list is empty | ReactNode | -
emptyImage | Image when list is empty | string | -
list | List data, format refer to the following table | Array | `[]`
loadedAll | All messages have been loaded | boolean | `true`
loading | Loading status of this tab | boolean | `false`
name | identifier for message Tab | string | -
scrollToLoad | Scroll to load | boolean | `true`
skeletonCount | Number of skeleton when tab is loading | number | `5`
skeletonProps | Props of skeleton | SkeletonProps | `{}`
showClear | Clear button display status | boolean | `true`
title | header for message Tab | string | -
### Tab data
Property | Description | Type | Default
----|------|-----|------
avatar | avatar img url | string \| ReactNode | -
title | title | ReactNode | -
description | description info | ReactNode | -
datetime | Timestamps | ReactNode | -
extra | Additional information in the upper right corner of the list item | ReactNode | -
clickClose | Close menu after clicking list item | boolean | `false`
import React, { PureComponent, Fragment } from 'react';
import ReactDOM from 'react-dom';
import { Icon, Tabs, Badge, Spin } from 'antd';
import classNames from 'classnames';
import HeaderDropdown from '../HeaderDropdown';
import List from './NoticeList';
import styles from './index.less';
const { TabPane } = Tabs;
export default class NoticeIcon extends PureComponent {
static Tab = TabPane;
static defaultProps = {
onItemClick: () => {},
onPopupVisibleChange: () => {},
onTabChange: () => {},
onClear: () => {},
loading: false,
clearClose: false,
locale: {
emptyText: 'No notifications',
clear: 'Clear',
loadedAll: 'Loaded',
loadMore: 'Loading more',
},
emptyImage: 'https://gw.alipayobjects.com/zos/rmsportal/wAhyIChODzsoKIOBHcBk.svg',
};
state = {
visible: false,
};
onItemClick = (item, tabProps) => {
const { onItemClick } = this.props;
const { clickClose } = item;
onItemClick(item, tabProps);
if (clickClose) {
this.popover.click();
}
};
onClear = name => {
const { onClear, clearClose } = this.props;
onClear(name);
if (clearClose) {
this.popover.click();
}
};
onTabChange = tabType => {
const { onTabChange } = this.props;
onTabChange(tabType);
};
onLoadMore = (tabProps, event) => {
const { onLoadMore } = this.props;
onLoadMore(tabProps, event);
};
getNotificationBox() {
const { visible } = this.state;
const { children, loading, locale } = this.props;
if (!children) {
return null;
}
const panes = React.Children.map(children, child => {
const {
list,
title,
name,
count,
emptyText,
emptyImage,
showClear,
loadedAll,
scrollToLoad,
skeletonCount,
skeletonProps,
loading: tabLoading,
} = child.props;
const len = list && list.length ? list.length : 0;
const msgCount = count || count === 0 ? count : len;
const tabTitle = msgCount > 0 ? `${title} (${msgCount})` : title;
return (
<TabPane tab={tabTitle} key={name}>
<List
data={list}
emptyImage={emptyImage}
emptyText={emptyText}
loadedAll={loadedAll}
loading={tabLoading}
locale={locale}
onClear={() => this.onClear(name)}
onClick={item => this.onItemClick(item, child.props)}
onLoadMore={event => this.onLoadMore(child.props, event)}
scrollToLoad={scrollToLoad}
showClear={showClear}
skeletonCount={skeletonCount}
skeletonProps={skeletonProps}
title={title}
visible={visible}
/>
</TabPane>
);
});
return (
<Fragment>
<Spin spinning={loading} delay={0}>
<Tabs className={styles.tabs} onChange={this.onTabChange}>
{panes}
</Tabs>
</Spin>
</Fragment>
);
}
handleVisibleChange = visible => {
const { onPopupVisibleChange } = this.props;
this.setState({ visible });
onPopupVisibleChange(visible);
};
render() {
const { className, count, popupVisible, bell } = this.props;
const { visible } = this.state;
const noticeButtonClass = classNames(className, styles.noticeButton);
const notificationBox = this.getNotificationBox();
const NoticeBellIcon = bell || <Icon type="bell" className={styles.icon} />;
const trigger = (
<span className={classNames(noticeButtonClass, { opened: visible })}>
<Badge count={count} style={{ boxShadow: 'none' }} className={styles.badge}>
{NoticeBellIcon}
</Badge>
</span>
);
if (!notificationBox) {
return trigger;
}
const popoverProps = {};
if ('popupVisible' in this.props) {
popoverProps.visible = popupVisible;
}
return (
<HeaderDropdown
placement="bottomRight"
overlay={notificationBox}
overlayClassName={styles.popover}
trigger={['click']}
visible={visible}
onVisibleChange={this.handleVisibleChange}
{...popoverProps}
ref={node => (this.popover = ReactDOM.findDOMNode(node))} // eslint-disable-line
>
{trigger}
</HeaderDropdown>
);
}
}
@import '~antd/lib/style/themes/default.less';
.popover {
width: 336px;
}
.noticeButton {
cursor: pointer;
display: inline-block;
transition: all 0.3s;
}
.icon {
padding: 4px;
}
.tabs {
:global {
.ant-tabs-nav-scroll {
text-align: center;
}
.ant-tabs-bar {
margin-bottom: 0;
}
}
}
---
title: NoticeIcon
subtitle: 通知菜单
cols: 1
order: 9
---
用在导航工具栏上,作为整个产品统一的通知中心。
## API
参数 | 说明 | 类型 | 默认值
----|------|-----|------
count | 图标上的消息总数 | number | -
bell | translate this please -> Change the bell Icon | ReactNode | `<Icon type='bell' />`
loading | 弹出卡片加载状态 | boolean | `false`
onClear | 点击清空按钮的回调 | function(tabName) | -
onItemClick | 点击列表项的回调 | function(item, tabProps) | -
onLoadMore | 加载更多的回调 | function(tabProps, event) | -
onPopupVisibleChange | 弹出卡片显隐的回调 | function(visible) | -
onTabChange | 切换页签的回调 | function(tabTitle) | -
popupVisible | 控制弹层显隐 | boolean | -
locale | 默认文案 | Object | `{ emptyText: 'No notifications', clear: 'Clear', loadedAll: 'Loaded', loadMore: 'Loading more' }`
clearClose | 点击清空按钮后关闭通知菜单 | boolean | `false`
### NoticeIcon.Tab
参数 | 说明 | 类型 | 默认值
----|------|-----|------
count | 当前 Tab 未读消息数量 | number | list.length
emptyText | 针对每个 Tab 定制空数据文案 | ReactNode | -
emptyImage | 针对每个 Tab 定制空数据图片 | string | -
list | 列表数据,格式参照下表 | Array | `[]`
loadedAll | 已加载完所有消息 | boolean | `true`
loading | 当前 Tab 的加载状态 | boolean | `false`
name | 消息分类的标识符 | string | -
scrollToLoad | 允许滚动自加载 | boolean | `true`
skeletonCount | 加载时占位骨架的数量 | number | `5`
skeletonProps | 加载时占位骨架的属性 | SkeletonProps | `{}`
showClear | 是否显示清空按钮 | boolean | `true`
title | 消息分类的页签标题 | string | -
### Tab data
参数 | 说明 | 类型 | 默认值
----|------|-----|------
avatar | 头像图片链接 | string \| ReactNode | -
title | 标题 | ReactNode | -
description | 描述信息 | ReactNode | -
datetime | 时间戳 | ReactNode | -
extra | 额外信息,在列表项右上角 | ReactNode | -
clickClose | 点击列表项关闭通知菜单 | boolean | `false`
---
order: 0
title:
zh-CN: 演示
en-US: Demo
---
## zh-CN
各种数据文案的展现方式。
## en-US
Used for presenting various numerical data.
````jsx
import NumberInfo from 'ant-design-pro/lib/NumberInfo';
import numeral from 'numeral';
ReactDOM.render(
<div>
<NumberInfo
subTitle={<span>Visits this week</span>}
total={numeral(12321).format('0,0')}
status="up"
subTotal={17.1}
/>
</div>
, mountNode);
````
import * as React from 'react';
export interface INumberInfoProps {
title?: React.ReactNode | string;
subTitle?: React.ReactNode | string;
total?: React.ReactNode | string;
status?: 'up' | 'down';
theme?: string;
gap?: number;
subTotal?: number;
style?: React.CSSProperties;
}
export default class NumberInfo extends React.Component<INumberInfoProps, any> {}
---
title: NumberInfo
cols: 1
order: 10
---
Often used in data cards for highlighting the business data.
## API
Property | Description | Type | Default
----|------|-----|------
title | title | ReactNode\|string | -
subTitle | subtitle | ReactNode\|string | -
total | total amount | ReactNode\|string | -
subTotal | total amount of additional information | ReactNode\|string | -
status | increase state | 'up \| down' | -
theme | state style | string | 'light'
gap | set the spacing (pixels) between numbers and descriptions | number | 8
import React from 'react';
import { Icon } from 'antd';
import classNames from 'classnames';
import styles from './index.less';
const NumberInfo = ({ theme, title, subTitle, total, subTotal, status, suffix, gap, ...rest }) => (
<div
className={classNames(styles.numberInfo, {
[styles[`numberInfo${theme}`]]: theme,
})}
{...rest}
>
{title && (
<div className={styles.numberInfoTitle} title={typeof title === 'string' ? title : ''}>
{title}
</div>
)}
{subTitle && (
<div
className={styles.numberInfoSubTitle}
title={typeof subTitle === 'string' ? subTitle : ''}
>
{subTitle}
</div>
)}
<div className={styles.numberInfoValue} style={gap ? { marginTop: gap } : null}>
<span>
{total}
{suffix && <em className={styles.suffix}>{suffix}</em>}
</span>
{(status || subTotal) && (
<span className={styles.subTotal}>
{subTotal}
{status && <Icon type={`caret-${status}`} />}
</span>
)}
</div>
</div>
);
export default NumberInfo;
@import '~antd/lib/style/themes/default.less';
.numberInfo {
.suffix {
color: @text-color;
font-size: 16px;
font-style: normal;
margin-left: 4px;
}
.numberInfoTitle {
color: @text-color;
font-size: @font-size-lg;
margin-bottom: 16px;
transition: all 0.3s;
}
.numberInfoSubTitle {
color: @text-color-secondary;
font-size: @font-size-base;
height: 22px;
line-height: 22px;
overflow: hidden;
text-overflow: ellipsis;
word-break: break-all;
white-space: nowrap;
}
.numberInfoValue {
margin-top: 4px;
font-size: 0;
overflow: hidden;
text-overflow: ellipsis;
word-break: break-all;
white-space: nowrap;
& > span {
color: @heading-color;
display: inline-block;
line-height: 32px;
height: 32px;
font-size: 24px;
margin-right: 32px;
}
.subTotal {
color: @text-color-secondary;
font-size: @font-size-lg;
vertical-align: top;
margin-right: 0;
i {
font-size: 12px;
transform: scale(0.82);
margin-left: 4px;
}
:global {
.anticon-caret-up {
color: @red-6;
}
.anticon-caret-down {
color: @green-6;
}
}
}
}
}
.numberInfolight {
.numberInfoValue {
& > span {
color: @text-color;
}
}
}
---
title: NumberInfo
subtitle: 数据文本
cols: 1
order: 10
---
常用在数据卡片中,用于突出展示某个业务数据。
## API
参数 | 说明 | 类型 | 默认值
----|------|-----|------
title | 标题 | ReactNode\|string | -
subTitle | 子标题 | ReactNode\|string | -
total | 总量 | ReactNode\|string | -
subTotal | 子总量 | ReactNode\|string | -
status | 增加状态 | 'up \| down' | -
theme | 状态样式 | string | 'light'
gap | 设置数字和描述之间的间距(像素)| number | 8
import * as React from 'react';
import { IPageHeaderProps } from './index';
export default class BreadcrumbView extends React.Component<IPageHeaderProps, any> {}
export function getBreadcrumb(breadcrumbNameMap: object, url: string): object;
import React, { PureComponent, createElement } from 'react';
import pathToRegexp from 'path-to-regexp';
import { Breadcrumb } from 'antd';
import styles from './index.less';
import { urlToList } from '../_utils/pathTools';
export const getBreadcrumb = (breadcrumbNameMap, url) => {
let breadcrumb = breadcrumbNameMap[url];
if (!breadcrumb) {
Object.keys(breadcrumbNameMap).forEach(item => {
if (pathToRegexp(item).test(url)) {
breadcrumb = breadcrumbNameMap[item];
}
});
}
return breadcrumb || {};
};
export default class BreadcrumbView extends PureComponent {
state = {
breadcrumb: null,
};
componentDidMount() {
this.getBreadcrumbDom();
}
componentDidUpdate(preProps) {
const { location } = this.props;
if (!location || !preProps.location) {
return;
}
const prePathname = preProps.location.pathname;
if (prePathname !== location.pathname) {
this.getBreadcrumbDom();
}
}
getBreadcrumbDom = () => {
const breadcrumb = this.conversionBreadcrumbList();
this.setState({
breadcrumb,
});
};
getBreadcrumbProps = () => {
const { routes, params, location, breadcrumbNameMap } = this.props;
return {
routes,
params,
routerLocation: location,
breadcrumbNameMap,
};
};
// Generated according to props
conversionFromProps = () => {
const { breadcrumbList, breadcrumbSeparator, itemRender, linkElement = 'a' } = this.props;
return (
<Breadcrumb className={styles.breadcrumb} separator={breadcrumbSeparator}>
{breadcrumbList.map(item => {
const title = itemRender ? itemRender(item) : item.title;
return (
<Breadcrumb.Item key={item.title}>
{item.href
? createElement(
linkElement,
{
[linkElement === 'a' ? 'href' : 'to']: item.href,
},
title
)
: title}
</Breadcrumb.Item>
);
})}
</Breadcrumb>
);
};
conversionFromLocation = (routerLocation, breadcrumbNameMap) => {
const { breadcrumbSeparator, home, itemRender, linkElement = 'a' } = this.props;
// Convert the url to an array
const pathSnippets = urlToList(routerLocation.pathname);
// Loop data mosaic routing
const extraBreadcrumbItems = pathSnippets.map((url, index) => {
const currentBreadcrumb = getBreadcrumb(breadcrumbNameMap, url);
if (currentBreadcrumb.inherited) {
return null;
}
const isLinkable = index !== pathSnippets.length - 1 && currentBreadcrumb.component;
const name = itemRender ? itemRender(currentBreadcrumb) : currentBreadcrumb.name;
return currentBreadcrumb.name && !currentBreadcrumb.hideInBreadcrumb ? (
<Breadcrumb.Item key={url}>
{createElement(
isLinkable ? linkElement : 'span',
{ [linkElement === 'a' ? 'href' : 'to']: url },
name
)}
</Breadcrumb.Item>
) : null;
});
// Add home breadcrumbs to your head
extraBreadcrumbItems.unshift(
<Breadcrumb.Item key="home">
{createElement(
linkElement,
{
[linkElement === 'a' ? 'href' : 'to']: '/',
},
home || 'Home'
)}
</Breadcrumb.Item>
);
return (
<Breadcrumb className={styles.breadcrumb} separator={breadcrumbSeparator}>
{extraBreadcrumbItems}
</Breadcrumb>
);
};
/**
* 将参数转化为面包屑
* Convert parameters into breadcrumbs
*/
conversionBreadcrumbList = () => {
const { breadcrumbList, breadcrumbSeparator } = this.props;
const { routes, params, routerLocation, breadcrumbNameMap } = this.getBreadcrumbProps();
if (breadcrumbList && breadcrumbList.length) {
return this.conversionFromProps();
}
// 如果传入 routes 和 params 属性
// If pass routes and params attributes
if (routes && params) {
return (
<Breadcrumb
className={styles.breadcrumb}
routes={routes.filter(route => route.breadcrumbName)}
params={params}
itemRender={this.itemRender}
separator={breadcrumbSeparator}
/>
);
}
// 根据 location 生成 面包屑
// Generate breadcrumbs based on location
if (routerLocation && routerLocation.pathname) {
return this.conversionFromLocation(routerLocation, breadcrumbNameMap);
}
return null;
};
// 渲染Breadcrumb 子节点
// Render the Breadcrumb child node
itemRender = (route, params, routes, paths) => {
const { linkElement = 'a' } = this.props;
const last = routes.indexOf(route) === routes.length - 1;
return last || !route.component ? (
<span>{route.breadcrumbName}</span>
) : (
createElement(
linkElement,
{
href: paths.join('/') || '/',
to: paths.join('/') || '/',
},
route.breadcrumbName
)
);
};
render() {
const { breadcrumb } = this.state;
return breadcrumb;
}
}
---
order: 2
title: With Image
---
带图片的页头。
````jsx
import PageHeader from 'ant-design-pro/lib/PageHeader';
const content = (
<div>
<p>段落示意:蚂蚁金服务设计平台 ant.design,用最小的工作量,无缝接入蚂蚁金服生态,提供跨越设计与开发的体验解决方案。</p>
<div className="link">
<a>
<img alt="" src="https://gw.alipayobjects.com/zos/rmsportal/MjEImQtenlyueSmVEfUD.svg" /> 快速开始
</a>
<a>
<img alt="" src="https://gw.alipayobjects.com/zos/rmsportal/NbuDUAuBlIApFuDvWiND.svg" /> 产品简介
</a>
<a>
<img alt="" src="https://gw.alipayobjects.com/zos/rmsportal/ohOEPSYdDTNnyMbGuyLb.svg" /> 产品文档
</a>
</div>
</div>
);
const extra = (
<div className="imgContainer">
<img style={{ width: '100%' }} alt="" src="https://gw.alipayobjects.com/zos/rmsportal/RzwpdLnhmvDJToTdfDPe.png" />
</div>
);
const breadcrumbList = [{
title: '一级菜单',
href: '/',
}, {
title: '二级菜单',
href: '/',
}, {
title: '三级菜单',
}];
ReactDOM.render(
<div>
<PageHeader
title="这是一个标题"
content={content}
extraContent={extra}
breadcrumbList={breadcrumbList}
/>
</div>
, mountNode);
````
<style>
#scaffold-src-components-PageHeader-demo-image .code-box-demo {
background: #f2f4f5;
}
#scaffold-src-components-PageHeader-demo-image .imgContainer {
margin-top: -60px;
text-align: center;
width: 195px;
}
#scaffold-src-components-PageHeader-demo-image .link {
margin-top: 16px;
}
#scaffold-src-components-PageHeader-demo-image .link a {
margin-right: 32px;
}
#scaffold-src-components-PageHeader-demo-image .link img {
vertical-align: middle;
margin-right: 8px;
}
</style>
---
order: 3
title: Simple
---
简单的页头。
````jsx
import PageHeader from 'ant-design-pro/lib/PageHeader';
const breadcrumbList = [{
title: '一级菜单',
href: '/',
}, {
title: '二级菜单',
href: '/',
}, {
title: '三级菜单',
}];
ReactDOM.render(
<div>
<PageHeader title="页面标题" breadcrumbList={breadcrumbList} />
</div>
, mountNode);
````
<style>
#scaffold-src-components-PageHeader-demo-simple .code-box-demo {
background: #f2f4f5;
}
</style>
---
order: 1
title: Standard
---
标准页头。
````jsx
import PageHeader from 'ant-design-pro/lib/PageHeader';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import { Button, Menu, Dropdown, Icon, Row, Col } from 'antd';
const { Description } = DescriptionList;
const ButtonGroup = Button.Group;
const description = (
<DescriptionList size="small" col="2">
<Description term="创建人">曲丽丽</Description>
<Description term="订购产品">XX 服务</Description>
<Description term="创建时间">2017-07-07</Description>
<Description term="关联单据"><a href="">12421</a></Description>
</DescriptionList>
);
const menu = (
<Menu>
<Menu.Item key="1">选项一</Menu.Item>
<Menu.Item key="2">选项二</Menu.Item>
<Menu.Item key="3">选项三</Menu.Item>
</Menu>
);
const action = (
<div>
<ButtonGroup>
<Button>操作</Button>
<Button>操作</Button>
<Dropdown overlay={menu} placement="bottomRight">
<Button><Icon type="ellipsis" /></Button>
</Dropdown>
</ButtonGroup>
<Button type="primary">主操作</Button>
</div>
);
const extra = (
<Row>
<Col sm={24} md={12}>
<div style={{ color: 'rgba(0, 0, 0, 0.43)' }}>状态</div>
<div style={{ color: 'rgba(0, 0, 0, 0.85)', fontSize: 20 }}>待审批</div>
</Col>
<Col sm={24} md={12}>
<div style={{ color: 'rgba(0, 0, 0, 0.43)' }}>订单金额</div>
<div style={{ color: 'rgba(0, 0, 0, 0.85)', fontSize: 20 }}>¥ 568.08</div>
</Col>
</Row>
);
const breadcrumbList = [{
title: '一级菜单',
href: '/',
}, {
title: '二级菜单',
href: '/',
}, {
title: '三级菜单',
}];
const tabList = [{
key: 'detail',
tab: '详情',
}, {
key: 'rule',
tab: '规则',
}];
function onTabChange(key) {
console.log(key);
}
ReactDOM.render(
<div>
<PageHeader
title="单号:234231029431"
logo={<img alt="" src="https://gw.alipayobjects.com/zos/rmsportal/nxkuOJlFJuAUhzlMTCEe.png" />}
action={action}
content={description}
extraContent={extra}
breadcrumbList={breadcrumbList}
tabList={tabList}
tabActiveKey="detail"
onTabChange={onTabChange}
/>
</div>
, mountNode);
````
<style>
#scaffold-src-components-PageHeader-demo-standard .code-box-demo {
background: #f2f4f5;
}
</style>
---
order: 0
title: Structure
---
基本结构,具备响应式布局功能,主要断点为 768px 和 576px,拖动窗口改变大小试试看。
````jsx
import PageHeader from 'ant-design-pro/lib/PageHeader';
const breadcrumbList = [{
title: '面包屑',
}];
const tabList = [{
key: '1',
tab: '页签一',
}, {
key: '2',
tab: '页签二',
}, {
key: '3',
tab: '页签三',
}];
ReactDOM.render(
<div>
<PageHeader
className="tabs"
title={<div className="title">Title</div>}
logo={<div className="logo">logo</div>}
action={<div className="action">action</div>}
content={<div className="content">content</div>}
extraContent={<div className="extraContent">extraContent</div>}
breadcrumbList={breadcrumbList}
tabList={tabList}
tabActiveKey="1"
/>
</div>
, mountNode);
````
<style>
#scaffold-src-components-PageHeader-demo-structure .code-box-demo {
background: #f2f4f5;
}
#scaffold-src-components-PageHeader-demo-structure .logo {
background: #3ba0e9;
color: #fff;
height: 100%;
}
#scaffold-src-components-PageHeader-demo-structure .title {
background: rgba(16, 142, 233, 1);
color: #fff;
}
#scaffold-src-components-PageHeader-demo-structure .action {
background: #7dbcea;
color: #fff;
}
#scaffold-src-components-PageHeader-demo-structure .content {
background: #7dbcea;
color: #fff;
}
#scaffold-src-components-PageHeader-demo-structure .extraContent {
background: #7dbcea;
color: #fff;
}
</style>
import * as React from 'react';
export interface IPageHeaderProps {
title?: React.ReactNode | string;
logo?: React.ReactNode | string;
action?: React.ReactNode | string;
content?: React.ReactNode;
extraContent?: React.ReactNode;
routes?: any[];
params?: any;
breadcrumbList?: Array<{ title: React.ReactNode; href?: string }>;
tabList?: Array<{ key: string; tab: React.ReactNode }>;
tabActiveKey?: string;
tabDefaultActiveKey?: string;
onTabChange?: (key: string) => void;
tabBarExtraContent?: React.ReactNode;
linkElement?: React.ReactNode;
style?: React.CSSProperties;
home?: React.ReactNode;
wide?: boolean;
hiddenBreadcrumb?: boolean;
}
export default class PageHeader extends React.Component<IPageHeaderProps, any> {}
import React, { PureComponent } from 'react';
import { Tabs, Skeleton } from 'antd';
import classNames from 'classnames';
import styles from './index.less';
import BreadcrumbView from './breadcrumb';
const { TabPane } = Tabs;
export default class PageHeader extends PureComponent {
onChange = key => {
const { onTabChange } = this.props;
if (onTabChange) {
onTabChange(key);
}
};
render() {
const {
title,
logo,
action,
content,
extraContent,
tabList,
className,
tabActiveKey,
tabDefaultActiveKey,
tabBarExtraContent,
loading = false,
wide = false,
hiddenBreadcrumb = false,
} = this.props;
const clsString = classNames(styles.pageHeader, className);
const activeKeyProps = {};
if (tabDefaultActiveKey !== undefined) {
activeKeyProps.defaultActiveKey = tabDefaultActiveKey;
}
if (tabActiveKey !== undefined) {
activeKeyProps.activeKey = tabActiveKey;
}
return (
<div className={clsString}>
<div className={wide ? styles.wide : ''}>
<Skeleton
loading={loading}
title={false}
active
paragraph={{ rows: 3 }}
avatar={{ size: 'large', shape: 'circle' }}
>
{hiddenBreadcrumb ? null : <BreadcrumbView {...this.props} />}
<div className={styles.detail}>
{logo && <div className={styles.logo}>{logo}</div>}
<div className={styles.main}>
<div className={styles.row}>
{title && <h1 className={styles.title}>{title}</h1>}
{action && <div className={styles.action}>{action}</div>}
</div>
<div className={styles.row}>
{content && <div className={styles.content}>{content}</div>}
{extraContent && <div className={styles.extraContent}>{extraContent}</div>}
</div>
</div>
</div>
{tabList && tabList.length ? (
<Tabs
className={styles.tabs}
{...activeKeyProps}
onChange={this.onChange}
tabBarExtraContent={tabBarExtraContent}
>
{tabList.map(item => (
<TabPane tab={item.tab} key={item.key} />
))}
</Tabs>
) : null}
</Skeleton>
</div>
</div>
);
}
}
@import '~antd/lib/style/themes/default.less';
.pageHeader {
background: @component-background;
padding: 16px 32px 0 32px;
border-bottom: @border-width-base @border-style-base @border-color-split;
.wide {
max-width: 1200px;
margin: auto;
}
.detail {
display: flex;
}
.row {
display: flex;
width: 100%;
}
.breadcrumb {
margin-bottom: 16px;
}
.tabs {
margin: 0 0 0 -8px;
:global {
// 1px 可以让选中效果显示完成
.ant-tabs-bar {
border-bottom: none;
margin-bottom: 1px;
}
}
}
.logo {
flex: 0 1 auto;
margin-right: 16px;
padding-top: 1px;
> img {
width: 28px;
height: 28px;
border-radius: @border-radius-base;
display: block;
}
}
.title {
font-size: 20px;
font-weight: 500;
color: @heading-color;
}
.action {
margin-left: 56px;
min-width: 266px;
:global {
.ant-btn-group:not(:last-child),
.ant-btn:not(:last-child) {
margin-right: 8px;
}
.ant-btn-group > .ant-btn {
margin-right: 0;
}
}
}
.title,
.content {
flex: auto;
}
.action,
.extraContent,
.main {
flex: 0 1 auto;
}
.main {
width: 100%;
}
.title,
.action {
margin-bottom: 16px;
}
.logo,
.content,
.extraContent {
margin-bottom: 16px;
}
.action,
.extraContent {
text-align: right;
}
.extraContent {
margin-left: 88px;
min-width: 242px;
}
}
@media screen and (max-width: @screen-xl) {
.pageHeader {
.extraContent {
margin-left: 44px;
}
}
}
@media screen and (max-width: @screen-lg) {
.pageHeader {
.extraContent {
margin-left: 20px;
}
}
}
@media screen and (max-width: @screen-md) {
.pageHeader {
.row {
display: block;
}
.action,
.extraContent {
margin-left: 0;
text-align: left;
}
}
}
@media screen and (max-width: @screen-sm) {
.pageHeader {
.detail {
display: block;
}
}
}
@media screen and (max-width: @screen-xs) {
.pageHeader {
.action {
:global {
.ant-btn-group,
.ant-btn {
display: block;
margin-bottom: 8px;
}
.ant-btn-group > .ant-btn {
display: inline-block;
margin-bottom: 0;
}
}
}
}
}
---
title:
en-US: PageHeader
zh-CN: PageHeader
subtitle: 页头
cols: 1
order: 11
---
页头用来声明页面的主题,包含了用户所关注的最重要的信息,使用户可以快速理解当前页面是什么以及它的功能。
## API
| 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------|
| title | title 区域 | ReactNode | - |
| logo | logo区域 | ReactNode | - |
| action | 操作区,位于 title 行的行尾 | ReactNode | - |
| home | 默认的主页说明文字 | ReactNode | - |
| content | 内容区 | ReactNode | - |
| extraContent | 额外内容区,位于content的右侧 | ReactNode | - |
| breadcrumbList | 面包屑数据,配置了此属性时 `routes` `params` `location` `breadcrumbNameMap` 无效 | array<{title: ReactNode, href?: string}> | - |
| hiddenBreadcrumb |隐藏面包屑 | boolean | false |
| routes | 面包屑相关属性,router 的路由栈信息 | object[] | - |
| params | 面包屑相关属性,路由的参数 | object | - |
| location | 面包屑相关属性,当前的路由信息 | object | - |
| breadcrumbNameMap | 面包屑相关属性,路由的地址-名称映射表 | object | - |
| tabList | tab 标题列表 | array<{key: string, tab: ReactNode}> | - |
| tabActiveKey | 当前高亮的 tab 项 | string | - |
| tabDefaultActiveKey | 默认高亮的 tab 项 | string | 第一项 |
| wide | 是否定宽 | boolean | false |
| onTabChange | 切换面板的回调 | (key) => void | - |
| itemRender | 自定义节点方法 | (menuItem) => ReactNode | - |
| linkElement | 定义链接的元素,默认为 `a`,可传入 react-router 的 Link | string\|ReactElement | - |
> 面包屑的配置方式有三种,一是直接配置 `breadcrumbList`,二是结合 `react-router@2` `react-router@3`,配置 `routes` 及 `params` 实现,类似 [面包屑 Demo](https://ant.design/components/breadcrumb-cn/#components-breadcrumb-demo-router),三是结合 `react-router@4`,配置 `location` `breadcrumbNameMap`,优先级依次递减,脚手架中使用最后一种。 对于后两种用法,你也可以将 `routes` `params` 及 `location` `breadcrumbNameMap` 放到 context 中,组件会自动获取。
import { getBreadcrumb } from './breadcrumb';
import { urlToList } from '../_utils/pathTools';
const routerData = {
'/dashboard/analysis': {
name: '分析页',
},
'/userinfo': {
name: '用户列表',
},
'/userinfo/:id': {
name: '用户信息',
},
'/userinfo/:id/addr': {
name: '收货订单',
},
};
describe('test getBreadcrumb', () => {
it('Simple url', () => {
expect(getBreadcrumb(routerData, '/dashboard/analysis').name).toEqual('分析页');
});
it('Parameters url', () => {
expect(getBreadcrumb(routerData, '/userinfo/2144').name).toEqual('用户信息');
});
it('The middle parameter url', () => {
expect(getBreadcrumb(routerData, '/userinfo/2144/addr').name).toEqual('收货订单');
});
it('Loop through the parameters', () => {
const urlNameList = urlToList('/userinfo/2144/addr').map(
url => getBreadcrumb(routerData, url).name
);
expect(urlNameList).toEqual(['用户列表', '用户信息', '收货订单']);
});
it('a path', () => {
const urlNameList = urlToList('/userinfo').map(url => getBreadcrumb(routerData, url).name);
expect(urlNameList).toEqual(['用户列表']);
});
it('Secondary path', () => {
const urlNameList = urlToList('/userinfo/2144').map(url => getBreadcrumb(routerData, url).name);
expect(urlNameList).toEqual(['用户列表', '用户信息']);
});
});
import React from 'react'; import React from 'react';
import { FormattedMessage } from 'umi/locale'; import { FormattedMessage } from 'umi/locale';
import Link from 'umi/link'; import Link from 'umi/link';
import PageHeader from '@/components/PageHeader'; import PageHeader from 'ant-design-pro/lib/PageHeader';
import { connect } from 'dva'; import { connect } from 'dva';
import GridContent from './GridContent'; import GridContent from './GridContent';
import styles from './index.less'; import styles from './index.less';
......
---
order: 1
title: Classic
---
典型结果页面。
````jsx
import Result from 'ant-design-pro/lib/Result';
import { Button, Row, Col, Icon, Steps } from 'antd';
const { Step } = Steps;
const desc1 = (
<div style={{ fontSize: 14, position: 'relative', left: 38 }}>
<div style={{ marginTop: 8, marginBottom: 4 }}>
曲丽丽
<Icon type="dingding" style={{ marginLeft: 8 }} />
</div>
<div style={{ marginTop: 8, marginBottom: 4 }}>2016-12-12 12:32</div>
</div>
);
const desc2 = (
<div style={{ fontSize: 14, position: 'relative', left: 38 }}>
<div style={{ marginTop: 8, marginBottom: 4 }}>
周毛毛
<Icon type="dingding" style={{ color: '#00A0E9', marginLeft: 8 }} />
</div>
<div style={{ marginTop: 8, marginBottom: 4 }}><a href="">催一下</a></div>
</div>
);
const extra = (
<div>
<div style={{ fontSize: 16, color: 'rgba(0, 0, 0, 0.85)', fontWeight: 500, marginBottom: 20 }}>
项目名称
</div>
<Row style={{ marginBottom: 16 }}>
<Col xs={24} sm={12} md={12} lg={12} xl={6}>
<span style={{ color: 'rgba(0, 0, 0, 0.85)' }}>项目 ID:</span>
23421
</Col>
<Col xs={24} sm={12} md={12} lg={12} xl={6}>
<span style={{ color: 'rgba(0, 0, 0, 0.85)' }}>负责人:</span>
曲丽丽
</Col>
<Col xs={24} sm={24} md={24} lg={24} xl={12}>
<span style={{ color: 'rgba(0, 0, 0, 0.85)' }}>生效时间:</span>
2016-12-12 ~ 2017-12-12
</Col>
</Row>
<Steps progressDot current={1}>
<Step title="创建项目" description={desc1} />
<Step title="部门初审" description={desc2} />
<Step title="财务复核" />
<Step title="完成" />
</Steps>
</div>
);
const actions = (
<div>
<Button type="primary">返回列表</Button>
<Button>查看项目</Button>
<Button>打 印</Button>
</div>
);
ReactDOM.render(
<Result
type="success"
title="提交成功"
description="提交结果页用于反馈一系列操作任务的处理结果,如果仅是简单操作,使用 Message 全局提示反馈即可。本文字区域可以展示简单的补充说明,如果有类似展示“单据”的需求,下面这个灰色区域可以呈现比较复杂的内容。"
extra={extra}
actions={actions}
style={{ width: '100%' }}
/>
, mountNode);
````
---
order: 2
title: Failed
---
提交失败。
````jsx
import Result from 'ant-design-pro/lib/Result';
import { Button, Icon } from 'antd';
const extra = (
<div>
<div style={{ fontSize: 16, color: 'rgba(0, 0, 0, 0.85)', fontWeight: 500, marginBottom: 16 }}>
您提交的内容有如下错误:
</div>
<div style={{ marginBottom: 16 }}>
<Icon style={{ color: '#f5222d', marginRight: 8 }} type="close-circle" />您的账户已被冻结
<a style={{ marginLeft: 16 }}>立即解冻 <Icon type="right" /></a>
</div>
<div>
<Icon style={{ color: '#f5222d', marginRight: 8 }} type="close-circle" />您的账户还不具备申请资格
<a style={{ marginLeft: 16 }}>立即升级 <Icon type="right" /></a>
</div>
</div>
);
const actions = <Button type="primary">返回修改</Button>;
ReactDOM.render(
<Result
type="error"
title="提交失败"
description="请核对并修改以下信息后,再重新提交。"
extra={extra}
actions={actions}
/>
, mountNode);
````
---
order: 0
title: Structure
---
结构包含 `处理结果``补充信息` 以及 `操作建议` 三个部分,其中 `处理结果``提示图标``标题``结果描述` 组成。
````jsx
import Result from 'ant-design-pro/lib/Result';
ReactDOM.render(
<Result
type="success"
title={<div style={{ background: '#7dbcea', color: '#fff' }}>标题</div>}
description={<div style={{ background: 'rgba(16, 142, 233, 1)', color: '#fff' }}>结果描述</div>}
extra="其他补充信息,自带灰底效果"
actions={<div style={{ background: '#3ba0e9', color: '#fff' }}>操作建议,一般放置按钮组</div>}
/>
, mountNode);
````
import * as React from 'react';
export interface IResultProps {
type: 'success' | 'error';
title: React.ReactNode;
description?: React.ReactNode;
extra?: React.ReactNode;
actions?: React.ReactNode;
style?: React.CSSProperties;
}
export default class Result extends React.Component<IResultProps, any> {}
import React from 'react';
import classNames from 'classnames';
import { Icon } from 'antd';
import styles from './index.less';
export default function Result({
className,
type,
title,
description,
extra,
actions,
...restProps
}) {
const iconMap = {
error: <Icon className={styles.error} type="close-circle" theme="filled" />,
success: <Icon className={styles.success} type="check-circle" theme="filled" />,
};
const clsString = classNames(styles.result, className);
return (
<div className={clsString} {...restProps}>
<div className={styles.icon}>{iconMap[type]}</div>
<div className={styles.title}>{title}</div>
{description && <div className={styles.description}>{description}</div>}
{extra && <div className={styles.extra}>{extra}</div>}
{actions && <div className={styles.actions}>{actions}</div>}
</div>
);
}
@import '~antd/lib/style/themes/default.less';
.result {
text-align: center;
width: 72%;
margin: 0 auto;
@media screen and (max-width: @screen-xs) {
width: 100%;
}
.icon {
font-size: 72px;
line-height: 72px;
margin-bottom: 24px;
& > .success {
color: @success-color;
}
& > .error {
color: @error-color;
}
}
.title {
font-size: 24px;
color: @heading-color;
font-weight: 500;
line-height: 32px;
margin-bottom: 16px;
}
.description {
font-size: 14px;
line-height: 22px;
color: @text-color-secondary;
margin-bottom: 24px;
}
.extra {
background: #fafafa;
padding: 24px 40px;
border-radius: @border-radius-sm;
text-align: left;
@media screen and (max-width: @screen-xs) {
padding: 18px 20px;
}
}
.actions {
margin-top: 32px;
button:not(:last-child) {
margin-right: 8px;
}
}
}
---
title:
en-US: Result
zh-CN: Result
subtitle: 处理结果
cols: 1
order: 12
---
结果页用于对用户进行的一系列任务处理结果进行反馈。
## API
| 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------|
| type | 类型,不同类型自带对应的图标 | Enum {'success', 'error'} | - |
| title | 标题 | ReactNode | - |
| description | 结果描述 | ReactNode | - |
| extra | 补充信息,有默认的灰色背景 | ReactNode | - |
| actions | 操作建议,推荐放置跳转链接,按钮组等 | ReactNode | - |
import * as React from 'react';
export interface ITagSelectOptionProps {
value: string | number;
style?: React.CSSProperties;
}
export default class TagSelectOption extends React.Component<ITagSelectOptionProps, any> {}
---
order: 3
title: 受控模式
---
结合 `Tag``TagSelect` 组件,方便的应用于筛选类目的业务场景中。
```jsx
import { Button } from 'antd';
import TagSelect from 'ant-design-pro/lib/TagSelect';
class Demo extends React.Component {
state = {
value: ['cat1'],
};
handleFormSubmit = value => {
this.setState({
value,
});
};
checkAll = () => {
this.setState({
value: ['cat1', 'cat2', 'cat3', 'cat4', 'cat5', 'cat6'],
});
};
render() {
return (
<div>
<Button onClick={this.checkAll}>全部</Button>
<div
style={{
padding: 16,
}}
>
<TagSelect hideCheckAll={true} value={this.state.value} onChange={this.handleFormSubmit}>
<TagSelect.Option value="cat1">类目一</TagSelect.Option>
<TagSelect.Option value="cat2">类目二</TagSelect.Option>
<TagSelect.Option value="cat3">类目三</TagSelect.Option>
<TagSelect.Option value="cat4">类目四</TagSelect.Option>
<TagSelect.Option value="cat5">类目五</TagSelect.Option>
<TagSelect.Option value="cat6">类目六</TagSelect.Option>
</TagSelect>
</div>
</div>
);
}
}
ReactDOM.render(<Demo />, mountNode);
```
---
order: 1
title: 可展开和收起
---
使用 `expandable` 属性,让标签组可以收起,避免过高。
````jsx
import TagSelect from 'ant-design-pro/lib/TagSelect';
function handleFormSubmit(checkedValue) {
console.log(checkedValue);
}
ReactDOM.render(
<TagSelect onChange={handleFormSubmit} expandable>
<TagSelect.Option value="cat1">类目一</TagSelect.Option>
<TagSelect.Option value="cat2">类目二</TagSelect.Option>
<TagSelect.Option value="cat3">类目三</TagSelect.Option>
<TagSelect.Option value="cat4">类目四</TagSelect.Option>
<TagSelect.Option value="cat5">类目五</TagSelect.Option>
<TagSelect.Option value="cat6">类目六</TagSelect.Option>
<TagSelect.Option value="cat7">类目七</TagSelect.Option>
<TagSelect.Option value="cat8">类目八</TagSelect.Option>
<TagSelect.Option value="cat9">类目九</TagSelect.Option>
<TagSelect.Option value="cat10">类目十</TagSelect.Option>
<TagSelect.Option value="cat11">类目十一</TagSelect.Option>
<TagSelect.Option value="cat12">类目十二</TagSelect.Option>
</TagSelect>
, mountNode);
````
---
order: 0
title: 基础样例
---
结合 `Tag``TagSelect` 组件,方便的应用于筛选类目的业务场景中。
````jsx
import TagSelect from 'ant-design-pro/lib/TagSelect';
function handleFormSubmit(checkedValue) {
console.log(checkedValue);
}
ReactDOM.render(
<TagSelect onChange={handleFormSubmit}>
<TagSelect.Option value="cat1">类目一</TagSelect.Option>
<TagSelect.Option value="cat2">类目二</TagSelect.Option>
<TagSelect.Option value="cat3">类目三</TagSelect.Option>
<TagSelect.Option value="cat4">类目四</TagSelect.Option>
<TagSelect.Option value="cat5">类目五</TagSelect.Option>
<TagSelect.Option value="cat6">类目六</TagSelect.Option>
</TagSelect>
, mountNode);
````
import * as React from 'react';
import TagSelectOption from './TagSelectOption';
export interface ITagSelectProps {
onChange?: (value: string[]) => void;
expandable?: boolean;
value?: string[] | number[];
style?: React.CSSProperties;
hideCheckAll?: boolean;
}
export default class TagSelect extends React.Component<ITagSelectProps, any> {
public static Option: typeof TagSelectOption;
private children:
| React.ReactElement<TagSelectOption>
| Array<React.ReactElement<TagSelectOption>>;
}
import React, { Component } from 'react';
import classNames from 'classnames';
import { Tag, Icon } from 'antd';
import styles from './index.less';
const { CheckableTag } = Tag;
const TagSelectOption = ({ children, checked, onChange, value }) => (
<CheckableTag checked={checked} key={value} onChange={state => onChange(value, state)}>
{children}
</CheckableTag>
);
TagSelectOption.isTagSelectOption = true;
class TagSelect extends Component {
static defaultProps = {
hideCheckAll: false,
};
constructor(props) {
super(props);
this.state = {
expand: false,
value: props.value || props.defaultValue || [],
};
}
static getDerivedStateFromProps(nextProps) {
if ('value' in nextProps) {
return { value: nextProps.value || [] };
}
return null;
}
onChange = value => {
const { onChange } = this.props;
if (!('value' in this.props)) {
this.setState({ value });
}
if (onChange) {
onChange(value);
}
};
onSelectAll = checked => {
let checkedTags = [];
if (checked) {
checkedTags = this.getAllTags();
}
this.onChange(checkedTags);
};
getAllTags() {
let { children } = this.props;
children = React.Children.toArray(children);
const checkedTags = children
.filter(child => this.isTagSelectOption(child))
.map(child => child.props.value);
return checkedTags || [];
}
handleTagChange = (value, checked) => {
const { value: StateValue } = this.state;
const checkedTags = [...StateValue];
const index = checkedTags.indexOf(value);
if (checked && index === -1) {
checkedTags.push(value);
} else if (!checked && index > -1) {
checkedTags.splice(index, 1);
}
this.onChange(checkedTags);
};
handleExpand = () => {
const { expand } = this.state;
this.setState({
expand: !expand,
});
};
isTagSelectOption = node =>
node &&
node.type &&
(node.type.isTagSelectOption || node.type.displayName === 'TagSelectOption');
render() {
const { value, expand } = this.state;
const { children, hideCheckAll, className, style, expandable } = this.props;
const checkedAll = this.getAllTags().length === value.length;
const cls = classNames(styles.tagSelect, className, {
[styles.hasExpandTag]: expandable,
[styles.expanded]: expand,
});
return (
<div className={cls} style={style}>
{hideCheckAll ? null : (
<CheckableTag checked={checkedAll} key="tag-select-__all__" onChange={this.onSelectAll}>
全部
</CheckableTag>
)}
{value &&
React.Children.map(children, child => {
if (this.isTagSelectOption(child)) {
return React.cloneElement(child, {
key: `tag-select-${child.props.value}`,
value: child.props.value,
checked: value.indexOf(child.props.value) > -1,
onChange: this.handleTagChange,
});
}
return child;
})}
{expandable && (
<a className={styles.trigger} onClick={this.handleExpand}>
{expand ? '收起' : '展开'} <Icon type={expand ? 'up' : 'down'} />
</a>
)}
</div>
);
}
}
TagSelect.Option = TagSelectOption;
export default TagSelect;
@import '~antd/lib/style/themes/default.less';
.tagSelect {
user-select: none;
margin-left: -8px;
position: relative;
overflow: hidden;
max-height: 32px;
line-height: 32px;
transition: all 0.3s;
:global {
.ant-tag {
padding: 0 8px;
margin-right: 24px;
font-size: @font-size-base;
}
}
&.expanded {
transition: all 0.3s;
max-height: 200px;
}
.trigger {
position: absolute;
top: 0;
right: 0;
i {
font-size: 12px;
}
}
&.hasExpandTag {
padding-right: 50px;
}
}
---
title:
en-US: TagSelect
zh-CN: TagSelect
subtitle: 标签选择器
cols: 1
order: 13
---
可进行多选,带折叠收起和展开更多功能,常用于对列表进行筛选。
## API
### TagSelect
| 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------|
| value |选中的项 |string[] \| number[] | |
| defaultValue |默认选中的项 |string[] \| number[] | |
| onChange | 标签选择的回调函数 | Function(checkedTags) | |
| expandable | 是否展示 `展开/收起` 按钮 | Boolean | false |
| hideCheckAll | 隐藏 `全部` 按钮 | Boolean | false |
### TagSelectOption
| 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------|
| value | TagSelect的值 | string\| number | - |
| children | tag的内容 | string \| ReactNode | - |
---
order: 0
title: 演示
---
在数值背后添加一个小图标来标识涨跌情况。
```jsx
import Trend from 'ant-design-pro/lib/Trend';
ReactDOM.render(
<div>
<Trend flag="up" >12%</Trend>
<Trend flag="down" style={{ marginLeft: 8 }}>11%</Trend>
</div>
, mountNode);
```
---
order: 0
title: 颜色反转
---
在数值背后添加一个小图标来标识涨跌情况。
```jsx
import Trend from 'ant-design-pro/lib/Trend';
ReactDOM.render(
<div>
<Trend flag="up" reverseColor={true} >12%</Trend>
<Trend flag="down" reverseColor={true} style={{ marginLeft: 8 }}>11%</Trend>
</div>
, mountNode);
```
import * as React from 'react';
export interface ITrendProps {
colorful?: boolean;
flag: 'up' | 'down';
style?: React.CSSProperties;
reverseColor?: boolean;
}
export default class Trend extends React.Component<ITrendProps, any> {}
import React from 'react';
import { Icon } from 'antd';
import classNames from 'classnames';
import styles from './index.less';
const Trend = ({ colorful = true, reverseColor = false, flag, children, className, ...rest }) => {
const classString = classNames(
styles.trendItem,
{
[styles.trendItemGrey]: !colorful,
[styles.reverseColor]: reverseColor && colorful,
},
className
);
return (
<div {...rest} className={classString} title={typeof children === 'string' ? children : ''}>
<span>{children}</span>
{flag && (
<span className={styles[flag]}>
<Icon type={`caret-${flag}`} />
</span>
)}
</div>
);
};
export default Trend;
@import '~antd/lib/style/themes/default.less';
.trendItem {
display: inline-block;
font-size: @font-size-base;
line-height: 22px;
.up,
.down {
margin-left: 4px;
position: relative;
top: 1px;
i {
font-size: 12px;
transform: scale(0.83);
}
}
.up {
color: @red-6;
}
.down {
color: @green-6;
top: -1px;
}
&.trendItemGrey .up,
&.trendItemGrey .down {
color: @text-color;
}
&.reverseColor .up {
color: @green-6;
}
&.reverseColor .down {
color: @red-6;
}
}
---
title:
en-US: Trend
zh-CN: Trend
subtitle: 趋势标记
cols: 1
order: 14
---
趋势符号,标记上升和下降趋势。通常用绿色代表“好”,红色代表“不好”,股票涨跌场景除外。
## API
```html
<Trend flag="up">50%</Trend>
```
| 参数 | 说明 | 类型 | 默认值 |
|----------|------------------------------------------|-------------|-------|
| colorful | 是否彩色标记 | Boolean | true |
| flag | 上升下降标识:`up|down` | string | - |
| reverseColor | 颜色反转 | Boolean | false |
import React from 'react'; import React from 'react';
import { notification, Button, message } from 'antd'; import { notification, Button, message } from 'antd';
import { formatMessage } from 'umi/locale'; import { formatMessage } from 'umi/locale';
import 'ant-design-pro/dist/ant-design-pro.css';
// Notify user if offline now // Notify user if offline now
window.addEventListener('sw.offline', () => { window.addEventListener('sw.offline', () => {
......
import React, { Fragment } from 'react'; import React, { Fragment } from 'react';
import { Layout, Icon } from 'antd'; import { Layout, Icon } from 'antd';
import GlobalFooter from '@/components/GlobalFooter'; import GlobalFooter from 'ant-design-pro/lib/GlobalFooter';
const { Footer } = Layout; const { Footer } = Layout;
const FooterView = () => ( const FooterView = () => (
......
...@@ -2,7 +2,7 @@ import React, { Fragment } from 'react'; ...@@ -2,7 +2,7 @@ import React, { Fragment } from 'react';
import { formatMessage } from 'umi/locale'; import { formatMessage } from 'umi/locale';
import Link from 'umi/link'; import Link from 'umi/link';
import { Icon } from 'antd'; import { Icon } from 'antd';
import GlobalFooter from '@/components/GlobalFooter'; import GlobalFooter from 'ant-design-pro/lib/GlobalFooter';
import SelectLang from '@/components/SelectLang'; import SelectLang from '@/components/SelectLang';
import styles from './UserLayout.less'; import styles from './UserLayout.less';
import logo from '../assets/logo.svg'; import logo from '../assets/logo.svg';
......
import React from 'react'; import React from 'react';
import Link from 'umi/link'; import Link from 'umi/link';
import { formatMessage } from 'umi/locale'; import { formatMessage } from 'umi/locale';
import Exception from '@/components/Exception'; import Exception from 'ant-design-pro/lib/Exception';
export default () => ( export default () => (
<Exception <Exception
......
...@@ -2,7 +2,7 @@ import React, { PureComponent } from 'react'; ...@@ -2,7 +2,7 @@ import React, { PureComponent } from 'react';
import { List, Card } from 'antd'; import { List, Card } from 'antd';
import moment from 'moment'; import moment from 'moment';
import { connect } from 'dva'; import { connect } from 'dva';
import AvatarList from '@/components/AvatarList'; import AvatarList from 'ant-design-pro/lib/AvatarList';
import stylesProjects from '../../List/Projects.less'; import stylesProjects from '../../List/Projects.less';
@connect(({ list }) => ({ @connect(({ list }) => ({
......
import React from 'react'; import React from 'react';
import RenderAuthorized from '@/components/Authorized'; import RenderAuthorized from 'ant-design-pro/lib/Authorized';
import { getAuthority } from '@/utils/authority'; import { getAuthority } from '@/utils/authority';
import Redirect from 'umi/redirect'; import Redirect from 'umi/redirect';
......
...@@ -2,8 +2,8 @@ import React, { memo } from 'react'; ...@@ -2,8 +2,8 @@ import React, { memo } from 'react';
import { Row, Col, Icon, Tooltip } from 'antd'; import { Row, Col, Icon, Tooltip } from 'antd';
import { FormattedMessage } from 'umi/locale'; import { FormattedMessage } from 'umi/locale';
import styles from './Analysis.less'; import styles from './Analysis.less';
import { ChartCard, MiniArea, MiniBar, MiniProgress, Field } from '@/components/Charts'; import { ChartCard, MiniArea, MiniBar, MiniProgress, Field } from 'ant-design-pro/lib/Charts';
import Trend from '@/components/Trend'; import Trend from 'ant-design-pro/lib/Trend';
import numeral from 'numeral'; import numeral from 'numeral';
import Yuan from '@/utils/Yuan'; import Yuan from '@/utils/Yuan';
......
...@@ -2,9 +2,9 @@ import React, { PureComponent } from 'react'; ...@@ -2,9 +2,9 @@ import React, { PureComponent } from 'react';
import { connect } from 'dva'; import { connect } from 'dva';
import { formatMessage, FormattedMessage } from 'umi/locale'; import { formatMessage, FormattedMessage } from 'umi/locale';
import { Row, Col, Card, Tooltip } from 'antd'; import { Row, Col, Card, Tooltip } from 'antd';
import { Pie, WaterWave, Gauge, TagCloud } from '@/components/Charts'; import { Pie, WaterWave, Gauge, TagCloud } from 'ant-design-pro/lib/Charts';
import NumberInfo from '@/components/NumberInfo'; import NumberInfo from 'ant-design-pro/lib/NumberInfo';
import CountDown from '@/components/CountDown'; import CountDown from 'ant-design-pro/lib/CountDown';
import ActiveChart from '@/components/ActiveChart'; import ActiveChart from '@/components/ActiveChart';
import numeral from 'numeral'; import numeral from 'numeral';
import GridContent from '@/components/PageHeaderWrapper/GridContent'; import GridContent from '@/components/PageHeaderWrapper/GridContent';
......
import React, { memo } from 'react'; import React, { memo } from 'react';
import { Card, Tabs, Row, Col } from 'antd'; import { Card, Tabs, Row, Col } from 'antd';
import { formatMessage, FormattedMessage } from 'umi/locale'; import { formatMessage, FormattedMessage } from 'umi/locale';
import { TimelineChart, Pie } from 'ant-design-pro/lib/Charts';
import NumberInfo from 'ant-design-pro/lib/NumberInfo';
import styles from './Analysis.less'; import styles from './Analysis.less';
import { TimelineChart, Pie } from '@/components/Charts';
import NumberInfo from '@/components/NumberInfo';
const CustomTab = ({ data, currentTabKey: currentKey }) => ( const CustomTab = ({ data, currentTabKey: currentKey }) => (
<Row gutter={8} style={{ width: 138, margin: '8px 0' }}> <Row gutter={8} style={{ width: 138, margin: '8px 0' }}>
......
...@@ -2,7 +2,7 @@ import React, { memo } from 'react'; ...@@ -2,7 +2,7 @@ import React, { memo } from 'react';
import { Card, Radio } from 'antd'; import { Card, Radio } from 'antd';
import { FormattedMessage } from 'umi/locale'; import { FormattedMessage } from 'umi/locale';
import styles from './Analysis.less'; import styles from './Analysis.less';
import { Pie } from '@/components/Charts'; import { Pie } from 'ant-design-pro/lib/Charts';
import Yuan from '@/utils/Yuan'; import Yuan from '@/utils/Yuan';
const ProportionSales = memo( const ProportionSales = memo(
......
...@@ -2,8 +2,8 @@ import React, { memo } from 'react'; ...@@ -2,8 +2,8 @@ import React, { memo } from 'react';
import { Row, Col, Card, Tabs, DatePicker } from 'antd'; import { Row, Col, Card, Tabs, DatePicker } from 'antd';
import { FormattedMessage, formatMessage } from 'umi/locale'; import { FormattedMessage, formatMessage } from 'umi/locale';
import numeral from 'numeral'; import numeral from 'numeral';
import { Bar } from 'ant-design-pro/lib/Charts';
import styles from './Analysis.less'; import styles from './Analysis.less';
import { Bar } from '@/components/Charts';
const { RangePicker } = DatePicker; const { RangePicker } = DatePicker;
const { TabPane } = Tabs; const { TabPane } = Tabs;
......
import React, { memo } from 'react'; import React, { memo } from 'react';
import { Row, Col, Table, Tooltip, Card, Icon } from 'antd'; import { Row, Col, Table, Tooltip, Card, Icon } from 'antd';
import { FormattedMessage } from 'umi/locale'; import { FormattedMessage } from 'umi/locale';
import Trend from '@/components/Trend'; import Trend from 'ant-design-pro/lib/Trend';
import numeral from 'numeral'; import numeral from 'numeral';
import NumberInfo from 'ant-design-pro/lib/NumberInfo';
import { MiniArea } from 'ant-design-pro/lib/Charts';
import styles from './Analysis.less'; import styles from './Analysis.less';
import NumberInfo from '@/components/NumberInfo';
import { MiniArea } from '@/components/Charts';
const columns = [ const columns = [
{ {
......
...@@ -4,7 +4,7 @@ import { connect } from 'dva'; ...@@ -4,7 +4,7 @@ import { connect } from 'dva';
import Link from 'umi/link'; import Link from 'umi/link';
import { Row, Col, Card, List, Avatar } from 'antd'; import { Row, Col, Card, List, Avatar } from 'antd';
import { Radar } from '@/components/Charts'; import { Radar } from 'ant-design-pro/lib/Charts';
import EditableLinkGroup from '@/components/EditableLinkGroup'; import EditableLinkGroup from '@/components/EditableLinkGroup';
import PageHeaderWrapper from '@/components/PageHeaderWrapper'; import PageHeaderWrapper from '@/components/PageHeaderWrapper';
......
import React from 'react'; import React from 'react';
import { formatMessage } from 'umi/locale'; import { formatMessage } from 'umi/locale';
import Link from 'umi/link'; import Link from 'umi/link';
import Exception from '@/components/Exception'; import Exception from 'ant-design-pro/lib/Exception';
const Exception403 = () => ( const Exception403 = () => (
<Exception <Exception
......
import React from 'react'; import React from 'react';
import { formatMessage } from 'umi/locale'; import { formatMessage } from 'umi/locale';
import Link from 'umi/link'; import Link from 'umi/link';
import Exception from '@/components/Exception'; import Exception from 'ant-design-pro/lib/Exception';
const Exception404 = () => ( const Exception404 = () => (
<Exception <Exception
......
import React from 'react'; import React from 'react';
import { formatMessage } from 'umi/locale'; import { formatMessage } from 'umi/locale';
import Link from 'umi/link'; import Link from 'umi/link';
import Exception from '@/components/Exception'; import Exception from 'ant-design-pro/lib/Exception';
const Exception500 = () => ( const Exception500 = () => (
<Exception <Exception
......
...@@ -13,7 +13,7 @@ import { ...@@ -13,7 +13,7 @@ import {
Popover, Popover,
} from 'antd'; } from 'antd';
import { connect } from 'dva'; import { connect } from 'dva';
import FooterToolbar from '@/components/FooterToolbar'; import FooterToolbar from 'ant-design-pro/lib/FooterToolbar';
import PageHeaderWrapper from '@/components/PageHeaderWrapper'; import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import TableForm from './TableForm'; import TableForm from './TableForm';
import styles from './style.less'; import styles from './style.less';
......
...@@ -2,7 +2,7 @@ import React, { Fragment } from 'react'; ...@@ -2,7 +2,7 @@ import React, { Fragment } from 'react';
import { connect } from 'dva'; import { connect } from 'dva';
import { Button, Row, Col } from 'antd'; import { Button, Row, Col } from 'antd';
import router from 'umi/router'; import router from 'umi/router';
import Result from '@/components/Result'; import Result from 'ant-design-pro/lib/Result';
import styles from './style.less'; import styles from './style.less';
@connect(({ form }) => ({ @connect(({ form }) => ({
......
...@@ -2,7 +2,7 @@ import React, { PureComponent } from 'react'; ...@@ -2,7 +2,7 @@ import React, { PureComponent } from 'react';
import numeral from 'numeral'; import numeral from 'numeral';
import { connect } from 'dva'; import { connect } from 'dva';
import { Row, Col, Form, Card, Select, Icon, Avatar, List, Tooltip, Dropdown, Menu } from 'antd'; import { Row, Col, Form, Card, Select, Icon, Avatar, List, Tooltip, Dropdown, Menu } from 'antd';
import TagSelect from '@/components/TagSelect'; import TagSelect from 'ant-design-pro/lib/TagSelect';
import StandardFormRow from '@/components/StandardFormRow'; import StandardFormRow from '@/components/StandardFormRow';
import { formatWan } from '@/utils/utils'; import { formatWan } from '@/utils/utils';
......
...@@ -2,7 +2,7 @@ import React, { Component, Fragment } from 'react'; ...@@ -2,7 +2,7 @@ import React, { Component, Fragment } from 'react';
import { connect } from 'dva'; import { connect } from 'dva';
import { Form, Card, Select, List, Tag, Icon, Row, Col, Button } from 'antd'; import { Form, Card, Select, List, Tag, Icon, Row, Col, Button } from 'antd';
import TagSelect from '@/components/TagSelect'; import TagSelect from 'ant-design-pro/lib/TagSelect';
import StandardFormRow from '@/components/StandardFormRow'; import StandardFormRow from '@/components/StandardFormRow';
import ArticleListContent from '@/components/ArticleListContent'; import ArticleListContent from '@/components/ArticleListContent';
import styles from './Articles.less'; import styles from './Articles.less';
......
...@@ -22,7 +22,7 @@ import { ...@@ -22,7 +22,7 @@ import {
} from 'antd'; } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper'; import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Result from '@/components/Result'; import Result from 'ant-design-pro/lib/Result';
import styles from './BasicList.less'; import styles from './BasicList.less';
......
...@@ -2,7 +2,7 @@ import React, { PureComponent } from 'react'; ...@@ -2,7 +2,7 @@ import React, { PureComponent } from 'react';
import { connect } from 'dva'; import { connect } from 'dva';
import { Card, Button, Icon, List } from 'antd'; import { Card, Button, Icon, List } from 'antd';
import Ellipsis from '@/components/Ellipsis'; import Ellipsis from 'ant-design-pro/lib/Ellipsis';
import PageHeaderWrapper from '@/components/PageHeaderWrapper'; import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from './CardList.less'; import styles from './CardList.less';
......
...@@ -3,9 +3,9 @@ import moment from 'moment'; ...@@ -3,9 +3,9 @@ import moment from 'moment';
import { connect } from 'dva'; import { connect } from 'dva';
import { Row, Col, Form, Card, Select, List } from 'antd'; import { Row, Col, Form, Card, Select, List } from 'antd';
import TagSelect from '@/components/TagSelect'; import TagSelect from 'ant-design-pro/lib/TagSelect';
import AvatarList from '@/components/AvatarList'; import AvatarList from 'ant-design-pro/lib/AvatarList';
import Ellipsis from '@/components/Ellipsis'; import Ellipsis from 'ant-design-pro/lib/Ellipsis';
import StandardFormRow from '@/components/StandardFormRow'; import StandardFormRow from '@/components/StandardFormRow';
import styles from './Projects.less'; import styles from './Projects.less';
......
...@@ -18,7 +18,7 @@ import { ...@@ -18,7 +18,7 @@ import {
Divider, Divider,
} from 'antd'; } from 'antd';
import classNames from 'classnames'; import classNames from 'classnames';
import DescriptionList from '@/components/DescriptionList'; import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper'; import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from './AdvancedProfile.less'; import styles from './AdvancedProfile.less';
......
import React, { Component } from 'react'; import React, { Component } from 'react';
import { connect } from 'dva'; import { connect } from 'dva';
import { Card, Badge, Table, Divider } from 'antd'; import { Card, Badge, Table, Divider } from 'antd';
import DescriptionList from '@/components/DescriptionList'; import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper'; import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from './BasicProfile.less'; import styles from './BasicProfile.less';
......
import React, { Fragment } from 'react'; import React, { Fragment } from 'react';
import { formatMessage, FormattedMessage } from 'umi/locale'; import { formatMessage, FormattedMessage } from 'umi/locale';
import { Button, Icon, Card } from 'antd'; import { Button, Icon, Card } from 'antd';
import Result from '@/components/Result'; import Result from 'ant-design-pro/lib/Result';
import PageHeaderWrapper from '@/components/PageHeaderWrapper'; import PageHeaderWrapper from '@/components/PageHeaderWrapper';
const extra = ( const extra = (
......
import React, { Fragment } from 'react'; import React, { Fragment } from 'react';
import { formatMessage, FormattedMessage } from 'umi/locale'; import { formatMessage, FormattedMessage } from 'umi/locale';
import { Button, Row, Col, Icon, Steps, Card } from 'antd'; import { Button, Row, Col, Icon, Steps, Card } from 'antd';
import Result from '@/components/Result'; import Result from 'ant-design-pro/lib/Result';
import PageHeaderWrapper from '@/components/PageHeaderWrapper'; import PageHeaderWrapper from '@/components/PageHeaderWrapper';
const { Step } = Steps; const { Step } = Steps;
......
...@@ -3,7 +3,7 @@ import { connect } from 'dva'; ...@@ -3,7 +3,7 @@ import { connect } from 'dva';
import { formatMessage, FormattedMessage } from 'umi/locale'; import { formatMessage, FormattedMessage } from 'umi/locale';
import Link from 'umi/link'; import Link from 'umi/link';
import { Checkbox, Alert, Icon } from 'antd'; import { Checkbox, Alert, Icon } from 'antd';
import Login from '@/components/Login'; import Login from 'ant-design-pro/lib/Login';
import styles from './Login.less'; import styles from './Login.less';
const { Tab, UserName, Password, Mobile, Captcha, Submit } = Login; const { Tab, UserName, Password, Mobile, Captcha, Submit } = Login;
......
...@@ -2,7 +2,7 @@ import React from 'react'; ...@@ -2,7 +2,7 @@ import React from 'react';
import { formatMessage, FormattedMessage } from 'umi/locale'; import { formatMessage, FormattedMessage } from 'umi/locale';
import { Button } from 'antd'; import { Button } from 'antd';
import Link from 'umi/link'; import Link from 'umi/link';
import Result from '@/components/Result'; import Result from 'ant-design-pro/lib/Result';
import styles from './RegisterResult.less'; import styles from './RegisterResult.less';
const actions = ( const actions = (
......
import RenderAuthorized from '@/components/Authorized'; import RenderAuthorized from 'ant-design-pro/lib/Authorized';
import { getAuthority } from './authority'; import { getAuthority } from './authority';
let Authorized = RenderAuthorized(getAuthority()); // eslint-disable-line let Authorized = RenderAuthorized(getAuthority()); // eslint-disable-line
......
import React from 'react'; import React from 'react';
import { yuan } from '@/components/Charts'; import { yuan } from 'ant-design-pro/lib/Charts';
/** /**
* 减少使用 dangerouslySetInnerHTML * 减少使用 dangerouslySetInnerHTML
*/ */
......
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