vendor: amis 6.13.0 base (fork root)
This commit is contained in:
50
packages/amis-ui/src/components/404.tsx
Normal file
50
packages/amis-ui/src/components/404.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* @file 404
|
||||
* @author fex
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import {themeable, ClassNamesFn} from 'amis-core';
|
||||
|
||||
interface NotFoundProps {
|
||||
code?: string | number;
|
||||
description?: string;
|
||||
links?: React.ReactNode;
|
||||
footerText?: React.ReactNode;
|
||||
classPrefix: string;
|
||||
classnames: ClassNamesFn;
|
||||
children?: React.ReactElement;
|
||||
}
|
||||
|
||||
export class NotFound extends React.Component<NotFoundProps, any> {
|
||||
render() {
|
||||
const {links, footerText, description, children, code} = this.props;
|
||||
|
||||
return (
|
||||
<div className="container w-xxl w-auto-xs m-auto">
|
||||
<div className="text-center m-b-lg">
|
||||
<h1 className="text-shadow text-white">{code || '404'}</h1>
|
||||
{description ? (
|
||||
<div className="text-danger">{description}</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{children}
|
||||
|
||||
{links ? (
|
||||
<div className="list-group bg-info auto m-b-sm m-b-lg">{links}</div>
|
||||
) : null}
|
||||
|
||||
{footerText ? (
|
||||
<div className="text-center">
|
||||
<p>
|
||||
<small className="text-muted">{footerText}</small>
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(NotFound);
|
||||
400
packages/amis-ui/src/components/Alert.tsx
Normal file
400
packages/amis-ui/src/components/Alert.tsx
Normal file
@@ -0,0 +1,400 @@
|
||||
/**
|
||||
* @file Alert
|
||||
* @author fex
|
||||
*/
|
||||
|
||||
import React, {version} from 'react';
|
||||
import {render} from 'react-dom';
|
||||
import Modal from './Modal';
|
||||
import Button from './Button';
|
||||
import {ClassNamesFn, themeable, ThemeProps} from 'amis-core';
|
||||
import {LocaleProps, localeable} from 'amis-core';
|
||||
import Html from './Html';
|
||||
import type {PlainObject} from 'amis-core';
|
||||
// import {createRoot} from 'react-dom/client';
|
||||
export interface AlertProps extends ThemeProps, LocaleProps {
|
||||
container?: any;
|
||||
confirmText?: string;
|
||||
cancelText?: string;
|
||||
title?: string;
|
||||
confirmBtnLevel?: string;
|
||||
alertBtnLevel?: string;
|
||||
isolate?: boolean;
|
||||
children?: React.ReactElement;
|
||||
closeOnEsc?: boolean;
|
||||
size?: '' | 'xs' | 'sm' | 'md' | 'lg' | 'xl' | 'full';
|
||||
cancelBtnLevel?: string;
|
||||
}
|
||||
|
||||
interface ConfirmOptions {
|
||||
className?: string;
|
||||
closeOnEsc?: AlertProps['closeOnEsc'];
|
||||
size?: AlertProps['size'];
|
||||
confirmBtnLevel?: AlertProps['confirmBtnLevel'];
|
||||
cancelBtnLevel?: AlertProps['cancelBtnLevel'];
|
||||
confirmText?: AlertProps['confirmText'];
|
||||
cancelText?: AlertProps['cancelText'];
|
||||
}
|
||||
|
||||
export interface AlertState {
|
||||
show: boolean;
|
||||
title?: string;
|
||||
content: string | React.ReactNode;
|
||||
confirm: boolean;
|
||||
prompt?: boolean;
|
||||
controls?: any;
|
||||
value?: any;
|
||||
confirmText?: string;
|
||||
cancelText?: string;
|
||||
closeOnEsc?: AlertProps['closeOnEsc'];
|
||||
size?: AlertProps['size'];
|
||||
confirmBtnLevel?: AlertProps['confirmBtnLevel'];
|
||||
cancelBtnLevel?: AlertProps['cancelBtnLevel'];
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export class Alert extends React.Component<AlertProps, AlertState> {
|
||||
static instance: any = null;
|
||||
static async getInstance() {
|
||||
if (!Alert.instance || Alert.instance.unmount) {
|
||||
console.warn('Alert 组件应该没有被渲染,所以隐性的渲染到 body 了');
|
||||
const container = document.body;
|
||||
const div = document.createElement('div');
|
||||
container.appendChild(div);
|
||||
|
||||
// if (parseInt(version.split('.')[0], 10) >= 18) {
|
||||
// const root = createRoot(div);
|
||||
// await new Promise<void>(resolve =>
|
||||
// root.render(<FinnalAlert ref={() => resolve()} />)
|
||||
// );
|
||||
// } else {
|
||||
render(<FinnalAlert />, div);
|
||||
// }
|
||||
}
|
||||
|
||||
return Alert.instance;
|
||||
}
|
||||
|
||||
_resolve: (value: any) => void;
|
||||
_modal: any;
|
||||
_body: any;
|
||||
state: AlertState = {
|
||||
show: false,
|
||||
title: '',
|
||||
content: '',
|
||||
confirm: false,
|
||||
size: '',
|
||||
confirmBtnLevel: 'danger',
|
||||
cancelBtnLevel: 'default',
|
||||
closeOnEsc: false,
|
||||
confirmText: '确认',
|
||||
cancelText: '取消'
|
||||
};
|
||||
originInstance: Alert | null;
|
||||
unmount = false;
|
||||
constructor(props: AlertProps) {
|
||||
super(props);
|
||||
|
||||
this.close = this.close.bind(this);
|
||||
this.handleConfirm = this.handleConfirm.bind(this);
|
||||
this.handleCancel = this.handleCancel.bind(this);
|
||||
this.modalRef = this.modalRef.bind(this);
|
||||
this.handleFormSubmit = this.handleFormSubmit.bind(this);
|
||||
this.scopeRef = this.scopeRef.bind(this);
|
||||
|
||||
if (!props.isolate) {
|
||||
this.originInstance = Alert.instance;
|
||||
Alert.instance = this;
|
||||
}
|
||||
}
|
||||
|
||||
static defaultProps = {
|
||||
confirmText: 'confirm',
|
||||
cancelText: 'cancel',
|
||||
title: 'Alert.info',
|
||||
alertBtnLevel: 'primary',
|
||||
confirmBtnLevel: 'danger',
|
||||
cancelBtnLevel: 'default'
|
||||
};
|
||||
|
||||
componentDidMount() {
|
||||
this._body && (this._body.innerHTML = this.state.content);
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps: AlertProps, prevState: AlertState) {
|
||||
if (prevState.content !== this.state.content) {
|
||||
this._body && (this._body.innerHTML = this.state.content);
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.unmount = true;
|
||||
if (Alert.instance === this) {
|
||||
Alert.instance = this.originInstance || null;
|
||||
this.originInstance = null;
|
||||
}
|
||||
}
|
||||
|
||||
schemaSope: any;
|
||||
scopeRef(schemaSope: any) {
|
||||
this.schemaSope = schemaSope;
|
||||
}
|
||||
|
||||
handleConfirm() {
|
||||
const form = this.schemaSope?.getComponentByName('form');
|
||||
|
||||
if (form) {
|
||||
form.doAction({type: 'submit'});
|
||||
} else {
|
||||
this.close(true);
|
||||
}
|
||||
}
|
||||
|
||||
handleCancel() {
|
||||
this.close(false);
|
||||
}
|
||||
|
||||
close(confirmed: boolean) {
|
||||
const isConfirm = this.state.confirm || this.state.prompt;
|
||||
|
||||
this.setState(
|
||||
{
|
||||
show: false,
|
||||
prompt: false,
|
||||
confirm: false
|
||||
},
|
||||
isConfirm ? () => this._resolve(confirmed) /*this._reject()*/ : undefined
|
||||
);
|
||||
}
|
||||
|
||||
alert(content: string, title?: string, className?: string) {
|
||||
this.setState({
|
||||
title,
|
||||
content,
|
||||
show: true,
|
||||
confirm: false,
|
||||
className
|
||||
});
|
||||
}
|
||||
|
||||
confirm(
|
||||
content: string | React.ReactNode,
|
||||
title?: string,
|
||||
optionsOrCofnrimText?: string | ConfirmOptions,
|
||||
cancelText?: string
|
||||
) {
|
||||
this.setState({
|
||||
title,
|
||||
content,
|
||||
show: true,
|
||||
confirm: true,
|
||||
confirmText:
|
||||
typeof optionsOrCofnrimText === 'string'
|
||||
? optionsOrCofnrimText
|
||||
: optionsOrCofnrimText?.confirmText,
|
||||
cancelText,
|
||||
size:
|
||||
typeof optionsOrCofnrimText === 'string'
|
||||
? ''
|
||||
: optionsOrCofnrimText?.size,
|
||||
closeOnEsc:
|
||||
typeof optionsOrCofnrimText === 'string'
|
||||
? false
|
||||
: optionsOrCofnrimText?.closeOnEsc,
|
||||
className:
|
||||
typeof optionsOrCofnrimText === 'string'
|
||||
? ''
|
||||
: optionsOrCofnrimText?.className,
|
||||
confirmBtnLevel:
|
||||
typeof optionsOrCofnrimText === 'string'
|
||||
? 'danger'
|
||||
: optionsOrCofnrimText?.confirmBtnLevel,
|
||||
cancelBtnLevel:
|
||||
typeof optionsOrCofnrimText === 'string'
|
||||
? 'default'
|
||||
: optionsOrCofnrimText?.cancelBtnLevel
|
||||
});
|
||||
|
||||
return new Promise(resolve => {
|
||||
this._resolve = resolve;
|
||||
});
|
||||
}
|
||||
|
||||
prompt(
|
||||
controls: any,
|
||||
defaultValue?: any,
|
||||
title: string = 'placeholder.enter',
|
||||
confirmText: string = 'confirm'
|
||||
) {
|
||||
if (typeof controls === 'string') {
|
||||
// 兼容浏览器标准用法。
|
||||
controls = [
|
||||
{
|
||||
name: 'text',
|
||||
label: controls,
|
||||
type: 'text'
|
||||
}
|
||||
];
|
||||
|
||||
if (typeof defaultValue === 'string') {
|
||||
defaultValue = {
|
||||
text: defaultValue
|
||||
};
|
||||
}
|
||||
} else if (!Array.isArray(controls)) {
|
||||
controls = [controls];
|
||||
}
|
||||
|
||||
this.setState({
|
||||
title,
|
||||
controls,
|
||||
show: true,
|
||||
prompt: true,
|
||||
value: defaultValue,
|
||||
confirmText
|
||||
});
|
||||
|
||||
return new Promise(resolve => {
|
||||
this._resolve = resolve;
|
||||
});
|
||||
}
|
||||
|
||||
modalRef(ref: any) {
|
||||
this._modal = ref;
|
||||
}
|
||||
|
||||
handleFormSubmit(values: any) {
|
||||
this.close(values);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
container,
|
||||
cancelText,
|
||||
confirmText,
|
||||
title,
|
||||
confirmBtnLevel,
|
||||
alertBtnLevel,
|
||||
cancelBtnLevel,
|
||||
classnames: cx
|
||||
} = this.props;
|
||||
let theme = this.props.theme || 'cxd';
|
||||
if (theme === 'default') {
|
||||
theme = 'cxd';
|
||||
}
|
||||
const __ = this.props.translate;
|
||||
const finalTitle = __(this.state.title ?? title);
|
||||
const finalConfirmText = __(this.state.confirmText ?? confirmText);
|
||||
const finalCancelText = __(this.state.cancelText ?? cancelText);
|
||||
const finalConfirmBtnLevel = this.state.confirmBtnLevel ?? confirmBtnLevel;
|
||||
const finalCancelBtnLevel = this.state.cancelBtnLevel ?? cancelBtnLevel;
|
||||
|
||||
return (
|
||||
<Modal
|
||||
show={this.state.show}
|
||||
onHide={this.handleCancel}
|
||||
container={container}
|
||||
ref={this.modalRef}
|
||||
closeOnEsc={this.state.closeOnEsc}
|
||||
size={this.state.size}
|
||||
className={cx(this.state.className)}
|
||||
>
|
||||
{finalTitle ? (
|
||||
<div className={cx('Modal-header')}>
|
||||
<div className={cx('Modal-title')}>{finalTitle}</div>
|
||||
</div>
|
||||
) : null}
|
||||
<div className={cx('Modal-body')}>
|
||||
{this.state.prompt ? (
|
||||
renderForm(
|
||||
this.state.controls,
|
||||
this.state.value,
|
||||
this.handleFormSubmit,
|
||||
this.scopeRef,
|
||||
theme
|
||||
)
|
||||
) : typeof this.state.content === 'string' ? (
|
||||
<Html html={this.state.content} />
|
||||
) : (
|
||||
<>{this.state.content}</>
|
||||
)}
|
||||
</div>
|
||||
{finalConfirmText ? (
|
||||
<div className={cx('Modal-footer')}>
|
||||
{this.state.confirm || this.state.prompt ? (
|
||||
<Button level={finalCancelBtnLevel} onClick={this.handleCancel}>
|
||||
{__(finalCancelText)}
|
||||
</Button>
|
||||
) : null}
|
||||
<Button
|
||||
level={
|
||||
this.state.confirm || this.state.prompt
|
||||
? finalConfirmBtnLevel
|
||||
: alertBtnLevel
|
||||
}
|
||||
onClick={this.handleConfirm}
|
||||
>
|
||||
{finalConfirmText}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export type renderSchemaFn = (
|
||||
controls: Array<any>,
|
||||
value: PlainObject,
|
||||
callback?: (values: PlainObject) => void,
|
||||
scopeRef?: (value: any) => void,
|
||||
theme?: string
|
||||
) => JSX.Element;
|
||||
let renderSchemaFn: renderSchemaFn;
|
||||
export function setRenderSchemaFn(fn: renderSchemaFn) {
|
||||
renderSchemaFn = fn;
|
||||
}
|
||||
|
||||
function renderForm(
|
||||
controls: Array<any>,
|
||||
value: PlainObject = {},
|
||||
callback?: (values: PlainObject) => void,
|
||||
scopeRef?: (value: any) => void,
|
||||
theme?: string
|
||||
) {
|
||||
return renderSchemaFn?.(controls, value, callback, scopeRef, theme);
|
||||
}
|
||||
|
||||
export const alert: (
|
||||
content: string,
|
||||
title?: string,
|
||||
className?: string
|
||||
) => Promise<void> = async (content, title, className) => {
|
||||
const instance = await Alert.getInstance();
|
||||
return instance.alert(content, title, className);
|
||||
};
|
||||
export const confirm: (
|
||||
content: string | React.ReactNode,
|
||||
title?: string,
|
||||
optionsOrCofnrimText?: string | ConfirmOptions,
|
||||
cancelText?: string
|
||||
) => Promise<any> = async (
|
||||
content,
|
||||
title,
|
||||
optionsOrCofnrimText,
|
||||
cancelText
|
||||
) => {
|
||||
const instance = await Alert.getInstance();
|
||||
return instance.confirm(content, title, optionsOrCofnrimText, cancelText);
|
||||
};
|
||||
export const prompt: (
|
||||
controls: any,
|
||||
defaultvalue?: any,
|
||||
title?: string,
|
||||
confirmText?: string
|
||||
) => Promise<any> = async (controls, defaultvalue, title, confirmText) => {
|
||||
const instance = await Alert.getInstance();
|
||||
return instance.prompt(controls, defaultvalue, title, confirmText);
|
||||
};
|
||||
export const FinnalAlert = themeable(localeable(Alert));
|
||||
export default FinnalAlert;
|
||||
118
packages/amis-ui/src/components/Alert2.tsx
Normal file
118
packages/amis-ui/src/components/Alert2.tsx
Normal file
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* @file Alert2
|
||||
* @author fex
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import {ClassNamesFn, themeable} from 'amis-core';
|
||||
import {Icon, getIcon} from './icons';
|
||||
|
||||
export interface AlertProps {
|
||||
level: 'danger' | 'info' | 'success' | 'warning';
|
||||
title?: string;
|
||||
className?: string;
|
||||
style?: any;
|
||||
showCloseButton: boolean;
|
||||
showIcon?: boolean;
|
||||
icon?: string | React.ReactNode;
|
||||
iconClassName?: string;
|
||||
closeButtonClassName?: string;
|
||||
onClose?: () => void;
|
||||
classnames: ClassNamesFn;
|
||||
classPrefix: string;
|
||||
children?: React.ReactNode | Array<React.ReactNode>;
|
||||
actions?: React.ReactNode | React.ReactNode[];
|
||||
}
|
||||
|
||||
export interface AlertState {
|
||||
show: boolean;
|
||||
}
|
||||
|
||||
export class Alert extends React.Component<AlertProps, AlertState> {
|
||||
static defaultProps: Pick<
|
||||
AlertProps,
|
||||
'level' | 'className' | 'showCloseButton'
|
||||
> = {
|
||||
level: 'info',
|
||||
className: '',
|
||||
showCloseButton: false
|
||||
};
|
||||
static propsList: Array<string> = [
|
||||
'level',
|
||||
'className',
|
||||
'showCloseButton',
|
||||
'onClose'
|
||||
];
|
||||
|
||||
constructor(props: AlertProps) {
|
||||
super(props);
|
||||
|
||||
this.handleClick = this.handleClick.bind(this);
|
||||
this.state = {
|
||||
show: true
|
||||
};
|
||||
}
|
||||
|
||||
handleClick() {
|
||||
this.setState(
|
||||
{
|
||||
show: false
|
||||
},
|
||||
this.props.onClose
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
classnames: cx,
|
||||
className,
|
||||
style,
|
||||
level,
|
||||
children,
|
||||
actions,
|
||||
showCloseButton,
|
||||
title,
|
||||
icon,
|
||||
showIcon,
|
||||
iconClassName,
|
||||
closeButtonClassName
|
||||
} = this.props;
|
||||
|
||||
// 优先使用内置svg,其次使用icon库
|
||||
const iconNode = showIcon ? (
|
||||
<Icon cx={cx} icon={icon || `alert-${level}`} className="icon" />
|
||||
) : null;
|
||||
|
||||
return this.state.show ? (
|
||||
<div
|
||||
className={cx(
|
||||
'Alert',
|
||||
level ? `Alert--${level}` : '',
|
||||
title ? 'Alert-has-title' : '',
|
||||
className
|
||||
)}
|
||||
style={style}
|
||||
>
|
||||
{showIcon && iconNode ? (
|
||||
<div className={cx('Alert-icon', iconClassName)}>{iconNode}</div>
|
||||
) : null}
|
||||
<div className={cx('Alert-content')}>
|
||||
{title ? <div className={cx('Alert-title')}>{title}</div> : null}
|
||||
<div className={cx('Alert-desc')}>{children}</div>
|
||||
</div>
|
||||
{actions ? <div className={cx('Alert-actions')}>{actions}</div> : null}
|
||||
{showCloseButton ? (
|
||||
<button
|
||||
className={cx('Alert-close', closeButtonClassName)}
|
||||
onClick={this.handleClick}
|
||||
type="button"
|
||||
>
|
||||
<Icon icon="close" className="icon" />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
) : null;
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(Alert);
|
||||
79
packages/amis-ui/src/components/AlphabetIndexer.tsx
Normal file
79
packages/amis-ui/src/components/AlphabetIndexer.tsx
Normal file
@@ -0,0 +1,79 @@
|
||||
import React, {useRef, useEffect} from 'react';
|
||||
import {ClassNamesFn} from 'amis-core';
|
||||
|
||||
interface AlphabetIndexerProps {
|
||||
items: Array<any>;
|
||||
getItemLetter: (item: any) => string;
|
||||
onLetterClick: (letter: string) => void;
|
||||
classnames: ClassNamesFn;
|
||||
currentLetter?: string;
|
||||
}
|
||||
|
||||
const AlphabetIndexer: React.FC<AlphabetIndexerProps> = ({
|
||||
items,
|
||||
getItemLetter,
|
||||
onLetterClick,
|
||||
classnames: cx,
|
||||
currentLetter
|
||||
}) => {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const letters = React.useMemo(() => {
|
||||
return Array.from(
|
||||
new Set(
|
||||
items
|
||||
.map(item => {
|
||||
const value = getItemLetter(item);
|
||||
return typeof value === 'string'
|
||||
? value.charAt(0).toUpperCase()
|
||||
: '';
|
||||
})
|
||||
.filter(Boolean)
|
||||
.sort()
|
||||
)
|
||||
);
|
||||
}, [items, getItemLetter]);
|
||||
|
||||
const handleTouchMove = (e: TouchEvent) => {
|
||||
e.preventDefault();
|
||||
const touch = e.touches[0];
|
||||
const target = document.elementFromPoint(touch.clientX, touch.clientY);
|
||||
const letter = target?.getAttribute('data-letter');
|
||||
if (letter) {
|
||||
onLetterClick(letter);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const container = containerRef.current;
|
||||
if (container) {
|
||||
container.addEventListener('touchmove', handleTouchMove, {
|
||||
passive: false
|
||||
});
|
||||
|
||||
return () => {
|
||||
container.removeEventListener('touchmove', handleTouchMove);
|
||||
};
|
||||
}
|
||||
return () => {};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className={cx('AlphabetIndexer')}>
|
||||
{letters.map(letter => (
|
||||
<div
|
||||
key={letter}
|
||||
className={cx('AlphabetIndexer-letter', {
|
||||
'is-active': letter === currentLetter
|
||||
})}
|
||||
data-letter={letter}
|
||||
onClick={() => onLetterClick(letter)}
|
||||
>
|
||||
{letter}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AlphabetIndexer;
|
||||
243
packages/amis-ui/src/components/AnchorNav.tsx
Normal file
243
packages/amis-ui/src/components/AnchorNav.tsx
Normal file
@@ -0,0 +1,243 @@
|
||||
/**
|
||||
* @file AnchorNav
|
||||
* @description 锚点导航
|
||||
* @author hsm-lv
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import {ThemeProps, themeable} from 'amis-core';
|
||||
|
||||
import {autobind} from 'amis-core';
|
||||
import {uncontrollable} from 'amis-core';
|
||||
import find from 'lodash/find';
|
||||
import type {Schema} from 'amis-core';
|
||||
|
||||
export interface AnchorNavSectionProps extends ThemeProps {
|
||||
title?: string; // 标题
|
||||
name: string | number; // 标识
|
||||
body?: Schema; // Schema
|
||||
className?: string; // 样式名
|
||||
style?: any;
|
||||
children?: React.ReactNode | Array<React.ReactNode>;
|
||||
}
|
||||
|
||||
class AnchorNavSectionComponent extends React.PureComponent<AnchorNavSectionProps> {
|
||||
contentDom: any;
|
||||
contentRef = (ref: any) => (this.contentDom = ref);
|
||||
|
||||
render() {
|
||||
const {classnames: cx, children, className, name} = this.props;
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={this.contentRef}
|
||||
className={cx('AnchorNav-section', className)}
|
||||
data-id={name + ''}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const AnchorNavSection = themeable(AnchorNavSectionComponent);
|
||||
|
||||
export interface AnchorNavProps extends ThemeProps {
|
||||
links?: Array<AnchorNavSectionProps>; // 锚点数据
|
||||
active?: string | number; // 激活标识
|
||||
linkClassName?: string; // 导航 CSS类名
|
||||
sectionClassName?: string; // 区域 CSS类名
|
||||
sectionRender?: (
|
||||
section: AnchorNavSectionProps,
|
||||
props?: AnchorNavProps
|
||||
) => JSX.Element; // 锚点区域渲染器
|
||||
onSelect?: (key: string | number) => void; // 选中回调方法
|
||||
direction?: 'vertical' | 'horizontal'; // 导航方向
|
||||
children?: React.ReactNode | Array<React.ReactNode>;
|
||||
}
|
||||
|
||||
export class AnchorNav extends React.Component<AnchorNavProps> {
|
||||
static defaultProps: Pick<
|
||||
AnchorNavProps,
|
||||
'linkClassName' | 'sectionClassName' | 'direction'
|
||||
> = {
|
||||
linkClassName: '',
|
||||
sectionClassName: '',
|
||||
direction: 'vertical'
|
||||
};
|
||||
|
||||
// 滚动区域DOM
|
||||
contentDom: React.RefObject<HTMLDivElement> = React.createRef();
|
||||
|
||||
// 后代节点观察器
|
||||
observer: IntersectionObserver;
|
||||
|
||||
sections: {
|
||||
key: string | number;
|
||||
element: HTMLDivElement;
|
||||
isIntersecting?: boolean;
|
||||
}[] = [];
|
||||
|
||||
fromSelect: boolean = false;
|
||||
fromSelectTimer: any;
|
||||
|
||||
componentDidMount() {
|
||||
this.observer = new IntersectionObserver(this.scrollToNav);
|
||||
this.sections.forEach(item => {
|
||||
this.observer.observe(item.element);
|
||||
});
|
||||
if (this.props.active) {
|
||||
this.scrollToSection(this.props.active);
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.observer.disconnect();
|
||||
}
|
||||
|
||||
@autobind
|
||||
scrollToNav(entries: IntersectionObserverEntry[]) {
|
||||
entries.forEach(entry => {
|
||||
const key = entry.target.getAttribute('data-id');
|
||||
const currentSection = this.sections.find(item => item.key === key);
|
||||
if (currentSection) {
|
||||
currentSection.isIntersecting = entry.isIntersecting;
|
||||
}
|
||||
});
|
||||
// 找到第一个可见的区域
|
||||
const firstIntersectingSection = this.sections.find(
|
||||
item => item.isIntersecting
|
||||
);
|
||||
if (!this.fromSelect) {
|
||||
firstIntersectingSection && this.fireSelect(firstIntersectingSection.key);
|
||||
} else {
|
||||
// 滚动结束后,重置fromSelect状态
|
||||
if (this.fromSelectTimer) {
|
||||
clearTimeout(this.fromSelectTimer);
|
||||
}
|
||||
this.fromSelectTimer = setTimeout(() => {
|
||||
this.fromSelect = false;
|
||||
}, 300);
|
||||
}
|
||||
}
|
||||
|
||||
scrollToSection(key: string | number) {
|
||||
this.fromSelect = true;
|
||||
const node = find(this.sections, item => item.key === key)?.element;
|
||||
node?.scrollIntoView?.({behavior: 'smooth'});
|
||||
}
|
||||
|
||||
handleSelect(key: string | number) {
|
||||
this.scrollToSection(key);
|
||||
this.fireSelect(key);
|
||||
}
|
||||
|
||||
fireSelect(key: string | number) {
|
||||
const {onSelect} = this.props;
|
||||
onSelect && onSelect(key);
|
||||
}
|
||||
|
||||
renderLink(link: any, index: number) {
|
||||
if (!link) {
|
||||
return;
|
||||
}
|
||||
|
||||
const {classnames: cx, active: activeProp} = this.props;
|
||||
const {title, name} = link.props;
|
||||
const active = activeProp === undefined && index === 0 ? name : activeProp;
|
||||
// 判断是否为子节点,子节点key为 <父节点索引>-<子节点索引>
|
||||
const isChild = link.key?.split('-').length >= 2;
|
||||
|
||||
return (
|
||||
<li
|
||||
className={cx(
|
||||
'AnchorNav-link',
|
||||
isChild ? 'AnchorNav-link-child' : '',
|
||||
String(active) === String(name) ? 'is-active' : ''
|
||||
)}
|
||||
key={link.key}
|
||||
onClick={() => this.handleSelect(name)}
|
||||
>
|
||||
<a title={title}>{title}</a>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
renderSection(section: any, index: number) {
|
||||
if (!section) {
|
||||
return;
|
||||
}
|
||||
|
||||
const {active: activeProp, classnames} = this.props;
|
||||
const name = section.props.name;
|
||||
const key = section.key;
|
||||
const active = activeProp === undefined && index === 0 ? name : activeProp;
|
||||
return React.cloneElement(section, {
|
||||
...section.props,
|
||||
key,
|
||||
classnames,
|
||||
active,
|
||||
ref: (props: any) => {
|
||||
if (props && !this.sections.find(item => item.key === name)) {
|
||||
// 收集每个段落的真实dom节点
|
||||
this.sections.push({key: name, element: props.ref.contentDom});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
classnames: cx,
|
||||
className,
|
||||
style,
|
||||
linkClassName,
|
||||
sectionClassName,
|
||||
children,
|
||||
direction
|
||||
} = this.props;
|
||||
|
||||
if (!Array.isArray(children)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx(
|
||||
'AnchorNav',
|
||||
{
|
||||
[`AnchorNav--${direction}`]: direction
|
||||
},
|
||||
className
|
||||
)}
|
||||
style={style}
|
||||
>
|
||||
<ul
|
||||
className={cx('AnchorNav-link-wrap', linkClassName)}
|
||||
role="anchorlist"
|
||||
>
|
||||
{children.map((link, index) => this.renderLink(link, index))}
|
||||
</ul>
|
||||
|
||||
<div
|
||||
className={cx('AnchorNav-section-wrap', sectionClassName)}
|
||||
ref={this.contentDom}
|
||||
>
|
||||
{children.map((section, index) => {
|
||||
return this.renderSection(section, index);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const ThemedAnchorNav = themeable(
|
||||
uncontrollable(AnchorNav, {
|
||||
active: 'onSelect'
|
||||
})
|
||||
);
|
||||
|
||||
export default ThemedAnchorNav as typeof ThemedAnchorNav & {
|
||||
AnchorNavSection: typeof AnchorNavSection;
|
||||
};
|
||||
3
packages/amis-ui/src/components/AnchorNavSection.tsx
Normal file
3
packages/amis-ui/src/components/AnchorNavSection.tsx
Normal file
@@ -0,0 +1,3 @@
|
||||
import {AnchorNavSection} from './AnchorNav';
|
||||
|
||||
export default AnchorNavSection;
|
||||
234
packages/amis-ui/src/components/ArrayInput.tsx
Normal file
234
packages/amis-ui/src/components/ArrayInput.tsx
Normal file
@@ -0,0 +1,234 @@
|
||||
import React from 'react';
|
||||
import {ThemeProps, themeable} from 'amis-core';
|
||||
import {LocaleProps, localeable} from 'amis-core';
|
||||
import InputBox from './InputBox';
|
||||
import {Icon} from './icons';
|
||||
import Button from './Button';
|
||||
import {autobind, guid} from 'amis-core';
|
||||
import {uncontrollable} from 'amis-core';
|
||||
import Sortable from 'sortablejs';
|
||||
import {findDOMNode} from 'react-dom';
|
||||
|
||||
export interface ArrayInputProps extends ThemeProps, LocaleProps {
|
||||
value?: Array<any>;
|
||||
onChange?: (value: Array<any>) => void;
|
||||
placeholder: string;
|
||||
itemRender: (props: {
|
||||
value: any;
|
||||
onChange: (value: any) => void;
|
||||
index: number;
|
||||
disabled?: boolean;
|
||||
}) => JSX.Element;
|
||||
itemInitalValue?: any;
|
||||
maxLength?: number;
|
||||
minLength?: number;
|
||||
disabled?: boolean;
|
||||
sortable?: boolean;
|
||||
removable?: boolean;
|
||||
addable?: boolean;
|
||||
editable?: boolean;
|
||||
sortTip?: string;
|
||||
}
|
||||
|
||||
export class ArrayInput extends React.Component<ArrayInputProps> {
|
||||
static defaultProps = {
|
||||
placeholder: 'empty',
|
||||
itemRender: ({
|
||||
value,
|
||||
onChange
|
||||
}: {
|
||||
value: any;
|
||||
onChange: (value: any) => void;
|
||||
index: number;
|
||||
disabled?: boolean;
|
||||
}) => <InputBox value={value} onChange={onChange} />
|
||||
};
|
||||
|
||||
id: string = guid();
|
||||
dragTip?: HTMLElement;
|
||||
sortable?: Sortable;
|
||||
|
||||
handleItemOnChange(index: number, itemValue: any) {
|
||||
const {onChange} = this.props;
|
||||
const value = this.props.value;
|
||||
const newValue = Array.isArray(value) ? value.concat() : [];
|
||||
newValue.splice(index, 1, itemValue);
|
||||
onChange?.(newValue);
|
||||
}
|
||||
|
||||
@autobind
|
||||
dragTipRef(ref: any) {
|
||||
if (!this.dragTip && ref) {
|
||||
this.initDragging();
|
||||
} else if (this.dragTip && !ref) {
|
||||
this.destroyDragging();
|
||||
}
|
||||
|
||||
this.dragTip = ref;
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleAdd() {
|
||||
const {value, onChange, itemInitalValue} = this.props;
|
||||
const newValue = Array.isArray(value) ? value.concat() : [];
|
||||
|
||||
newValue.push(itemInitalValue);
|
||||
|
||||
onChange?.(newValue);
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleRemove(e: React.MouseEvent<HTMLElement>) {
|
||||
const indx = parseInt(e.currentTarget.getAttribute('data-index')!, 10);
|
||||
const {value, onChange, itemInitalValue} = this.props;
|
||||
const newValue = Array.isArray(value) ? value.concat() : [];
|
||||
newValue.splice(indx, 1);
|
||||
onChange?.(newValue);
|
||||
}
|
||||
|
||||
initDragging() {
|
||||
const onChange = this.props.onChange;
|
||||
const ns = this.props.classPrefix;
|
||||
const dom = findDOMNode(this) as HTMLElement;
|
||||
this.sortable = new Sortable(
|
||||
dom.querySelector(`.drag-group`) as HTMLElement,
|
||||
{
|
||||
group: `array-input-${this.id}`,
|
||||
animation: 150,
|
||||
handle: `.drag-bar`,
|
||||
ghostClass: `${ns}ArrayInput-item--dragging`,
|
||||
onEnd: (e: any) => {
|
||||
// 没有移动
|
||||
if (e.newIndex === e.oldIndex) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 换回来
|
||||
const parent = e.to as HTMLElement;
|
||||
if (e.oldIndex < parent.childNodes.length - 1) {
|
||||
parent.insertBefore(
|
||||
e.item,
|
||||
parent.childNodes[
|
||||
e.oldIndex > e.newIndex ? e.oldIndex + 1 : e.oldIndex
|
||||
]
|
||||
);
|
||||
} else {
|
||||
parent.appendChild(e.item);
|
||||
}
|
||||
|
||||
const value = this.props.value;
|
||||
if (!Array.isArray(value)) {
|
||||
return;
|
||||
}
|
||||
const newValue = value.concat();
|
||||
newValue.splice(e.newIndex, 0, newValue.splice(e.oldIndex, 1)[0]);
|
||||
onChange?.(newValue);
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
destroyDragging() {
|
||||
this.sortable && this.sortable.destroy();
|
||||
}
|
||||
|
||||
renderItem(value: any, index: number, collection: Array<any>) {
|
||||
const {
|
||||
itemRender,
|
||||
disabled,
|
||||
classnames: cx,
|
||||
sortable,
|
||||
removable,
|
||||
minLength
|
||||
} = this.props;
|
||||
|
||||
return (
|
||||
<div className={cx('ArrayInput-item')} key={index}>
|
||||
{sortable && collection.length > 1 && !disabled ? (
|
||||
<a className={cx('ArrayInput-itemDrager drag-bar')}>
|
||||
<Icon icon="drag-bar" className="icon" />
|
||||
</a>
|
||||
) : null}
|
||||
|
||||
{itemRender({
|
||||
value,
|
||||
onChange: this.handleItemOnChange.bind(this, index),
|
||||
index,
|
||||
disabled
|
||||
})}
|
||||
|
||||
{removable !== false &&
|
||||
!disabled &&
|
||||
(!minLength || collection.length > minLength) ? (
|
||||
<a
|
||||
data-index={index}
|
||||
className={cx('ArrayInput-itemRemove')}
|
||||
onClick={this.handleRemove}
|
||||
>
|
||||
<Icon icon="close" className="icon" />
|
||||
</a>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
classnames: cx,
|
||||
value,
|
||||
placeholder,
|
||||
translate: __,
|
||||
maxLength,
|
||||
sortable,
|
||||
sortTip,
|
||||
disabled
|
||||
} = this.props;
|
||||
|
||||
return (
|
||||
<div className={cx('ArrayInput')}>
|
||||
{Array.isArray(value) && value.length ? (
|
||||
<div className={cx('ArrayInput-items drag-group')}>
|
||||
{value.map((item, index) => this.renderItem(item, index, value))}
|
||||
</div>
|
||||
) : (
|
||||
<div className={cx('ArrayInput-placeholder')}>{__(placeholder)}</div>
|
||||
)}
|
||||
|
||||
<div
|
||||
className={cx(
|
||||
'ArrayInput-toolbar',
|
||||
sortable && Array.isArray(value) && value.length > 1
|
||||
? 'ArrayInput-toolbar--dnd'
|
||||
: ''
|
||||
)}
|
||||
>
|
||||
{!Array.isArray(value) || !maxLength || value.length < maxLength ? (
|
||||
<Button
|
||||
className={cx('ArrayInput-addBtn')}
|
||||
onClick={this.handleAdd}
|
||||
level=""
|
||||
disabled={disabled}
|
||||
>
|
||||
<Icon icon="plus" className="icon" />
|
||||
<span>{__('add')}</span>
|
||||
</Button>
|
||||
) : null}
|
||||
|
||||
{sortable && Array.isArray(value) && value.length ? (
|
||||
<span className={cx(`ArrayInput-sortTip`)} ref={this.dragTipRef}>
|
||||
{Array.isArray(value) && value.length > 1 ? __(sortTip) : ''}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(
|
||||
localeable(
|
||||
uncontrollable(ArrayInput, {
|
||||
value: 'onChange'
|
||||
})
|
||||
)
|
||||
);
|
||||
283
packages/amis-ui/src/components/AsideNav.tsx
Normal file
283
packages/amis-ui/src/components/AsideNav.tsx
Normal file
@@ -0,0 +1,283 @@
|
||||
/**
|
||||
* @file AsideNav
|
||||
* @description 左侧导航。
|
||||
* @author fex
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import {TestIdBuilder, mapTree} from 'amis-core';
|
||||
import {ClassNamesFn, themeable} from 'amis-core';
|
||||
|
||||
export type LinkItem = LinkItemProps;
|
||||
interface LinkItemProps {
|
||||
id?: number;
|
||||
label: string;
|
||||
hidden?: boolean;
|
||||
open?: boolean;
|
||||
active?: boolean;
|
||||
className?: string;
|
||||
children?: Array<LinkItem>;
|
||||
path?: string;
|
||||
icon?: string;
|
||||
component?: React.ElementType;
|
||||
testIdBuilder?: TestIdBuilder;
|
||||
}
|
||||
|
||||
export interface Navigation {
|
||||
label: string;
|
||||
children?: Array<LinkItem>;
|
||||
prefix?: JSX.Element;
|
||||
affix?: JSX.Element;
|
||||
className?: string;
|
||||
[propName: string]: any;
|
||||
}
|
||||
|
||||
export interface AsideNavProps {
|
||||
id?: string;
|
||||
className?: string;
|
||||
classPrefix: string;
|
||||
classnames: ClassNamesFn;
|
||||
renderLink: Function;
|
||||
isActive: Function;
|
||||
isOpen: (link: LinkItemProps) => boolean;
|
||||
navigations: Array<Navigation>;
|
||||
renderSubLinks: (
|
||||
link: LinkItemProps,
|
||||
renderLink: Function,
|
||||
depth: number,
|
||||
props: AsideNavProps
|
||||
) => React.ReactNode;
|
||||
}
|
||||
|
||||
interface AsideNavState {
|
||||
navigations: Array<Navigation>;
|
||||
}
|
||||
|
||||
export class AsideNav extends React.Component<AsideNavProps, AsideNavState> {
|
||||
static defaultProps = {
|
||||
renderLink: (item: LinkItemProps) => (
|
||||
<a {...item.testIdBuilder?.getTestId()}>{item.label}</a>
|
||||
),
|
||||
renderSubLinks: (
|
||||
link: LinkItemProps,
|
||||
renderLink: Function,
|
||||
depth: number,
|
||||
{classnames: cx}: AsideNavProps
|
||||
) =>
|
||||
link.children && link.children.length ? (
|
||||
<ul className={cx('AsideNav-subList')}>
|
||||
{link.label ? (
|
||||
<li key="subHeader" className={cx('AsideNav-subHeader')}>
|
||||
{renderLink(
|
||||
{
|
||||
...link,
|
||||
children: undefined
|
||||
},
|
||||
'subHeader',
|
||||
{},
|
||||
depth
|
||||
)}
|
||||
</li>
|
||||
) : null}
|
||||
{link.children.map((link, key) =>
|
||||
renderLink(link, key, {}, depth + 1)
|
||||
)}
|
||||
</ul>
|
||||
) : link.label && depth === 1 ? (
|
||||
<div className={cx('AsideNav-tooltip')}>{link.label}</div>
|
||||
) : null,
|
||||
isActive: (link: LinkItem) => link.open,
|
||||
isOpen: (item: LinkItemProps) =>
|
||||
item.children ? item.children.some(item => item.open) : false
|
||||
};
|
||||
|
||||
constructor(props: AsideNavProps) {
|
||||
super(props);
|
||||
|
||||
const isOpen = props.isOpen;
|
||||
let id = 1;
|
||||
this.state = {
|
||||
navigations: mapTree(
|
||||
props.navigations,
|
||||
(item: Navigation) => {
|
||||
const isActive =
|
||||
typeof item.active === 'undefined'
|
||||
? (props.isActive as Function)(item)
|
||||
: item.active;
|
||||
|
||||
return {
|
||||
...item,
|
||||
id: id++,
|
||||
active: isActive,
|
||||
open: isActive || isOpen(item as LinkItemProps)
|
||||
};
|
||||
},
|
||||
1,
|
||||
true
|
||||
)
|
||||
};
|
||||
|
||||
this.renderLink = this.renderLink.bind(this);
|
||||
this.toggleExpand = this.toggleExpand.bind(this);
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps: AsideNavProps) {
|
||||
const props = this.props;
|
||||
const isOpen = prevProps.isOpen;
|
||||
|
||||
if (
|
||||
prevProps.navigations !== props.navigations ||
|
||||
prevProps.isActive !== props.isActive
|
||||
) {
|
||||
let id = 1;
|
||||
this.setState({
|
||||
navigations: mapTree(
|
||||
props.navigations,
|
||||
(item: Navigation) => {
|
||||
const isActive =
|
||||
typeof item.active === 'undefined'
|
||||
? (props.isActive as Function)(item)
|
||||
: item.active;
|
||||
|
||||
return {
|
||||
...item,
|
||||
id: id++,
|
||||
active: isActive,
|
||||
open: isActive || isOpen(item as LinkItemProps)
|
||||
};
|
||||
},
|
||||
1,
|
||||
true
|
||||
)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
toggleExpand(link: LinkItemProps, e?: React.MouseEvent<HTMLElement>) {
|
||||
if (e) {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
}
|
||||
|
||||
this.setState({
|
||||
navigations: mapTree(
|
||||
this.state.navigations,
|
||||
(item: Navigation) => ({
|
||||
...item,
|
||||
open: link.id === item.id ? !item.open : item.open
|
||||
}),
|
||||
1,
|
||||
true
|
||||
)
|
||||
});
|
||||
}
|
||||
|
||||
renderLink(
|
||||
link: LinkItemProps,
|
||||
key: any,
|
||||
props: Partial<AsideNavProps> = {},
|
||||
depth = 1
|
||||
): React.ReactNode {
|
||||
const {
|
||||
renderLink,
|
||||
isActive,
|
||||
renderSubLinks,
|
||||
classnames: cx,
|
||||
...others
|
||||
} = this.props;
|
||||
|
||||
const dom = (renderLink as Function)({
|
||||
link,
|
||||
active: link.active,
|
||||
open: link.open,
|
||||
toggleExpand: this.toggleExpand,
|
||||
depth,
|
||||
classnames: cx,
|
||||
subHeader: key === 'subHeader',
|
||||
...others
|
||||
});
|
||||
|
||||
if (!dom) {
|
||||
return;
|
||||
} else if (key === 'subHeader') {
|
||||
return React.cloneElement(dom, {
|
||||
key
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<li
|
||||
{...props}
|
||||
key={key}
|
||||
className={cx(`AsideNav-item`, link.className, {
|
||||
[`is-open`]: link.open,
|
||||
[`is-active`]: link.active
|
||||
})}
|
||||
>
|
||||
{dom}
|
||||
{renderSubLinks(link, this.renderLink, depth, this.props)}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const navigations = this.state.navigations;
|
||||
let links: Array<React.ReactNode> = [];
|
||||
const {className, classnames: cx} = this.props;
|
||||
|
||||
navigations.forEach((navigation, index) => {
|
||||
if (!Array.isArray(navigation.children)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (navigation.prefix) {
|
||||
const prefix: JSX.Element =
|
||||
typeof navigation.prefix === 'function'
|
||||
? (navigation.prefix as any)(this.props)
|
||||
: navigation.prefix;
|
||||
links.push(
|
||||
React.cloneElement(prefix, {
|
||||
...prefix.props,
|
||||
key: `${index}-prefix`
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
navigation.label &&
|
||||
links.push(
|
||||
<li
|
||||
key={`${index}-label`}
|
||||
className={cx(`AsideNav-label`, navigation.className)}
|
||||
>
|
||||
<span>{navigation.label}</span>
|
||||
</li>
|
||||
);
|
||||
|
||||
navigation.children.forEach((item, key) => {
|
||||
const link = this.renderLink(item, `${index}-${key}`);
|
||||
link && links.push(link);
|
||||
});
|
||||
|
||||
if (navigation.affix) {
|
||||
const affix: JSX.Element =
|
||||
typeof navigation.affix === 'function'
|
||||
? (navigation.affix as any)(this.props)
|
||||
: navigation.affix;
|
||||
links.push(
|
||||
React.cloneElement(affix, {
|
||||
...affix.props,
|
||||
key: `${index}-affix`
|
||||
})
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<nav className={cx(`AsideNav`, className)}>
|
||||
<ul className={cx(`AsideNav-list`)}>{links}</ul>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(AsideNav);
|
||||
283
packages/amis-ui/src/components/AssociatedSelection.tsx
Normal file
283
packages/amis-ui/src/components/AssociatedSelection.tsx
Normal file
@@ -0,0 +1,283 @@
|
||||
/**
|
||||
* 关联多选框,仅支持两层关联选择。
|
||||
* 左边先点选,然后右边再次点选。
|
||||
* 可以满足,先从 tree 中选中一个元素,然后查出来一个列表再次勾选。
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import {BaseSelectionProps, BaseSelection} from './Selection';
|
||||
import {Options, Option} from './Select';
|
||||
import {autobind} from 'amis-core';
|
||||
import {themeable} from 'amis-core';
|
||||
import {uncontrollable} from 'amis-core';
|
||||
import GroupedSelection from './GroupedSelection';
|
||||
import TableSelection from './TableSelection';
|
||||
import ChainedSelection from './ChainedSelection';
|
||||
import {Icon} from './icons';
|
||||
import {localeable} from 'amis-core';
|
||||
import Tree from './Tree';
|
||||
import {SpinnerExtraProps} from './Spinner';
|
||||
|
||||
export interface AssociatedSelectionProps
|
||||
extends BaseSelectionProps,
|
||||
SpinnerExtraProps {
|
||||
leftOptions: Options;
|
||||
leftDefaultValue?: any;
|
||||
leftMode?: 'tree' | 'list' | 'group';
|
||||
rightMode?: 'table' | 'list' | 'group' | 'tree' | 'chained';
|
||||
columns?: Array<any>;
|
||||
cellRender?: (
|
||||
column: {
|
||||
name: string;
|
||||
label: string;
|
||||
[propName: string]: any;
|
||||
},
|
||||
option: Option,
|
||||
colIndex: number,
|
||||
rowIndex: number
|
||||
) => JSX.Element;
|
||||
}
|
||||
|
||||
export interface AssociatedSelectionState {
|
||||
leftValue?: Option;
|
||||
}
|
||||
|
||||
export class AssociatedSelection extends BaseSelection<
|
||||
AssociatedSelectionProps,
|
||||
AssociatedSelectionState
|
||||
> {
|
||||
state: AssociatedSelectionState = {
|
||||
leftValue: this.props.leftDefaultValue
|
||||
};
|
||||
|
||||
componentDidMount() {
|
||||
const leftValue = this.state.leftValue;
|
||||
const {options, onDeferLoad, deferField = 'defer'} = this.props;
|
||||
|
||||
if (leftValue) {
|
||||
const selectdOption = BaseSelection.resolveSelected(
|
||||
leftValue,
|
||||
options,
|
||||
(option: Option) => option.ref
|
||||
);
|
||||
|
||||
if (selectdOption && onDeferLoad && selectdOption[deferField]) {
|
||||
onDeferLoad(selectdOption);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@autobind
|
||||
leftOption2Value(option: Option) {
|
||||
return option.value;
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleLeftSelect(value: Option) {
|
||||
const {options, onDeferLoad, deferField = 'defer'} = this.props;
|
||||
this.setState({leftValue: value});
|
||||
|
||||
const selectdOption = BaseSelection.resolveSelected(
|
||||
value,
|
||||
options,
|
||||
(option: Option) => option.ref
|
||||
);
|
||||
|
||||
if (selectdOption && onDeferLoad && selectdOption[deferField]) {
|
||||
onDeferLoad(selectdOption);
|
||||
}
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleLeftDeferLoad(option: Option) {
|
||||
const {leftOptions, onLeftDeferLoad, onDeferLoad} = this.props;
|
||||
|
||||
if (typeof onLeftDeferLoad === 'function') {
|
||||
// TabsTransfer
|
||||
return onLeftDeferLoad?.(option, leftOptions);
|
||||
} else if (typeof onDeferLoad === 'function') {
|
||||
// Select
|
||||
return onDeferLoad?.(option);
|
||||
}
|
||||
}
|
||||
|
||||
handleRetry(option: Option) {
|
||||
const {onDeferLoad} = this.props;
|
||||
onDeferLoad?.(option);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
classnames: cx,
|
||||
className,
|
||||
leftOptions,
|
||||
options,
|
||||
option2value,
|
||||
rightMode,
|
||||
onChange,
|
||||
columns,
|
||||
value,
|
||||
disabled,
|
||||
leftMode,
|
||||
cellRender,
|
||||
multiple,
|
||||
itemRender,
|
||||
labelField,
|
||||
virtualThreshold,
|
||||
itemHeight,
|
||||
loadingConfig,
|
||||
checkAll,
|
||||
checkAllLabel,
|
||||
deferField = 'defer',
|
||||
testIdBuilder
|
||||
} = this.props;
|
||||
|
||||
const selectdOption = BaseSelection.resolveSelected(
|
||||
this.state.leftValue,
|
||||
options,
|
||||
(option: Option) => option.ref
|
||||
);
|
||||
const __ = this.props.translate;
|
||||
|
||||
return (
|
||||
<div className={cx('AssociatedSelection', className)}>
|
||||
<div className={cx('AssociatedSelection-left')}>
|
||||
{leftMode === 'tree' ? (
|
||||
<Tree
|
||||
multiple={false}
|
||||
disabled={disabled}
|
||||
value={this.state.leftValue}
|
||||
options={leftOptions}
|
||||
onChange={this.handleLeftSelect}
|
||||
onDeferLoad={this.handleLeftDeferLoad}
|
||||
virtualThreshold={virtualThreshold}
|
||||
// itemHeight={itemHeight}
|
||||
loadingConfig={loadingConfig}
|
||||
testIdBuilder={testIdBuilder?.getChild('left-selection')}
|
||||
/>
|
||||
) : (
|
||||
<GroupedSelection
|
||||
option2value={this.leftOption2Value}
|
||||
options={leftOptions}
|
||||
value={this.state.leftValue}
|
||||
disabled={disabled}
|
||||
onChange={this.handleLeftSelect}
|
||||
multiple={false}
|
||||
clearable={false}
|
||||
virtualThreshold={virtualThreshold}
|
||||
itemHeight={itemHeight}
|
||||
testIdBuilder={testIdBuilder?.getChild('left-selection')}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className={cx('AssociatedSelection-right')}>
|
||||
{this.state.leftValue ? (
|
||||
selectdOption ? (
|
||||
selectdOption[deferField] && !selectdOption.loaded ? (
|
||||
<div className={cx('AssociatedSelection-box')}>
|
||||
<div
|
||||
className={cx(
|
||||
'AssociatedSelection-reload',
|
||||
selectdOption.loading ? 'is-spin' : 'is-clickable'
|
||||
)}
|
||||
onClick={
|
||||
selectdOption.loading
|
||||
? undefined
|
||||
: this.handleRetry.bind(this, selectdOption)
|
||||
}
|
||||
>
|
||||
<Icon icon="reload" className="icon" />
|
||||
</div>
|
||||
|
||||
{selectdOption.loading ? (
|
||||
<p>{__('loading')}</p>
|
||||
) : (
|
||||
<p>{__('Transfer.refreshIcon')}</p>
|
||||
)}
|
||||
</div>
|
||||
) : rightMode === 'table' ? (
|
||||
<TableSelection
|
||||
columns={columns!}
|
||||
value={value}
|
||||
disabled={disabled}
|
||||
options={selectdOption.children || []}
|
||||
onChange={onChange}
|
||||
option2value={option2value}
|
||||
cellRender={cellRender}
|
||||
multiple={multiple}
|
||||
virtualThreshold={virtualThreshold}
|
||||
itemHeight={itemHeight}
|
||||
testIdBuilder={testIdBuilder?.getChild('right-selection')}
|
||||
/>
|
||||
) : rightMode === 'tree' ? (
|
||||
<Tree
|
||||
value={value}
|
||||
disabled={disabled}
|
||||
options={selectdOption.children || []}
|
||||
onChange={onChange!}
|
||||
multiple={multiple}
|
||||
labelField={labelField}
|
||||
virtualThreshold={virtualThreshold}
|
||||
// itemHeight={itemHeight}
|
||||
loadingConfig={loadingConfig}
|
||||
checkAllLabel={checkAllLabel}
|
||||
checkAll={checkAll}
|
||||
testIdBuilder={testIdBuilder?.getChild('right-selection')}
|
||||
/>
|
||||
) : rightMode === 'chained' ? (
|
||||
<ChainedSelection
|
||||
value={value}
|
||||
disabled={disabled}
|
||||
options={selectdOption.children || []}
|
||||
onChange={onChange}
|
||||
option2value={option2value}
|
||||
multiple={multiple}
|
||||
itemRender={itemRender}
|
||||
labelField={labelField}
|
||||
virtualThreshold={virtualThreshold}
|
||||
itemHeight={itemHeight}
|
||||
loadingConfig={loadingConfig}
|
||||
checkAllLabel={checkAllLabel}
|
||||
checkAll={checkAll}
|
||||
testIdBuilder={testIdBuilder?.getChild('right-selection')}
|
||||
/>
|
||||
) : (
|
||||
<GroupedSelection
|
||||
value={value}
|
||||
disabled={disabled}
|
||||
options={selectdOption.children || []}
|
||||
onChange={onChange}
|
||||
option2value={option2value}
|
||||
multiple={multiple}
|
||||
itemRender={itemRender}
|
||||
labelField={labelField}
|
||||
virtualThreshold={virtualThreshold}
|
||||
itemHeight={itemHeight}
|
||||
checkAllLabel={checkAllLabel}
|
||||
checkAll={checkAll}
|
||||
testIdBuilder={testIdBuilder?.getChild('right-selection')}
|
||||
/>
|
||||
)
|
||||
) : (
|
||||
<div className={cx('AssociatedSelection-box')}>
|
||||
{__('Transfer.configError')}
|
||||
</div>
|
||||
)
|
||||
) : (
|
||||
<div className={cx('AssociatedSelection-box')}>
|
||||
{__('Transfer.selectFromLeft')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(
|
||||
localeable(
|
||||
uncontrollable(AssociatedSelection, {
|
||||
value: 'onChange'
|
||||
})
|
||||
)
|
||||
);
|
||||
238
packages/amis-ui/src/components/AutoFoldedList.tsx
Normal file
238
packages/amis-ui/src/components/AutoFoldedList.tsx
Normal file
@@ -0,0 +1,238 @@
|
||||
/**
|
||||
* AutoFoldedList Component
|
||||
*
|
||||
* A component that automatically folds list items when there are too many to display.
|
||||
* When clicked, it expands to show all items.
|
||||
*
|
||||
* @component
|
||||
*/
|
||||
|
||||
import React, {useEffect, useRef, useState} from 'react';
|
||||
import {themeable, ThemeProps} from 'amis-core';
|
||||
import {resizeSensor} from 'amis-core';
|
||||
import TooltipWrapper, {type TooltipObject} from './TooltipWrapper';
|
||||
|
||||
export interface AutoFoldedListProps extends ThemeProps {
|
||||
enabled?: boolean;
|
||||
|
||||
/**
|
||||
* Maximum number of items to be visible
|
||||
*/
|
||||
maxVisibleCount?: number;
|
||||
|
||||
/**
|
||||
* Custom class name for the tooltip
|
||||
*/
|
||||
tooltipClassName?: string;
|
||||
|
||||
/**
|
||||
* Configuration options for the tooltip
|
||||
*/
|
||||
tooltipOptions?: TooltipObject;
|
||||
|
||||
/**
|
||||
* Array of items to be displayed in the list
|
||||
*/
|
||||
items: Array<any>;
|
||||
|
||||
/**
|
||||
* Function to render each list item
|
||||
* @param item - The item to render
|
||||
* @param index - The index of the item
|
||||
* @param folded - Whether the item is in folded state
|
||||
*/
|
||||
renderItem: (item: any, index: number, folded: boolean) => React.ReactNode;
|
||||
|
||||
/**
|
||||
* Function to render the summary text for remaining items
|
||||
* @param restItems - Array of remaining items
|
||||
*/
|
||||
renderMoreSummary?: (restItems: any[]) => React.ReactNode;
|
||||
|
||||
/**
|
||||
* Function to render the tooltip content
|
||||
* @param restItems - Array of remaining items
|
||||
*/
|
||||
renderTooltipContent?: (restItems: any[]) => React.ReactNode;
|
||||
|
||||
/**
|
||||
* Container element for the popover
|
||||
*/
|
||||
popOverContainer?: any;
|
||||
}
|
||||
|
||||
export const AutoFoldedList: React.FC<AutoFoldedListProps> = props => {
|
||||
const {
|
||||
items,
|
||||
renderItem,
|
||||
renderMoreSummary,
|
||||
renderTooltipContent,
|
||||
enabled = true,
|
||||
classnames: cx,
|
||||
popOverContainer,
|
||||
tooltipClassName,
|
||||
tooltipOptions,
|
||||
maxVisibleCount
|
||||
} = props;
|
||||
|
||||
// State to track number of visible items
|
||||
const [visibleCount, setVisibleCount] = useState(0);
|
||||
|
||||
// Refs for container and "more" elements
|
||||
const moreRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const [visibleItems, restItems] = React.useMemo(() => {
|
||||
return [
|
||||
visibleCount && enabled ? items.slice(0, visibleCount) : items,
|
||||
visibleCount && enabled ? items.slice(visibleCount) : []
|
||||
];
|
||||
}, [items, visibleCount, enabled]);
|
||||
|
||||
/**
|
||||
* Renders a single list item with proper key
|
||||
*/
|
||||
const itemRender = React.useCallback(
|
||||
(item: any, index: number, folded: boolean) => {
|
||||
const dom = renderItem(item, index, folded);
|
||||
if (React.isValidElement(dom)) {
|
||||
return React.cloneElement<any>(dom, {
|
||||
key: index
|
||||
});
|
||||
}
|
||||
return <div key={index}>{dom}</div>;
|
||||
},
|
||||
[renderItem]
|
||||
);
|
||||
|
||||
/**
|
||||
* Effect to calculate and update visible items count based on container width
|
||||
*/
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const more = moreRef.current!;
|
||||
const container = more.parentElement!;
|
||||
const moreWidth = Math.max(more.offsetWidth, 30);
|
||||
const gap = 10;
|
||||
let lastExtendAt = 0;
|
||||
|
||||
const calculateVisibleCount = () => {
|
||||
const rect = container.getBoundingClientRect();
|
||||
if (!rect.width) {
|
||||
return;
|
||||
}
|
||||
|
||||
const list = Array.from(container.children).filter(
|
||||
item => !item.hasAttribute('data-folder-ignore')
|
||||
);
|
||||
let rightElementsWidth = 0;
|
||||
|
||||
let rightElement: HTMLElement | null =
|
||||
more.nextElementSibling as HTMLElement;
|
||||
while (rightElement) {
|
||||
rightElementsWidth += rightElement.offsetWidth;
|
||||
rightElement = rightElement.nextElementSibling as HTMLElement;
|
||||
}
|
||||
|
||||
let last = more.previousElementSibling;
|
||||
while (last) {
|
||||
if (
|
||||
last.getBoundingClientRect().right +
|
||||
moreWidth +
|
||||
gap +
|
||||
rightElementsWidth <
|
||||
rect.right
|
||||
) {
|
||||
break;
|
||||
}
|
||||
last = last.previousElementSibling;
|
||||
}
|
||||
|
||||
if (
|
||||
last &&
|
||||
last === more.previousElementSibling &&
|
||||
Date.now() - lastExtendAt > 200 // Prevent flickering
|
||||
) {
|
||||
// Expand to show more items
|
||||
const width = (last as HTMLElement).offsetWidth;
|
||||
lastExtendAt = Date.now();
|
||||
const extend = Math.max(
|
||||
Math.floor(
|
||||
(rect.right -
|
||||
last.getBoundingClientRect().right -
|
||||
moreWidth -
|
||||
gap) /
|
||||
width
|
||||
),
|
||||
0
|
||||
);
|
||||
setVisibleCount(
|
||||
Math.min(
|
||||
list.indexOf(last) + 1 + extend,
|
||||
maxVisibleCount ?? items.length
|
||||
)
|
||||
);
|
||||
} else if (last) {
|
||||
// Collapse to show fewer items
|
||||
setVisibleCount(list.indexOf(last) + 1);
|
||||
}
|
||||
};
|
||||
|
||||
calculateVisibleCount();
|
||||
return resizeSensor(container, calculateVisibleCount, false, 'both', true);
|
||||
}, [items, maxVisibleCount, enabled]);
|
||||
|
||||
React.useLayoutEffect(() => {
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
moreRef.current!.parentElement?.classList.add(cx('AutoFoldedList'));
|
||||
return () => {
|
||||
moreRef.current!.parentElement?.classList.remove(cx('AutoFoldedList'));
|
||||
};
|
||||
}, [enabled]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{visibleItems.map((item, index) => itemRender(item, index, false))}
|
||||
<div className={cx('AutoFoldedList-more')} ref={moreRef}>
|
||||
{restItems.length > 0 ? (
|
||||
<TooltipWrapper
|
||||
container={popOverContainer}
|
||||
tooltip={{
|
||||
placement: 'auto',
|
||||
trigger: 'hover',
|
||||
showArrow: false,
|
||||
...tooltipOptions,
|
||||
children: () => (
|
||||
<div
|
||||
className={cx(
|
||||
'AutoFoldedList-more-tooltip',
|
||||
tooltipClassName
|
||||
)}
|
||||
>
|
||||
{renderTooltipContent
|
||||
? renderTooltipContent(restItems)
|
||||
: restItems.map((item, index) =>
|
||||
itemRender(item, index + visibleCount, true)
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}}
|
||||
>
|
||||
{renderMoreSummary ? (
|
||||
renderMoreSummary(restItems)
|
||||
) : (
|
||||
<span>+ {restItems.length} ...</span>
|
||||
)}
|
||||
</TooltipWrapper>
|
||||
) : null}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default themeable(AutoFoldedList);
|
||||
2
packages/amis-ui/src/components/AutoSizer.tsx
Normal file
2
packages/amis-ui/src/components/AutoSizer.tsx
Normal file
@@ -0,0 +1,2 @@
|
||||
import {AutoSizer} from './virtual-list';
|
||||
export default AutoSizer;
|
||||
280
packages/amis-ui/src/components/Avatar.tsx
Normal file
280
packages/amis-ui/src/components/Avatar.tsx
Normal file
@@ -0,0 +1,280 @@
|
||||
import * as React from 'react';
|
||||
import {ClassNamesFn, themeable, ThemeProps} from 'amis-core';
|
||||
import {Icon, IconCheckedSchema} from './icons';
|
||||
|
||||
/**
|
||||
* Avatar 属性
|
||||
*/
|
||||
interface AvatarCmptProps extends ThemeProps {
|
||||
style?: {
|
||||
[prop: string]: any;
|
||||
};
|
||||
className?: string;
|
||||
classnames: ClassNamesFn;
|
||||
|
||||
/**
|
||||
* 图片地址
|
||||
*/
|
||||
src?: string | React.ReactNode;
|
||||
|
||||
/**
|
||||
* 图标
|
||||
*/
|
||||
icon?: string | React.ReactNode | IconCheckedSchema;
|
||||
|
||||
/**
|
||||
* 图片相对于容器的缩放方式
|
||||
*/
|
||||
fit?: 'fill' | 'contain' | 'cover' | 'none' | 'scale-down';
|
||||
|
||||
/**
|
||||
* 形状
|
||||
*/
|
||||
shape?: 'circle' | 'square' | 'rounded';
|
||||
|
||||
/**
|
||||
* 大小
|
||||
*/
|
||||
size?: number | 'small' | 'default' | 'large';
|
||||
|
||||
/**
|
||||
* 文本
|
||||
*/
|
||||
text?: string;
|
||||
|
||||
/**
|
||||
* 字符类型距离左右两侧边界单位像素
|
||||
*/
|
||||
gap?: number;
|
||||
|
||||
/**
|
||||
* 图片无法显示时的替换文字地址
|
||||
*/
|
||||
alt?: string;
|
||||
|
||||
/**
|
||||
* 图片是否允许拖动
|
||||
*/
|
||||
draggable?: boolean;
|
||||
|
||||
/**
|
||||
* 图片CORS属性
|
||||
*/
|
||||
crossOrigin?: 'anonymous' | 'use-credentials' | '';
|
||||
|
||||
/**
|
||||
* 图片加载失败的事件,返回 false 会关闭组件默认的
|
||||
*/
|
||||
onError?: (event: React.SyntheticEvent<HTMLImageElement, Event>) => boolean;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
children?:
|
||||
| React.ReactNode
|
||||
| Array<React.ReactNode>
|
||||
| ((props?: any) => React.ReactNode | Array<React.ReactNode>);
|
||||
|
||||
/**
|
||||
* 点击事件
|
||||
*/
|
||||
onClick?: (e: React.MouseEvent) => void;
|
||||
|
||||
/**
|
||||
* 鼠标移入事件
|
||||
*/
|
||||
onMouseEnter?: (e: React.MouseEvent) => void;
|
||||
|
||||
/**
|
||||
* 鼠标移出事件
|
||||
*/
|
||||
onMouseLeave?: (e: React.MouseEvent) => void;
|
||||
}
|
||||
|
||||
const prefix = 'Avatar--';
|
||||
const childPrefix = prefix + 'text';
|
||||
|
||||
export interface AvatarState {
|
||||
scale: number;
|
||||
hasImg: boolean;
|
||||
}
|
||||
|
||||
export class Avatar extends React.Component<AvatarCmptProps, AvatarState> {
|
||||
static defaultProps: Partial<AvatarCmptProps> = {
|
||||
shape: 'circle',
|
||||
size: 'default',
|
||||
fit: 'cover',
|
||||
gap: 4
|
||||
};
|
||||
|
||||
state: AvatarState = {
|
||||
scale: 1,
|
||||
hasImg: true
|
||||
};
|
||||
|
||||
avatarChildrenRef: React.RefObject<HTMLElement>;
|
||||
avatarRef: React.RefObject<HTMLElement>;
|
||||
|
||||
constructor(props: AvatarCmptProps) {
|
||||
super(props);
|
||||
|
||||
this.avatarChildrenRef = React.createRef();
|
||||
this.avatarRef = React.createRef();
|
||||
|
||||
this.handleImageLoadError = this.handleImageLoadError.bind(this);
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
this.setScaleByGap();
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps: AvatarCmptProps, prevState: AvatarState) {
|
||||
const {src, gap, text, children} = this.props;
|
||||
const {hasImg} = this.state;
|
||||
if (prevProps.src !== src) {
|
||||
this.setState({
|
||||
hasImg: !!src
|
||||
});
|
||||
}
|
||||
if (
|
||||
(prevState.hasImg && !hasImg) ||
|
||||
prevProps.text !== text ||
|
||||
prevProps.children !== children ||
|
||||
prevProps.gap !== gap
|
||||
) {
|
||||
this.setScaleByGap();
|
||||
}
|
||||
}
|
||||
|
||||
handleImageLoadError(event: React.SyntheticEvent<HTMLImageElement, Event>) {
|
||||
const {onError} = this.props;
|
||||
this.setState({
|
||||
hasImg: onError ? !onError(event) : false
|
||||
});
|
||||
}
|
||||
|
||||
setScaleByGap() {
|
||||
const {gap = 4} = this.props;
|
||||
if (!this.avatarChildrenRef.current || !this.avatarRef.current) {
|
||||
return;
|
||||
}
|
||||
const childrenWidth = this.avatarChildrenRef.current.offsetWidth;
|
||||
const nodeWidth = this.avatarRef.current.offsetWidth;
|
||||
if (childrenWidth && nodeWidth) {
|
||||
if (gap * 2 < nodeWidth) {
|
||||
const diff = nodeWidth - gap * 2;
|
||||
this.setState({
|
||||
scale: diff < childrenWidth ? diff / childrenWidth : 1
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
let {
|
||||
style = {},
|
||||
className,
|
||||
shape,
|
||||
size,
|
||||
src,
|
||||
icon,
|
||||
alt,
|
||||
draggable,
|
||||
crossOrigin,
|
||||
fit,
|
||||
text,
|
||||
children,
|
||||
classnames: cx,
|
||||
onClick,
|
||||
onMouseEnter,
|
||||
onMouseLeave
|
||||
} = this.props;
|
||||
|
||||
const {scale, hasImg} = this.state;
|
||||
|
||||
const isImgRender = React.isValidElement(src);
|
||||
const isIconRender = React.isValidElement(icon);
|
||||
|
||||
let childrenRender: React.ReactNode | Array<React.ReactNode>;
|
||||
|
||||
let sizeStyle = {};
|
||||
let sizeClass = '';
|
||||
|
||||
if (typeof size === 'number') {
|
||||
sizeStyle = {
|
||||
height: size,
|
||||
width: size,
|
||||
lineHeight: size + 'px'
|
||||
};
|
||||
} else if (typeof size === 'string') {
|
||||
sizeClass =
|
||||
size === 'large'
|
||||
? `${prefix}lg`
|
||||
: size === 'small'
|
||||
? `${prefix}sm`
|
||||
: '';
|
||||
}
|
||||
|
||||
const scaleX = `scale(${scale}) translateX(-50%)`;
|
||||
const scaleStyle = {
|
||||
msTransform: scaleX,
|
||||
WebkitTransform: scaleX,
|
||||
transform: scaleX
|
||||
};
|
||||
|
||||
if (typeof src === 'string' && hasImg) {
|
||||
const imgStyle = fit ? {objectFit: fit} : {};
|
||||
childrenRender = (
|
||||
<img
|
||||
style={imgStyle}
|
||||
src={src}
|
||||
alt={alt}
|
||||
draggable={draggable}
|
||||
onError={this.handleImageLoadError}
|
||||
crossOrigin={crossOrigin}
|
||||
/>
|
||||
);
|
||||
} else if (isImgRender) {
|
||||
childrenRender = src;
|
||||
} else if (typeof text === 'string' || typeof text === 'number') {
|
||||
childrenRender = (
|
||||
<span
|
||||
className={cx(childPrefix)}
|
||||
ref={this.avatarChildrenRef}
|
||||
style={scaleStyle}
|
||||
>
|
||||
{text}
|
||||
</span>
|
||||
);
|
||||
} else if (['string', 'object'].includes(typeof icon)) {
|
||||
childrenRender = <Icon cx={cx} icon={icon} />;
|
||||
} else if (isIconRender) {
|
||||
childrenRender = icon as any;
|
||||
} else {
|
||||
childrenRender = (
|
||||
<span
|
||||
className={cx(childPrefix)}
|
||||
ref={this.avatarChildrenRef}
|
||||
style={scaleStyle}
|
||||
>
|
||||
{typeof children === 'function' ? children() : children}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<span
|
||||
className={cx(`Avatar`, className, prefix + shape, sizeClass)}
|
||||
style={{...sizeStyle, ...style}}
|
||||
onClick={onClick}
|
||||
onMouseEnter={onMouseEnter}
|
||||
onMouseLeave={onMouseLeave}
|
||||
ref={this.avatarRef}
|
||||
>
|
||||
{childrenRender}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(Avatar);
|
||||
307
packages/amis-ui/src/components/Badge.tsx
Normal file
307
packages/amis-ui/src/components/Badge.tsx
Normal file
@@ -0,0 +1,307 @@
|
||||
/**
|
||||
* @file 角标组件
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import hoistNonReactStatic from 'hoist-non-react-statics';
|
||||
|
||||
import {evalExpression, buildStyle} from 'amis-core';
|
||||
import {resolveVariable, resolveVariableAndFilter} from 'amis-core';
|
||||
import {ClassNamesFn} from 'amis-core';
|
||||
|
||||
/**
|
||||
* Badge 角标。
|
||||
* 文档:https://aisuda.bce.baidu.com/amis/zh-CN/components/badge
|
||||
*/
|
||||
export interface BadgeObject {
|
||||
className?: string;
|
||||
|
||||
/**
|
||||
* 文本内容
|
||||
*/
|
||||
text?: string | number;
|
||||
|
||||
/**
|
||||
* 大小
|
||||
*/
|
||||
size?: number;
|
||||
|
||||
/**
|
||||
* 角标类型
|
||||
*/
|
||||
mode?: 'text' | 'dot' | 'ribbon';
|
||||
|
||||
/**
|
||||
* 角标位置,相对于position的位置进行偏移
|
||||
*/
|
||||
offset?: [number | string, number | string];
|
||||
|
||||
/**
|
||||
* 角标位置
|
||||
*/
|
||||
position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left';
|
||||
|
||||
/**
|
||||
* 封顶的数字值
|
||||
*/
|
||||
overflowCount?: number;
|
||||
|
||||
/**
|
||||
* 动态控制是否显示
|
||||
*/
|
||||
visibleOn?: string;
|
||||
|
||||
/**
|
||||
* 是否显示动画
|
||||
*/
|
||||
animation?: boolean;
|
||||
|
||||
/**
|
||||
* 角标的自定义样式
|
||||
*/
|
||||
style?: {
|
||||
[propName: string]: any;
|
||||
};
|
||||
|
||||
/**
|
||||
* 提示类型
|
||||
*/
|
||||
level?: 'info' | 'warning' | 'success' | 'danger' | string;
|
||||
}
|
||||
|
||||
export interface BadgeProps {
|
||||
badge?: BadgeObject;
|
||||
classnames: ClassNamesFn;
|
||||
data?: any;
|
||||
children?: React.ReactNode | Array<React.ReactNode>;
|
||||
}
|
||||
|
||||
export class Badge extends React.Component<BadgeProps, object> {
|
||||
static propsList: Array<string> = ['body', 'className', 'children'];
|
||||
|
||||
constructor(props: BadgeProps) {
|
||||
super(props);
|
||||
}
|
||||
|
||||
renderBadge(
|
||||
text: any,
|
||||
size: number,
|
||||
position: any,
|
||||
offsetStyle: any,
|
||||
sizeStyle: any,
|
||||
animationElement: any
|
||||
) {
|
||||
const {classnames: cx, badge, data} = this.props;
|
||||
let {mode = 'dot', level = 'danger', style} = badge as BadgeObject;
|
||||
|
||||
const customStyle = buildStyle(style, data);
|
||||
|
||||
if (typeof level === 'string' && level[0] === '$') {
|
||||
level = resolveVariableAndFilter(level, data);
|
||||
}
|
||||
|
||||
switch (mode) {
|
||||
case 'dot':
|
||||
return (
|
||||
<span
|
||||
className={cx('Badge-dot', `Badge--${position}`, `Badge--${level}`)}
|
||||
style={{...offsetStyle, ...sizeStyle, ...customStyle}}
|
||||
>
|
||||
{animationElement}
|
||||
</span>
|
||||
);
|
||||
case 'text':
|
||||
return (
|
||||
<span
|
||||
className={cx(
|
||||
'Badge-text',
|
||||
`Badge--${position}`,
|
||||
`Badge--${level}`
|
||||
)}
|
||||
style={{...offsetStyle, ...sizeStyle, ...customStyle}}
|
||||
>
|
||||
{text}
|
||||
{animationElement}
|
||||
</span>
|
||||
);
|
||||
case 'ribbon':
|
||||
const outSize = size * Math.sqrt(2) + 5;
|
||||
return (
|
||||
<div
|
||||
className={cx('Badge-ribbon-out', `Badge-ribbon-out--${position}`)}
|
||||
style={{width: outSize, height: outSize}}
|
||||
>
|
||||
<span
|
||||
className={cx(
|
||||
'Badge-ribbon',
|
||||
`Badge-ribbon--${position}`,
|
||||
`Badge--${level}`
|
||||
)}
|
||||
style={{...sizeStyle, ...customStyle}}
|
||||
>
|
||||
{text}
|
||||
{animationElement}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
const badge = this.props.badge;
|
||||
if (!badge) {
|
||||
return this.props.children;
|
||||
}
|
||||
const {children, classnames: cx, data} = this.props;
|
||||
let isDisplay = true;
|
||||
if (typeof badge === 'string') {
|
||||
isDisplay = evalExpression(badge, data) === true;
|
||||
}
|
||||
|
||||
let {
|
||||
mode = 'dot',
|
||||
text,
|
||||
level,
|
||||
size,
|
||||
style,
|
||||
offset,
|
||||
position = 'top-right',
|
||||
overflowCount = 99,
|
||||
visibleOn,
|
||||
className,
|
||||
animation
|
||||
} = badge;
|
||||
|
||||
if (visibleOn) {
|
||||
isDisplay = evalExpression(visibleOn, data) === true;
|
||||
}
|
||||
|
||||
if (typeof text === 'string' && text[0] === '$') {
|
||||
text = resolveVariableAndFilter(text, data);
|
||||
}
|
||||
|
||||
// 设置默认值
|
||||
if (typeof size === 'undefined') {
|
||||
if (mode === 'dot') {
|
||||
size = 6;
|
||||
} else if (mode === 'ribbon') {
|
||||
size = 12;
|
||||
} else {
|
||||
size = 16;
|
||||
}
|
||||
}
|
||||
|
||||
let sizeStyle = {};
|
||||
if (mode === 'text') {
|
||||
sizeStyle = {
|
||||
borderRadius: size / 2,
|
||||
height: size + 2,
|
||||
lineHeight: size + 'px'
|
||||
};
|
||||
// 当text、overflowCount都为number类型时,进行封顶值处理
|
||||
// 当text从模版字符串解析(text: "${badge}")数字就会变为字符串
|
||||
// 因此当设置了overflowCount属性时 如果text可以强制转换成数字 那么也进行封顶处理
|
||||
if (
|
||||
typeof overflowCount === 'number' &&
|
||||
(typeof text === 'number' || (text && !isNaN(Number(text))))
|
||||
) {
|
||||
text = (
|
||||
(text as number) > (overflowCount as number)
|
||||
? `${overflowCount}+`
|
||||
: text
|
||||
) as string | number;
|
||||
}
|
||||
|
||||
if (!text) {
|
||||
isDisplay = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (mode === 'dot') {
|
||||
sizeStyle = {width: size, height: size};
|
||||
}
|
||||
|
||||
if (mode === 'ribbon') {
|
||||
sizeStyle = {
|
||||
height: size,
|
||||
lineHeight: size + 'px',
|
||||
fontSize: size
|
||||
};
|
||||
}
|
||||
|
||||
let offsetStyle = {};
|
||||
if (offset && offset.length) {
|
||||
const left = `calc(50% + ${parseInt(offset[0] as string, 10)}px)`;
|
||||
const right = `calc(-50% + ${parseInt(offset[1] as string, 10)}px)`;
|
||||
offsetStyle = {
|
||||
transform: `translate(${left}, ${right})`
|
||||
};
|
||||
}
|
||||
|
||||
let animationBackground = 'var(--danger)';
|
||||
|
||||
if (style && style.background) {
|
||||
animationBackground = style.background;
|
||||
}
|
||||
|
||||
const animationElement = animation ? (
|
||||
<div
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
border: `1px solid ${animationBackground}`,
|
||||
borderRadius: '50%',
|
||||
animation: 'badgeDotAnimation 1.2s infinite ease-in-out'
|
||||
}}
|
||||
></div>
|
||||
) : null;
|
||||
|
||||
return (
|
||||
<div className={cx('Badge', className)}>
|
||||
{children}
|
||||
{isDisplay
|
||||
? this.renderBadge(
|
||||
text,
|
||||
size,
|
||||
position,
|
||||
offsetStyle,
|
||||
sizeStyle,
|
||||
animationElement
|
||||
)
|
||||
: null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default Badge;
|
||||
|
||||
export function withBadge<P extends object>(Component: React.ComponentType<P>) {
|
||||
return hoistNonReactStatic(
|
||||
class WithBadge extends React.Component<P & BadgeProps> {
|
||||
static displayName: string = `WithBadge(${
|
||||
Component.displayName || Component.name
|
||||
})`;
|
||||
|
||||
render() {
|
||||
const badge = this.props.badge;
|
||||
|
||||
if (!badge) {
|
||||
return <Component {...(this.props as P)} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<Badge {...(this.props as BadgeProps)}>
|
||||
<Component {...(this.props as P)} />
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
},
|
||||
Component
|
||||
);
|
||||
}
|
||||
491
packages/amis-ui/src/components/BaiduMapPicker.tsx
Normal file
491
packages/amis-ui/src/components/BaiduMapPicker.tsx
Normal file
@@ -0,0 +1,491 @@
|
||||
import React from 'react';
|
||||
import {ClassNamesFn, themeable} from 'amis-core';
|
||||
import {loadScript, autobind, uuid} from 'amis-core';
|
||||
import debounce from 'lodash/debounce';
|
||||
import {Icon} from './icons';
|
||||
|
||||
declare const BMap: any;
|
||||
|
||||
/**
|
||||
* 坐标常量说明:
|
||||
* COORDINATES_WGS84 = 1, WGS84坐标
|
||||
* COORDINATES_WGS84_MC = 2, WGS84的平面墨卡托坐标
|
||||
* COORDINATES_GCJ02 = 3,GCJ02坐标
|
||||
* COORDINATES_GCJ02_MC = 4, GCJ02的平面墨卡托坐标
|
||||
* COORDINATES_BD09 = 5, 百度bd09经纬度坐标
|
||||
* COORDINATES_BD09_MC = 6,百度bd09墨卡托坐标
|
||||
* COORDINATES_MAPBAR = 7,mapbar地图坐标
|
||||
* COORDINATES_51 = 8,51地图坐标
|
||||
*/
|
||||
const COORDINATES_WGS84 = 1;
|
||||
const COORDINATES_WGS84_MC = 2;
|
||||
const COORDINATES_GCJ02 = 3;
|
||||
const COORDINATES_GCJ02_MC = 4;
|
||||
const COORDINATES_BD09 = 5;
|
||||
const COORDINATES_BD09_MC = 6;
|
||||
const COORDINATES_MAPBAR = 7;
|
||||
const COORDINATES_51 = 8;
|
||||
|
||||
interface MapPickerProps {
|
||||
ak: string;
|
||||
coordinatesType: string;
|
||||
classnames: ClassNamesFn;
|
||||
classPrefix: string;
|
||||
placeholder?: string;
|
||||
value?: {
|
||||
address: string;
|
||||
lat: number;
|
||||
lng: number;
|
||||
city?: string;
|
||||
zoom?: number;
|
||||
};
|
||||
onChange?: (value: any) => void;
|
||||
autoSelectCurrentLoc?: boolean;
|
||||
onlySelectCurrentLoc?: boolean;
|
||||
showSug?: boolean;
|
||||
showGeoLoc?: boolean;
|
||||
hideViewControl?: boolean;
|
||||
mapStyle?: React.CSSProperties;
|
||||
}
|
||||
|
||||
interface LocationItem {
|
||||
title?: string;
|
||||
address: string;
|
||||
lat: number;
|
||||
lng: number;
|
||||
city?: string;
|
||||
}
|
||||
|
||||
interface MapPickerState {
|
||||
inputValue: string;
|
||||
locIndex?: number;
|
||||
locs: Array<LocationItem>;
|
||||
sugs: Array<string>;
|
||||
innerValue?: {
|
||||
address: string;
|
||||
lat: number;
|
||||
lng: number;
|
||||
city?: string;
|
||||
zoom?: number;
|
||||
};
|
||||
}
|
||||
|
||||
// 记录百度地图SDK加载状态
|
||||
let BMapLoadingPromise: Promise<any> | null = null;
|
||||
|
||||
export class BaiduMapPicker extends React.Component<
|
||||
MapPickerProps,
|
||||
MapPickerState
|
||||
> {
|
||||
state: MapPickerState = {
|
||||
inputValue: '',
|
||||
locs: [],
|
||||
locIndex: -1,
|
||||
sugs: [],
|
||||
innerValue: this.props.value // 内部定位的值,用于内部更新地图定位点
|
||||
};
|
||||
|
||||
id = uuid();
|
||||
mapRef: React.RefObject<HTMLDivElement> = React.createRef();
|
||||
placeholderInput?: HTMLInputElement;
|
||||
map: any;
|
||||
ac: any;
|
||||
search = debounce(
|
||||
() => {
|
||||
if (this.state.inputValue) {
|
||||
this.ac?.search(this.state.inputValue);
|
||||
} else {
|
||||
this.setState({
|
||||
sugs: []
|
||||
});
|
||||
}
|
||||
},
|
||||
250,
|
||||
{
|
||||
trailing: true,
|
||||
leading: false
|
||||
}
|
||||
);
|
||||
convertor: any;
|
||||
|
||||
componentDidMount() {
|
||||
if ((window as any).BMap) {
|
||||
this.initMap();
|
||||
} else if (BMapLoadingPromise) {
|
||||
BMapLoadingPromise.then(this.initMap).then(() => {
|
||||
BMapLoadingPromise = null;
|
||||
});
|
||||
} else {
|
||||
BMapLoadingPromise = loadScript(
|
||||
`//api.map.baidu.com/api?v=3.0&ak=${this.props.ak}&callback={{callback}}`
|
||||
);
|
||||
BMapLoadingPromise.then(this.initMap).then(() => {
|
||||
BMapLoadingPromise = null;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.ac?.dispose?.();
|
||||
this.placeholderInput && document.body.removeChild(this.placeholderInput!);
|
||||
|
||||
delete this.placeholderInput;
|
||||
delete this.map;
|
||||
}
|
||||
|
||||
componentDidUpdate(
|
||||
prevProps: Readonly<MapPickerProps>,
|
||||
prevState: Readonly<MapPickerState>
|
||||
): void {
|
||||
// 值更新后需要重绘地图
|
||||
if (prevProps.value !== this.props.value) {
|
||||
this.setState({
|
||||
innerValue: this.props.value
|
||||
});
|
||||
} else if (
|
||||
this.state.innerValue !== prevState.innerValue &&
|
||||
this.state.innerValue &&
|
||||
this.map
|
||||
) {
|
||||
this.map.clearOverlays();
|
||||
|
||||
const value = this.state.innerValue;
|
||||
|
||||
let point = value
|
||||
? new BMap.Point(value.lng, value.lat)
|
||||
: new BMap.Point(116.404, 39.915);
|
||||
const zoom = value?.zoom || 15;
|
||||
|
||||
if (this.props.coordinatesType == 'gcj02') {
|
||||
this.covertPoint(point, COORDINATES_GCJ02, COORDINATES_BD09).then(
|
||||
point => this.map.centerAndZoom(point, zoom)
|
||||
);
|
||||
} else {
|
||||
this.map.centerAndZoom(point, zoom);
|
||||
}
|
||||
|
||||
const mk = new BMap.Marker(point);
|
||||
// 增加定位点
|
||||
this.map.addOverlay(mk);
|
||||
// 移动到中心
|
||||
this.map.panTo(point);
|
||||
}
|
||||
}
|
||||
|
||||
@autobind
|
||||
async initMap() {
|
||||
const autoSelectCurrentLoc = this.props.autoSelectCurrentLoc ?? false;
|
||||
const map = new BMap.Map(this.mapRef.current, {
|
||||
enableMapClick: false
|
||||
});
|
||||
this.map = map;
|
||||
this.convertor = new BMap.Convertor();
|
||||
|
||||
const value = this.props.value;
|
||||
let point = value
|
||||
? new BMap.Point(value.lng, value.lat)
|
||||
: new BMap.Point(116.404, 39.915);
|
||||
const zoom = value?.zoom || 15;
|
||||
if (this.props.coordinatesType == 'gcj02') {
|
||||
point = await this.covertPoint(
|
||||
point,
|
||||
COORDINATES_GCJ02,
|
||||
COORDINATES_BD09
|
||||
);
|
||||
map.centerAndZoom(point, zoom);
|
||||
} else {
|
||||
map.centerAndZoom(point, zoom);
|
||||
}
|
||||
|
||||
if (!this.props.hideViewControl) {
|
||||
map.addControl(
|
||||
// @ts-ignore
|
||||
new BMap.NavigationControl({type: BMAP_NAVIGATION_CONTROL_SMALL})
|
||||
);
|
||||
}
|
||||
|
||||
const geolocationControl = new BMap.GeolocationControl();
|
||||
geolocationControl.addEventListener('locationSuccess', (e: any) => {
|
||||
this.getLocations(e.point, autoSelectCurrentLoc);
|
||||
});
|
||||
if (this.props.showGeoLoc === true) {
|
||||
map.addControl(geolocationControl);
|
||||
}
|
||||
|
||||
map.addEventListener('click', (e: any) => {
|
||||
if (this.props.onlySelectCurrentLoc) {
|
||||
return;
|
||||
}
|
||||
this.getLocations(e.point, true);
|
||||
});
|
||||
|
||||
const input = document.createElement('input');
|
||||
input.className = 'invisible';
|
||||
this.placeholderInput = input;
|
||||
document.body.appendChild(input);
|
||||
|
||||
this.ac = new BMap.Autocomplete({
|
||||
input,
|
||||
location: map,
|
||||
onSearchComplete: (result: any) => {
|
||||
// 说明已经销毁了。
|
||||
if (!this.map) {
|
||||
return;
|
||||
}
|
||||
|
||||
const sugs: Array<string> = [];
|
||||
|
||||
const poiLength = result.getNumPois();
|
||||
if (poiLength) {
|
||||
for (let i = 0; i < poiLength; i++) {
|
||||
const poi = result.getPoi(i);
|
||||
if (poi) {
|
||||
sugs.push(
|
||||
[
|
||||
poi.province,
|
||||
poi.city,
|
||||
poi.district,
|
||||
poi.street,
|
||||
poi.business
|
||||
].join(' ')
|
||||
);
|
||||
}
|
||||
}
|
||||
this.setState({
|
||||
sugs
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
value ? this.getLocations(point) : geolocationControl.location();
|
||||
}
|
||||
|
||||
@autobind
|
||||
getLocations(point: any, selectCurrentLoc?: boolean) {
|
||||
const map = this.map;
|
||||
|
||||
map.clearOverlays();
|
||||
const mk = new BMap.Marker(point);
|
||||
map.addOverlay(mk);
|
||||
map.panTo(point);
|
||||
|
||||
var geoc = new BMap.Geocoder();
|
||||
geoc.getLocation(point, (rs: any) => {
|
||||
// 说明已经销毁了。
|
||||
if (!this.map) {
|
||||
return;
|
||||
}
|
||||
|
||||
const index = 0;
|
||||
const locs: Array<LocationItem> = [];
|
||||
|
||||
locs.push({
|
||||
title: '当前位置',
|
||||
address: rs.address,
|
||||
city: rs.addressComponents.city,
|
||||
lat: rs.point.lat,
|
||||
lng: rs.point.lng
|
||||
});
|
||||
|
||||
if (Array.isArray(rs.surroundingPois)) {
|
||||
rs.surroundingPois.forEach((item: any) => {
|
||||
locs.push({
|
||||
title: item.title,
|
||||
address: item.address,
|
||||
city: item.city,
|
||||
lat: item.point.lat,
|
||||
lng: item.point.lng
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
this.setState(
|
||||
{
|
||||
locIndex: index,
|
||||
locs
|
||||
},
|
||||
() => {
|
||||
if (!selectCurrentLoc) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.triggerOnChange(locs[0]);
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleChange(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
this.setState(
|
||||
{
|
||||
inputValue: e.currentTarget.value
|
||||
},
|
||||
this.search
|
||||
);
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleSelect(e: React.MouseEvent<HTMLElement>) {
|
||||
const index = parseInt(e.currentTarget.getAttribute('data-index')!, 10);
|
||||
const loc = this.state.locs[index];
|
||||
|
||||
this.setState(
|
||||
{
|
||||
locIndex: index,
|
||||
innerValue: loc
|
||||
},
|
||||
() => {
|
||||
this.triggerOnChange(loc);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
covertPoint(point: any, from: number, to: number) {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.convertor.translate([point], from, to, (res: any) => {
|
||||
if (res.status === 0 && res.points.length) {
|
||||
resolve(new BMap.Point(res.points[0].lng, res.points[0].lat));
|
||||
} else {
|
||||
reject();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
triggerOnChange(loc: LocationItem) {
|
||||
const point = new BMap.Point(loc.lng, loc.lat);
|
||||
if (this.props.coordinatesType == 'gcj02') {
|
||||
this.covertPoint(point, COORDINATES_BD09, COORDINATES_GCJ02).then(
|
||||
(convertedPoint: any) => {
|
||||
typeof this.props?.onChange === 'function' &&
|
||||
this.props.onChange({
|
||||
address: loc.address.trim() || loc.title,
|
||||
lat: convertedPoint.lat,
|
||||
lng: convertedPoint.lng,
|
||||
city: loc.city
|
||||
});
|
||||
}
|
||||
);
|
||||
} else {
|
||||
typeof this.props?.onChange === 'function' &&
|
||||
this.props?.onChange({
|
||||
address: loc.address.trim() || loc.title,
|
||||
lat: loc.lat,
|
||||
lng: loc.lng,
|
||||
city: loc.city
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleSugSelect(e: React.MouseEvent<HTMLDivElement>) {
|
||||
const value = e.currentTarget.innerText;
|
||||
this.setState({
|
||||
inputValue: value
|
||||
});
|
||||
|
||||
var local = new BMap.LocalSearch(this.map, {
|
||||
// 智能搜索
|
||||
onSearchComplete: () => {
|
||||
const results = local.getResults();
|
||||
const poi = results.getPoi(0);
|
||||
this.setState({
|
||||
inputValue: poi?.title,
|
||||
sugs: []
|
||||
});
|
||||
this.getLocations(poi?.point, true);
|
||||
}
|
||||
});
|
||||
local.search(value);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {classnames: cx, mapStyle, placeholder} = this.props;
|
||||
const onlySelectCurrentLoc = this.props.onlySelectCurrentLoc ?? false;
|
||||
const {locIndex, locs, inputValue, sugs} = this.state;
|
||||
const showSug = this.props.showSug ?? true;
|
||||
const hasSug = Array.isArray(sugs) && sugs.length;
|
||||
|
||||
return (
|
||||
<div className={cx('MapPicker')}>
|
||||
{!onlySelectCurrentLoc && (
|
||||
<div className={cx('MapPicker-search TextControl-control')}>
|
||||
<div className={cx('TextControl-input')}>
|
||||
<input
|
||||
onChange={this.handleChange}
|
||||
value={inputValue}
|
||||
placeholder={placeholder || '搜索地点'}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div
|
||||
ref={this.mapRef}
|
||||
className={cx('MapPicker-map', {
|
||||
invisible: hasSug
|
||||
})}
|
||||
style={mapStyle}
|
||||
/>
|
||||
|
||||
{!showSug ? null : (
|
||||
<div
|
||||
className={cx('MapPicker-result', {
|
||||
invisible: hasSug
|
||||
})}
|
||||
>
|
||||
{!onlySelectCurrentLoc &&
|
||||
locs.map((item, index) => (
|
||||
<div
|
||||
onClick={this.handleSelect}
|
||||
key={index}
|
||||
data-index={index}
|
||||
className={cx('MapPicker-item')}
|
||||
>
|
||||
<div className={cx('MapPicker-itemTitle')}>{item.title}</div>
|
||||
<div className={cx('MapPicker-itemDesc')}>{item.address}</div>
|
||||
{locIndex === index ? (
|
||||
<Icon icon="success" className="icon" />
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
{onlySelectCurrentLoc && locs.length > 0 && (
|
||||
<div
|
||||
onClick={this.handleSelect}
|
||||
key="locs-current"
|
||||
data-index={0}
|
||||
className={cx('MapPicker-item')}
|
||||
>
|
||||
<div className={cx('MapPicker-itemTitle')}>{locs[0].title}</div>
|
||||
<div className={cx('MapPicker-itemDesc')}>
|
||||
{locs[0].address}
|
||||
</div>
|
||||
{locIndex === 0 ? (
|
||||
<Icon icon="success" className="icon" />
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showSug && hasSug && !onlySelectCurrentLoc ? (
|
||||
<div className={cx('MapPicker-sug')}>
|
||||
{sugs.map(item => (
|
||||
<div
|
||||
onClick={this.handleSugSelect}
|
||||
className={cx('MapPicker-sugItem')}
|
||||
key={item}
|
||||
>
|
||||
{item}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(BaiduMapPicker);
|
||||
50
packages/amis-ui/src/components/BarCode.tsx
Normal file
50
packages/amis-ui/src/components/BarCode.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* @file 基于实现 bar code
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import {ClassNamesFn, themeable} from 'amis-core';
|
||||
|
||||
import JsBarcode from 'jsbarcode';
|
||||
|
||||
export interface BarCodeProps {
|
||||
value: string;
|
||||
className?: string;
|
||||
classPrefix: string;
|
||||
options?: JsBarcode.Options;
|
||||
classnames: ClassNamesFn;
|
||||
}
|
||||
|
||||
export class BarCode extends React.Component<BarCodeProps> {
|
||||
private dom;
|
||||
|
||||
constructor(props: BarCodeProps) {
|
||||
super(props);
|
||||
this.dom = React.createRef<HTMLImageElement>();
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps: BarCodeProps) {
|
||||
if (
|
||||
this.props.value !== prevProps.value ||
|
||||
JSON.stringify(this.props.options) !== JSON.stringify(prevProps.options)
|
||||
) {
|
||||
this.renderBarCode();
|
||||
}
|
||||
}
|
||||
|
||||
renderBarCode() {
|
||||
if (this.dom.current) {
|
||||
JsBarcode(this.dom.current, this.props.value, this.props.options);
|
||||
}
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
this.renderBarCode();
|
||||
}
|
||||
|
||||
render() {
|
||||
return <img ref={this.dom} />;
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(BarCode);
|
||||
327
packages/amis-ui/src/components/Breadcrumb.tsx
Normal file
327
packages/amis-ui/src/components/Breadcrumb.tsx
Normal file
@@ -0,0 +1,327 @@
|
||||
/**
|
||||
* @file Breadcrumb 面包屑
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import TooltipWrapper, {Trigger} from './TooltipWrapper';
|
||||
import {ClassNamesFn, themeable, ThemeProps} from 'amis-core';
|
||||
import {RootClose} from 'amis-core';
|
||||
import {removeHTMLTag} from 'amis-core';
|
||||
import {Icon} from './icons';
|
||||
import type {TestIdBuilder} from 'amis-core';
|
||||
|
||||
export type ItemPlace = 'start' | 'middle' | 'end';
|
||||
export type TooltipPositionType = 'top' | 'bottom' | 'left' | 'right';
|
||||
|
||||
interface BreadcrumbItemState {
|
||||
isOpened: boolean;
|
||||
tooltipTrigger: Trigger | Array<Trigger>;
|
||||
tooltipRootClose: boolean;
|
||||
}
|
||||
|
||||
interface BreadcrumbBaseItem {
|
||||
href: string;
|
||||
icon?: string;
|
||||
label?: string;
|
||||
dropdown?: Array<BreadcrumbBaseItem>;
|
||||
}
|
||||
|
||||
interface BreadcrumbItemProps {
|
||||
item: BreadcrumbBaseItem;
|
||||
itemPlace: ItemPlace;
|
||||
labelMaxLength?: number;
|
||||
tooltipContainer?: any;
|
||||
tooltipPosition?: TooltipPositionType;
|
||||
classnames: ClassNamesFn;
|
||||
testIdBuilder?: TestIdBuilder;
|
||||
[propName: string]: any;
|
||||
}
|
||||
|
||||
interface BreadcrumbProps extends ThemeProps {
|
||||
tooltipContainer?: any;
|
||||
tooltipPosition?: TooltipPositionType;
|
||||
items: Array<BreadcrumbBaseItem>;
|
||||
testIdBuilder?: TestIdBuilder;
|
||||
[propName: string]: any;
|
||||
}
|
||||
|
||||
/**
|
||||
* Breadcrumb 面包屑类
|
||||
*/
|
||||
export class Breadcrumb extends React.Component<BreadcrumbProps> {
|
||||
Item: typeof BreadcrumbItem;
|
||||
|
||||
static defaultProps: Pick<
|
||||
BreadcrumbProps,
|
||||
'separator' | 'labelMaxLength' | 'tooltipPosition'
|
||||
> = {
|
||||
separator: '>',
|
||||
labelMaxLength: 16,
|
||||
tooltipPosition: 'top'
|
||||
};
|
||||
|
||||
render() {
|
||||
const cx = this.props.classnames;
|
||||
const {
|
||||
className,
|
||||
style,
|
||||
separatorClassName,
|
||||
items,
|
||||
separator,
|
||||
testIdBuilder,
|
||||
...restProps
|
||||
} = this.props;
|
||||
|
||||
const crumbsLength = items?.length;
|
||||
if (!crumbsLength) {
|
||||
return <div className={cx('Breadcrumb', className)}></div>;
|
||||
}
|
||||
|
||||
const crumbs = items
|
||||
.map<React.ReactNode>((item, index) => {
|
||||
const itemTestIdBuilder = testIdBuilder?.getChild(
|
||||
`item-${item.label || index}`
|
||||
);
|
||||
let itemPlace: ItemPlace = 'middle';
|
||||
if (index === 0) {
|
||||
itemPlace = 'start';
|
||||
}
|
||||
if (index === crumbsLength - 1) {
|
||||
itemPlace = 'end';
|
||||
}
|
||||
return (
|
||||
<BreadcrumbItem
|
||||
{...restProps}
|
||||
item={item}
|
||||
itemPlace={itemPlace}
|
||||
key={index}
|
||||
testIdBuilder={itemTestIdBuilder}
|
||||
></BreadcrumbItem>
|
||||
);
|
||||
})
|
||||
.reduce((prev, curr, index) => [
|
||||
prev,
|
||||
<span
|
||||
className={cx('Breadcrumb-separator', separatorClassName)}
|
||||
key={`separator-${index}`}
|
||||
>
|
||||
{separator}
|
||||
</span>,
|
||||
curr
|
||||
]);
|
||||
|
||||
return (
|
||||
<div className={cx('Breadcrumb', className)} style={style}>
|
||||
{crumbs}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* BreadcrumbItem 面包项类
|
||||
*/
|
||||
export class BreadcrumbItem extends React.Component<
|
||||
BreadcrumbItemProps,
|
||||
BreadcrumbItemState
|
||||
> {
|
||||
target: any;
|
||||
|
||||
state: BreadcrumbItemState = {
|
||||
tooltipTrigger: ['hover', 'focus'],
|
||||
tooltipRootClose: false,
|
||||
isOpened: false
|
||||
};
|
||||
|
||||
domRef = (ref: any) => {
|
||||
this.target = ref;
|
||||
};
|
||||
|
||||
toogle = (e: React.MouseEvent<any>) => {
|
||||
e.preventDefault();
|
||||
|
||||
this.setState({
|
||||
isOpened: !this.state.isOpened
|
||||
});
|
||||
};
|
||||
|
||||
close = () => {
|
||||
this.setState({
|
||||
isOpened: false
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 渲染基础面包项
|
||||
* @param showHref 是否显示超链接
|
||||
* @param itemType 基础面包项类型
|
||||
* @param item 面包项
|
||||
* @param label 渲染文本
|
||||
* @returns
|
||||
*/
|
||||
renderBreadcrumbBaseItem(
|
||||
showHref: boolean,
|
||||
itemType: 'default' | 'dropdown',
|
||||
item: BreadcrumbBaseItem,
|
||||
label?: string
|
||||
) {
|
||||
const {
|
||||
itemClassName,
|
||||
dropdownItemClassName,
|
||||
classnames: cx,
|
||||
testIdBuilder
|
||||
} = this.props;
|
||||
const baseItemClassName =
|
||||
itemType === 'default' ? itemClassName : dropdownItemClassName;
|
||||
if (showHref) {
|
||||
return (
|
||||
<a
|
||||
href={item.href}
|
||||
className={cx('Breadcrumb-item-' + itemType, baseItemClassName)}
|
||||
{...testIdBuilder?.getTestId()}
|
||||
>
|
||||
{item.icon ? (
|
||||
<Icon
|
||||
cx={cx}
|
||||
icon={item.icon}
|
||||
className="Icon"
|
||||
classNameProp="Breadcrumb-icon"
|
||||
/>
|
||||
) : null}
|
||||
<span className={cx('TplField fr-view')}>{label}</span>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span
|
||||
className={cx('Breadcrumb-item-' + itemType, baseItemClassName)}
|
||||
{...testIdBuilder?.getTestId()}
|
||||
>
|
||||
{item.icon ? (
|
||||
<Icon
|
||||
cx={cx}
|
||||
icon={item.icon}
|
||||
className="Icon"
|
||||
classNameProp="Breadcrumb-icon"
|
||||
/>
|
||||
) : null}
|
||||
<span className={cx('TplField fr-view')}>{label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染基础面包项完整节点
|
||||
* @param item 面包项
|
||||
* @param tooltipPosition 浮窗提示位置
|
||||
* @param itemPlace 面包香所在相对位置
|
||||
* @param itemType 基础面包项类型
|
||||
* @returns
|
||||
*/
|
||||
renderBreadcrumbNode(
|
||||
item: BreadcrumbBaseItem,
|
||||
tooltipPosition: TooltipPositionType = 'top',
|
||||
itemPlace: ItemPlace,
|
||||
itemType: 'default' | 'dropdown'
|
||||
) {
|
||||
const {labelMaxLength, tooltipContainer} = this.props;
|
||||
const {tooltipTrigger, tooltipRootClose} = this.state;
|
||||
const pureLabel = item.label ? removeHTMLTag(item.label) : '';
|
||||
// 限制最大展示长度的最小值
|
||||
const maxLength =
|
||||
labelMaxLength && +labelMaxLength > 1 ? +labelMaxLength : 1;
|
||||
// 面包项相对位置为 middle ,且超过最大展示长度的面包项,进行缩略展示,并使用浮窗提示
|
||||
if (pureLabel.length > maxLength && itemPlace === 'middle') {
|
||||
return (
|
||||
<TooltipWrapper
|
||||
tooltip={pureLabel}
|
||||
placement={tooltipPosition}
|
||||
container={tooltipContainer}
|
||||
trigger={tooltipTrigger}
|
||||
rootClose={tooltipRootClose}
|
||||
>
|
||||
{this.renderBreadcrumbBaseItem(
|
||||
true,
|
||||
itemType,
|
||||
item,
|
||||
pureLabel.substring(0, maxLength) + '...'
|
||||
)}
|
||||
</TooltipWrapper>
|
||||
);
|
||||
}
|
||||
const showHref = !item.href || itemPlace === 'end';
|
||||
return this.renderBreadcrumbBaseItem(!showHref, itemType, item, pureLabel);
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染下拉菜单节点
|
||||
* @param dropdown 面包项下拉菜单
|
||||
* @returns
|
||||
*/
|
||||
renderDropdownNode(dropdown: BreadcrumbBaseItem[]) {
|
||||
const {dropdownClassName, classnames: cx} = this.props;
|
||||
return (
|
||||
<RootClose disabled={!this.state.isOpened} onRootClose={this.close}>
|
||||
{(ref: any) => {
|
||||
return (
|
||||
<ul
|
||||
className={cx('Breadcrumb-dropdown', dropdownClassName)}
|
||||
onClick={this.close}
|
||||
ref={ref}
|
||||
>
|
||||
{Array.isArray(dropdown) &&
|
||||
dropdown.map((menuItem: BreadcrumbBaseItem, index: number) => {
|
||||
return (
|
||||
<li key={'dropdown-item' + index}>
|
||||
{this.renderBreadcrumbNode(
|
||||
menuItem,
|
||||
'right',
|
||||
'middle',
|
||||
'dropdown'
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
);
|
||||
}}
|
||||
</RootClose>
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {item, itemPlace, tooltipPosition, classnames: cx} = this.props;
|
||||
const {dropdown, ...restItemProps} = item;
|
||||
return (
|
||||
<span
|
||||
className={cx(
|
||||
'Breadcrumb-item',
|
||||
{
|
||||
'is-opened': this.state.isOpened
|
||||
},
|
||||
{
|
||||
'Breadcrumb-item-last': itemPlace === 'end'
|
||||
}
|
||||
)}
|
||||
ref={this.domRef}
|
||||
>
|
||||
{this.renderBreadcrumbNode(
|
||||
{...restItemProps},
|
||||
tooltipPosition,
|
||||
itemPlace,
|
||||
'default'
|
||||
)}
|
||||
{dropdown ? (
|
||||
<span onClick={this.toogle} className={cx('Breadcrumb-item-caret')}>
|
||||
<Icon icon="down" className="icon" />
|
||||
</span>
|
||||
) : null}
|
||||
{dropdown && this.state.isOpened
|
||||
? this.renderDropdownNode(dropdown)
|
||||
: null}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(Breadcrumb);
|
||||
164
packages/amis-ui/src/components/Button.tsx
Normal file
164
packages/amis-ui/src/components/Button.tsx
Normal file
@@ -0,0 +1,164 @@
|
||||
/**
|
||||
* @file Button
|
||||
* @author fex
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import TooltipWrapper, {TooltipObject, Trigger} from './TooltipWrapper';
|
||||
import {TestIdBuilder, pickEventsProps} from 'amis-core';
|
||||
import {ClassNamesFn, themeable} from 'amis-core';
|
||||
import Spinner, {SpinnerExtraProps} from './Spinner';
|
||||
|
||||
export interface ButtonProps
|
||||
extends React.DOMAttributes<HTMLButtonElement>,
|
||||
SpinnerExtraProps {
|
||||
id?: string;
|
||||
className?: string;
|
||||
style?: any;
|
||||
href?: string;
|
||||
title?: string;
|
||||
size?: 'xs' | 'sm' | 'md' | 'lg';
|
||||
type: 'button' | 'reset' | 'submit';
|
||||
level: string; // 'link' | 'primary' | 'secondary' | 'info' | 'success' | 'warning' | 'danger' | 'light' | 'dark' | 'default';
|
||||
tooltip?: string | TooltipObject;
|
||||
tooltipPlacement: 'top' | 'right' | 'bottom' | 'left';
|
||||
tooltipContainer?: any;
|
||||
tooltipTrigger: Trigger | Array<Trigger>;
|
||||
tooltipRootClose: boolean;
|
||||
disabled?: boolean;
|
||||
active?: boolean;
|
||||
block?: boolean;
|
||||
iconOnly?: boolean;
|
||||
disabledTip?: string | TooltipObject;
|
||||
classPrefix: string;
|
||||
classnames: ClassNamesFn;
|
||||
componentClass: React.ElementType;
|
||||
tabIndex?: string;
|
||||
overrideClassName?: boolean;
|
||||
loading?: boolean;
|
||||
loadingClassName?: string;
|
||||
testIdBuilder?: TestIdBuilder;
|
||||
}
|
||||
|
||||
export class Button extends React.Component<ButtonProps> {
|
||||
static defaultProps: Pick<
|
||||
ButtonProps,
|
||||
| 'componentClass'
|
||||
| 'level'
|
||||
| 'type'
|
||||
| 'tooltipPlacement'
|
||||
| 'tooltipTrigger'
|
||||
| 'tooltipRootClose'
|
||||
> = {
|
||||
componentClass: 'button',
|
||||
level: 'default',
|
||||
type: 'button',
|
||||
tooltipPlacement: 'top',
|
||||
tooltipTrigger: ['hover', 'focus'],
|
||||
tooltipRootClose: false
|
||||
};
|
||||
|
||||
renderButton() {
|
||||
let {
|
||||
level,
|
||||
size = 'default',
|
||||
disabled,
|
||||
className,
|
||||
style,
|
||||
title,
|
||||
componentClass: Comp,
|
||||
classnames: cx,
|
||||
children,
|
||||
disabledTip,
|
||||
block,
|
||||
type,
|
||||
active,
|
||||
iconOnly,
|
||||
href,
|
||||
loading,
|
||||
loadingClassName,
|
||||
overrideClassName,
|
||||
loadingConfig,
|
||||
testIdBuilder,
|
||||
tabIndex,
|
||||
...rest
|
||||
} = this.props;
|
||||
|
||||
if (href) {
|
||||
Comp = 'a';
|
||||
} else if ((Comp === 'button' && disabled) || loading) {
|
||||
Comp = 'div';
|
||||
}
|
||||
|
||||
return (
|
||||
<Comp
|
||||
type={Comp === 'input' || Comp === 'button' ? type : undefined}
|
||||
{...pickEventsProps(rest)}
|
||||
onClick={rest.onClick && disabled ? () => {} : rest.onClick}
|
||||
href={href}
|
||||
{...testIdBuilder?.getTestId()}
|
||||
className={cx(
|
||||
overrideClassName
|
||||
? ''
|
||||
: {
|
||||
'Button': true,
|
||||
[`Button--${level}`]: level,
|
||||
[`Button--size-${size}`]: size,
|
||||
[`Button--block`]: block,
|
||||
[`Button--iconOnly`]: iconOnly,
|
||||
'is-disabled': disabled,
|
||||
'is-active': active
|
||||
},
|
||||
className
|
||||
)}
|
||||
style={style}
|
||||
title={title}
|
||||
disabled={disabled}
|
||||
tabIndex={tabIndex}
|
||||
>
|
||||
{loading && !disabled && (
|
||||
<Spinner
|
||||
loadingConfig={loadingConfig}
|
||||
size="sm"
|
||||
show
|
||||
icon="loading-outline"
|
||||
className={cx(
|
||||
overrideClassName
|
||||
? ''
|
||||
: {[`Button--loading Button--loading--${level}`]: level},
|
||||
loadingClassName
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
{children}
|
||||
</Comp>
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
tooltip,
|
||||
tooltipPlacement,
|
||||
tooltipContainer,
|
||||
tooltipTrigger,
|
||||
tooltipRootClose,
|
||||
disabled,
|
||||
disabledTip,
|
||||
classnames: cx
|
||||
} = this.props;
|
||||
|
||||
return (
|
||||
<TooltipWrapper
|
||||
placement={tooltipPlacement}
|
||||
tooltip={disabled ? disabledTip : tooltip}
|
||||
container={tooltipContainer}
|
||||
trigger={tooltipTrigger}
|
||||
rootClose={tooltipRootClose}
|
||||
>
|
||||
{this.renderButton()}
|
||||
</TooltipWrapper>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(Button);
|
||||
834
packages/amis-ui/src/components/CalendarMobile.tsx
Normal file
834
packages/amis-ui/src/components/CalendarMobile.tsx
Normal file
@@ -0,0 +1,834 @@
|
||||
/**
|
||||
* @file CalendarMobile
|
||||
* @description 移动端日历组件
|
||||
* @author hongyang03
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import moment from 'moment';
|
||||
import Calendar from './calendar/Calendar';
|
||||
import {themeable, ThemeProps} from 'amis-core';
|
||||
import {LocaleProps, localeable} from 'amis-core';
|
||||
import {autobind} from 'amis-core';
|
||||
import {ShortCuts} from './DatePicker';
|
||||
import type {ViewMode} from './calendar/Calendar';
|
||||
import PopUp from './PopUp';
|
||||
|
||||
export interface CalendarMobileProps extends ThemeProps, LocaleProps {
|
||||
className?: string;
|
||||
timeFormat?: string;
|
||||
inputFormat?: string;
|
||||
displayForamt?: string;
|
||||
startDate?: moment.Moment;
|
||||
endDate?: moment.Moment;
|
||||
minDate?: moment.Moment;
|
||||
maxDate?: moment.Moment;
|
||||
minDuration?: moment.Duration;
|
||||
maxDuration?: moment.Duration;
|
||||
dateFormat?: string;
|
||||
embed?: boolean;
|
||||
viewMode?: ViewMode;
|
||||
close?: () => void;
|
||||
confirm?: (startDate?: any, endTime?: any) => void;
|
||||
onChange?: (data: any, callback?: () => void) => void;
|
||||
footerExtra?: JSX.Element | null;
|
||||
showViewMode?: 'years' | 'months';
|
||||
isDatePicker?: boolean;
|
||||
timeConstraints?: {
|
||||
hours?: {
|
||||
min: number;
|
||||
max: number;
|
||||
step: number;
|
||||
};
|
||||
minutes?: {
|
||||
min: number;
|
||||
max: number;
|
||||
step: number;
|
||||
};
|
||||
seconds: {
|
||||
min: number;
|
||||
max: number;
|
||||
step: number;
|
||||
};
|
||||
};
|
||||
defaultDate?: moment.Moment;
|
||||
isEndDate?: boolean;
|
||||
popOverContainer?: any;
|
||||
}
|
||||
|
||||
export interface CalendarMobileState {
|
||||
startDate?: moment.Moment;
|
||||
endDate?: moment.Moment;
|
||||
currentDate: moment.Moment;
|
||||
showToast: boolean;
|
||||
isScrollToBottom: boolean;
|
||||
dateTime: any;
|
||||
minDate?: moment.Moment;
|
||||
maxDate?: moment.Moment;
|
||||
isPopupOpen: boolean;
|
||||
}
|
||||
|
||||
export class CalendarMobile extends React.Component<
|
||||
CalendarMobileProps,
|
||||
CalendarMobileState
|
||||
> {
|
||||
mobileBody: any;
|
||||
mobileHeader: any;
|
||||
timer: any;
|
||||
|
||||
static defaultProps: Pick<CalendarMobileProps, 'showViewMode'> = {
|
||||
showViewMode: 'months'
|
||||
};
|
||||
|
||||
constructor(props: CalendarMobileProps) {
|
||||
super(props);
|
||||
|
||||
this.mobileBody = React.createRef();
|
||||
this.mobileHeader = React.createRef();
|
||||
|
||||
const {startDate, endDate, defaultDate, minDate, maxDate} = this.props;
|
||||
const dateRange = this.getDateRange(minDate, maxDate, defaultDate);
|
||||
|
||||
this.state = {
|
||||
minDate: dateRange.minDate,
|
||||
maxDate: dateRange.maxDate,
|
||||
startDate,
|
||||
endDate,
|
||||
showToast: false,
|
||||
currentDate: dateRange.currentDate,
|
||||
isScrollToBottom: false,
|
||||
dateTime: endDate ? [endDate.hour(), endDate.minute()] : [0, 0],
|
||||
isPopupOpen: false
|
||||
};
|
||||
}
|
||||
|
||||
getDateRange(
|
||||
minDate?: moment.Moment,
|
||||
maxDate?: moment.Moment,
|
||||
defaultDate?: moment.Moment
|
||||
) {
|
||||
!moment.isMoment(minDate) || (!minDate.isValid() && (minDate = undefined));
|
||||
!moment.isMoment(maxDate) || (!maxDate.isValid() && (maxDate = undefined));
|
||||
|
||||
let currentDate = defaultDate || moment();
|
||||
let dateRange: {
|
||||
minDate: moment.Moment;
|
||||
maxDate: moment.Moment;
|
||||
} = {
|
||||
minDate: currentDate.clone().subtract(1, 'year').startOf('months'),
|
||||
maxDate: currentDate.clone().add(1, 'year').endOf('months')
|
||||
};
|
||||
if (minDate && maxDate) {
|
||||
dateRange = {
|
||||
minDate,
|
||||
maxDate
|
||||
};
|
||||
} else if (minDate && !maxDate) {
|
||||
dateRange = {
|
||||
minDate,
|
||||
maxDate: moment(minDate).add(2, 'year')
|
||||
};
|
||||
currentDate = minDate.clone();
|
||||
} else if (!minDate && maxDate) {
|
||||
dateRange = {
|
||||
minDate: moment(maxDate).subtract(2, 'year'),
|
||||
maxDate
|
||||
};
|
||||
currentDate = maxDate.clone();
|
||||
}
|
||||
|
||||
if (
|
||||
!currentDate.isBetween(dateRange.minDate, dateRange.maxDate, 'days', '[]')
|
||||
) {
|
||||
currentDate = dateRange.minDate.clone();
|
||||
}
|
||||
return {
|
||||
...dateRange,
|
||||
currentDate
|
||||
};
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
this.initMonths();
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps: CalendarMobileProps) {
|
||||
const props = this.props;
|
||||
const {classPrefix: ns} = props;
|
||||
|
||||
if (
|
||||
prevProps.minDate !== props.minDate ||
|
||||
prevProps.maxDate !== props.maxDate
|
||||
) {
|
||||
const currentDate = this.state.currentDate;
|
||||
const dateRange = this.getDateRange(
|
||||
props.minDate,
|
||||
props.maxDate,
|
||||
moment(currentDate)
|
||||
);
|
||||
this.setState(
|
||||
{
|
||||
minDate: dateRange.minDate,
|
||||
maxDate: dateRange.maxDate,
|
||||
currentDate: dateRange.currentDate
|
||||
},
|
||||
() => this.initMonths()
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
(prevProps.startDate !== props.startDate &&
|
||||
props.startDate !== this.state.startDate) ||
|
||||
(prevProps.endDate !== props.endDate &&
|
||||
props.endDate !== this.state.endDate)
|
||||
) {
|
||||
this.setState(
|
||||
{
|
||||
startDate: props.startDate,
|
||||
endDate: props.endDate
|
||||
},
|
||||
() =>
|
||||
requestAnimationFrame(() => {
|
||||
document
|
||||
.querySelector(
|
||||
`.${ns}CalendarMobile:not(.${ns}CalendarMobile-embed) .rdtRangeStart:not(.rdtNew)`
|
||||
)
|
||||
?.scrollIntoView();
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.setState({showToast: false});
|
||||
clearTimeout(this.timer);
|
||||
}
|
||||
|
||||
initMonths() {
|
||||
if (this.mobileBody.current) {
|
||||
const defaultDate = this.props.defaultDate || this.state.currentDate;
|
||||
this.scollToDate(defaultDate ? moment(defaultDate) : moment());
|
||||
}
|
||||
}
|
||||
|
||||
scollToDate(date: moment.Moment) {
|
||||
const index = date.month();
|
||||
const currentEl = this.mobileBody.current.children[index];
|
||||
if (!currentEl) {
|
||||
return;
|
||||
}
|
||||
const header = this.mobileHeader.current;
|
||||
this.mobileBody.current.scrollBy(
|
||||
0,
|
||||
currentEl.offsetTop -
|
||||
this.mobileBody.current.scrollTop -
|
||||
header.clientHeight
|
||||
);
|
||||
}
|
||||
|
||||
@autobind
|
||||
scrollPreYear() {
|
||||
if (!this.state.currentDate) {
|
||||
return;
|
||||
}
|
||||
let {currentDate, minDate} = this.state;
|
||||
currentDate = currentDate.clone().subtract(1, 'years');
|
||||
if (minDate && currentDate.isBefore(minDate)) {
|
||||
currentDate = minDate;
|
||||
}
|
||||
this.setState({
|
||||
currentDate
|
||||
});
|
||||
this.scollToDate(currentDate);
|
||||
}
|
||||
|
||||
@autobind
|
||||
scrollAfterYear() {
|
||||
if (!this.state.currentDate) {
|
||||
return;
|
||||
}
|
||||
let {currentDate, maxDate} = this.state;
|
||||
currentDate = currentDate.clone().add(1, 'years');
|
||||
if (maxDate && currentDate.isAfter(maxDate)) {
|
||||
currentDate = maxDate;
|
||||
}
|
||||
this.setState({
|
||||
currentDate
|
||||
});
|
||||
this.scollToDate(currentDate);
|
||||
}
|
||||
|
||||
getDaysOfWeek() {
|
||||
const locale = moment().localeData();
|
||||
const days = locale.weekdaysMin();
|
||||
const first = locale.firstDayOfWeek();
|
||||
const dow: string[] = [];
|
||||
let i = 0;
|
||||
|
||||
days.forEach((day: string) => {
|
||||
dow[(7 + i++ - first) % 7] = day;
|
||||
});
|
||||
|
||||
return dow;
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleCalendarClick(isDisabled: boolean) {
|
||||
if (isDisabled) {
|
||||
this.setState({showToast: true});
|
||||
this.timer = setTimeout(() => {
|
||||
this.setState({showToast: false});
|
||||
}, 2000);
|
||||
}
|
||||
}
|
||||
|
||||
getRenderProps(props: any, currentDate: moment.Moment) {
|
||||
let {startDate, endDate} = this.state;
|
||||
const {translate: __, viewMode, isDatePicker} = this.props;
|
||||
const precision = viewMode === 'time' ? 'hours' : viewMode || 'day';
|
||||
let footerText = '';
|
||||
|
||||
if (
|
||||
startDate &&
|
||||
endDate &&
|
||||
currentDate.isBetween(startDate, endDate, precision, '()')
|
||||
) {
|
||||
props.className += ' rdtBetween';
|
||||
} else if (
|
||||
startDate &&
|
||||
endDate &&
|
||||
startDate.isSame(endDate, precision) &&
|
||||
currentDate.isSame(startDate, precision)
|
||||
) {
|
||||
props.className += ' rdtRangeStart';
|
||||
footerText = __('Calendar.beginAndEnd');
|
||||
} else if (startDate && currentDate.isSame(startDate, precision)) {
|
||||
props.className += ' rdtRangeStart';
|
||||
footerText = __('Calendar.begin');
|
||||
if (endDate) {
|
||||
props.className += ' rdtRangeHasEnd';
|
||||
}
|
||||
} else if (endDate && currentDate.isSame(endDate, precision)) {
|
||||
props.className += ' rdtRangeEnd';
|
||||
footerText = __('Calendar.end');
|
||||
}
|
||||
|
||||
if (
|
||||
precision === 'day' &&
|
||||
currentDate.date() === 1 &&
|
||||
currentDate.day() === 1
|
||||
) {
|
||||
props.className += ' rdtOldNone';
|
||||
}
|
||||
|
||||
if (isDatePicker) {
|
||||
footerText = '';
|
||||
}
|
||||
|
||||
const rdtDisabled = props.className.indexOf('rdtDisabled') > -1;
|
||||
|
||||
return {
|
||||
props,
|
||||
footerText,
|
||||
rdtDisabled
|
||||
};
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleTimeChange(newTime: any) {
|
||||
if (!newTime) {
|
||||
return;
|
||||
}
|
||||
const {onChange} = this.props;
|
||||
let {startDate, endDate} = this.state;
|
||||
if (startDate) {
|
||||
let obj = {
|
||||
dateTime: newTime,
|
||||
startDate: endDate
|
||||
? startDate
|
||||
: startDate?.clone().set({
|
||||
hour: newTime[0],
|
||||
minute: newTime[1],
|
||||
second: newTime[2] || 0
|
||||
}),
|
||||
endDate: !endDate
|
||||
? endDate
|
||||
: endDate?.clone().set({
|
||||
hour: newTime[0],
|
||||
minute: newTime[1],
|
||||
second: newTime[2] || 0
|
||||
})
|
||||
};
|
||||
this.setState(obj, () => {
|
||||
onChange && onChange(this.state);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@autobind
|
||||
checkIsValidDate(currentDate: moment.Moment) {
|
||||
const {startDate, endDate, minDate, maxDate} = this.state;
|
||||
let {minDuration, maxDuration, viewMode} = this.props;
|
||||
const precision = viewMode === 'time' ? 'hours' : viewMode || 'day';
|
||||
|
||||
if (minDate && currentDate.isBefore(minDate, precision)) {
|
||||
return false;
|
||||
} else if (maxDate && currentDate.isAfter(maxDate, precision)) {
|
||||
return false;
|
||||
} else if (startDate && !endDate) {
|
||||
if (
|
||||
minDuration &&
|
||||
currentDate.isBefore(startDate.clone().add(minDuration)) &&
|
||||
currentDate.isSameOrAfter(startDate)
|
||||
) {
|
||||
return false;
|
||||
} else if (
|
||||
maxDuration &&
|
||||
currentDate.isAfter(startDate.clone().add(maxDuration))
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@autobind
|
||||
renderMobileDay(props: any, currentDate: moment.Moment) {
|
||||
const cx = this.props.classnames;
|
||||
const renderProps = this.getRenderProps(props, currentDate);
|
||||
|
||||
return (
|
||||
<td {...renderProps.props}>
|
||||
<div
|
||||
className="calendar-wrap"
|
||||
onClick={() => this.handleCalendarClick(renderProps.rdtDisabled)}
|
||||
>
|
||||
{currentDate.date()}
|
||||
<div className={cx('CalendarMobile-range-text')}>
|
||||
{renderProps.footerText}
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
);
|
||||
}
|
||||
|
||||
@autobind
|
||||
renderMonth(props: any, month: number, year: number) {
|
||||
const cx = this.props.classnames;
|
||||
const currentDate = moment().year(year).month(month);
|
||||
const monthStr = currentDate
|
||||
.localeData()
|
||||
.monthsShort(currentDate.month(month));
|
||||
const strLength = 3;
|
||||
const monthStrFixedLength = monthStr.substring(0, strLength);
|
||||
const renderProps = this.getRenderProps(props, currentDate);
|
||||
|
||||
return (
|
||||
<td {...renderProps.props}>
|
||||
<div
|
||||
className="calendar-wrap"
|
||||
onClick={() => this.handleCalendarClick(renderProps.rdtDisabled)}
|
||||
>
|
||||
{monthStrFixedLength}
|
||||
<div className={cx('CalendarMobile-range-text')}>
|
||||
{renderProps.footerText}
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
);
|
||||
}
|
||||
|
||||
@autobind
|
||||
renderQuarter(props: any, quarter: number, year: number) {
|
||||
const cx = this.props.classnames;
|
||||
const currentDate = moment().year(year).quarter(quarter);
|
||||
const renderProps = this.getRenderProps(props, currentDate);
|
||||
|
||||
return (
|
||||
<td {...props}>
|
||||
<div
|
||||
className="calendar-wrap"
|
||||
onClick={() => this.handleCalendarClick(renderProps.rdtDisabled)}
|
||||
>
|
||||
Q{quarter}
|
||||
<div className={cx('CalendarMobile-range-text')}>
|
||||
{renderProps.footerText}
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
);
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleMobileChange(newValue: moment.Moment) {
|
||||
const {
|
||||
embed,
|
||||
minDuration,
|
||||
maxDuration,
|
||||
confirm,
|
||||
onChange,
|
||||
viewMode,
|
||||
isDatePicker
|
||||
} = this.props;
|
||||
const {startDate, endDate, dateTime, minDate, maxDate} = this.state;
|
||||
const precision = viewMode === 'time' ? 'hours' : viewMode || 'day';
|
||||
|
||||
if (minDate && newValue && newValue.isBefore(minDate, 'second')) {
|
||||
newValue = minDate;
|
||||
}
|
||||
|
||||
if (maxDate && newValue && newValue.isAfter(maxDate, 'second')) {
|
||||
newValue = maxDate;
|
||||
}
|
||||
|
||||
if (
|
||||
!isDatePicker &&
|
||||
startDate &&
|
||||
!endDate &&
|
||||
newValue.isSameOrAfter(startDate) &&
|
||||
(!minDuration ||
|
||||
newValue.isSameOrAfter(startDate.clone().add(minDuration))) &&
|
||||
(!maxDuration ||
|
||||
newValue.isSameOrBefore(startDate.clone().add(maxDuration)))
|
||||
) {
|
||||
return this.setState(
|
||||
{
|
||||
endDate: newValue.clone().endOf(precision)
|
||||
// .set({
|
||||
// hour: dateTime[0],
|
||||
// minute: dateTime[1],
|
||||
// second: dateTime[2] || 0
|
||||
// })
|
||||
},
|
||||
() => {
|
||||
onChange &&
|
||||
onChange(
|
||||
this.state,
|
||||
() => embed && confirm && confirm(startDate, endDate)
|
||||
);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
this.setState(
|
||||
{
|
||||
startDate: newValue
|
||||
.clone()
|
||||
.startOf(precision)
|
||||
.set({
|
||||
hour: dateTime[0],
|
||||
minute: dateTime[1],
|
||||
second: dateTime[2] || 0
|
||||
}),
|
||||
endDate: undefined
|
||||
},
|
||||
() => {
|
||||
onChange && onChange(this.state);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@autobind
|
||||
renderMobileCalendarBody() {
|
||||
const {
|
||||
classnames: cx,
|
||||
dateFormat,
|
||||
timeFormat,
|
||||
inputFormat,
|
||||
displayForamt,
|
||||
locale,
|
||||
viewMode = 'days',
|
||||
close,
|
||||
defaultDate,
|
||||
showViewMode,
|
||||
isEndDate
|
||||
} = this.props;
|
||||
const __ = this.props.translate;
|
||||
|
||||
const {minDate, maxDate, currentDate} = this.state;
|
||||
if (!minDate || !maxDate) {
|
||||
return;
|
||||
}
|
||||
let calendarDates: moment.Moment[] = [];
|
||||
const currentYear = moment(currentDate).format('YYYY');
|
||||
for (
|
||||
let minDateClone = minDate.clone();
|
||||
minDateClone.isSameOrBefore(maxDate);
|
||||
minDateClone.add(1, showViewMode)
|
||||
) {
|
||||
let date = minDateClone.clone();
|
||||
if (defaultDate) {
|
||||
date = moment(defaultDate).set({
|
||||
year: date.get('year'),
|
||||
month: date.get('month')
|
||||
});
|
||||
}
|
||||
if (date.year() === +currentYear) {
|
||||
calendarDates.push(date);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cx('CalendarMobile-body')} ref={this.mobileBody}>
|
||||
{calendarDates.map((calendarDate: moment.Moment, index: number) => {
|
||||
const rdtOldNone =
|
||||
showViewMode === 'months' &&
|
||||
calendarDate.clone().startOf('month').day() === 1
|
||||
? 'rdtOldNone'
|
||||
: '';
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx('CalendarMobile-calendar-wrap', rdtOldNone)}
|
||||
key={'calendar-wrap' + index}
|
||||
>
|
||||
{showViewMode === 'months' && (
|
||||
<div
|
||||
className={cx('CalendarMobile-calendar-mark')}
|
||||
key={'calendar-mark' + index}
|
||||
>
|
||||
{calendarDate.month() + 1}
|
||||
</div>
|
||||
)}
|
||||
<div className={cx('CalendarMobile-calendar-header')}>
|
||||
<span className="rdtSwitch">
|
||||
{calendarDate.format(__('dateformat.year'))}
|
||||
</span>
|
||||
{showViewMode === 'months' && (
|
||||
<span className="rdtSwitch">
|
||||
{calendarDate.format(__('MMM'))}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<Calendar
|
||||
className={cx('CalendarMobile-calendar', rdtOldNone)}
|
||||
viewDate={calendarDate}
|
||||
value={calendarDate}
|
||||
onChange={this.handleMobileChange}
|
||||
requiredConfirm={false}
|
||||
dateFormat={dateFormat}
|
||||
displayForamt={displayForamt || inputFormat}
|
||||
timeFormat=""
|
||||
isValidDate={this.checkIsValidDate}
|
||||
viewMode={viewMode}
|
||||
input={false}
|
||||
onClose={close}
|
||||
renderDay={this.renderMobileDay}
|
||||
renderMonth={this.renderMonth}
|
||||
renderQuarter={this.renderQuarter}
|
||||
locale={locale}
|
||||
hideHeader={true}
|
||||
updateOn={viewMode}
|
||||
key={'calendar' + index}
|
||||
isEndDate={isEndDate}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@autobind
|
||||
renderMobileTimePicker() {
|
||||
const {
|
||||
classnames: cx,
|
||||
timeFormat,
|
||||
locale,
|
||||
close,
|
||||
timeConstraints,
|
||||
defaultDate,
|
||||
isDatePicker,
|
||||
isEndDate
|
||||
} = this.props;
|
||||
const __ = this.props.translate;
|
||||
|
||||
const {startDate, endDate, dateTime} = this.state;
|
||||
|
||||
return (
|
||||
<div className={cx('CalendarMobile-time')}>
|
||||
<div className={cx('CalendarMobile-time-title')}>
|
||||
{isDatePicker
|
||||
? __('Date.titleTime')
|
||||
: startDate && endDate
|
||||
? __('Calendar.endPick')
|
||||
: __('Calendar.startPick')}
|
||||
</div>
|
||||
<Calendar
|
||||
className={cx('CalendarMobile-time-calendar')}
|
||||
value={defaultDate}
|
||||
onChange={this.handleTimeChange}
|
||||
requiredConfirm={false}
|
||||
timeFormat={timeFormat}
|
||||
viewMode="time"
|
||||
input={false}
|
||||
onClose={close}
|
||||
locale={locale}
|
||||
mobileUI={true}
|
||||
showToolbar={false}
|
||||
viewDate={moment().set({
|
||||
hour: dateTime[0],
|
||||
minute: dateTime[1],
|
||||
second: dateTime[2] || 0
|
||||
})}
|
||||
timeConstraints={timeConstraints}
|
||||
isValidDate={this.checkIsValidDate}
|
||||
isEndDate={isEndDate}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@autobind
|
||||
openDatePicker() {
|
||||
this.setState({isPopupOpen: true});
|
||||
}
|
||||
|
||||
@autobind
|
||||
closePopup() {
|
||||
this.setState({isPopupOpen: false});
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleDateChange(currentDate: moment.Moment) {
|
||||
this.setState({
|
||||
currentDate
|
||||
});
|
||||
this.scollToDate(currentDate);
|
||||
this.closePopup();
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
className,
|
||||
classnames: cx,
|
||||
embed,
|
||||
close,
|
||||
confirm,
|
||||
footerExtra,
|
||||
timeFormat,
|
||||
showViewMode,
|
||||
isDatePicker,
|
||||
locale,
|
||||
popOverContainer,
|
||||
timeConstraints
|
||||
} = this.props;
|
||||
const __ = this.props.translate;
|
||||
|
||||
const {
|
||||
startDate,
|
||||
endDate,
|
||||
currentDate,
|
||||
showToast,
|
||||
isScrollToBottom,
|
||||
minDate,
|
||||
maxDate,
|
||||
isPopupOpen
|
||||
} = this.state;
|
||||
|
||||
const header = (
|
||||
<div className={cx('CalendarMobile-header')} ref={this.mobileHeader}>
|
||||
<div className={cx('CalendarMobile-subtitle')}>
|
||||
<span className="subtitle-text">
|
||||
{currentDate &&
|
||||
currentDate.isSameOrBefore(minDate, showViewMode) ? null : (
|
||||
<a className="rdtPrev" onClick={this.scrollPreYear}>
|
||||
‹
|
||||
</a>
|
||||
)}
|
||||
<span onClick={this.openDatePicker}>
|
||||
{moment(currentDate).format('YYYY')}
|
||||
</span>
|
||||
{(currentDate &&
|
||||
currentDate.isSameOrAfter(maxDate, showViewMode)) ||
|
||||
isScrollToBottom ? null : (
|
||||
<a className="rdtNext" onClick={this.scrollAfterYear}>
|
||||
›
|
||||
</a>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
{showViewMode === 'months' ? (
|
||||
<div className={cx('CalendarMobile-weekdays')}>
|
||||
{this.getDaysOfWeek().map((day: string, index: number) => (
|
||||
<span key={day + index} className="weekday">
|
||||
{day}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
|
||||
const footer = (
|
||||
<div className={cx('CalendarMobile-footer')}>
|
||||
{timeFormat && startDate && this.renderMobileTimePicker()}
|
||||
<div className={cx('CalendarMobile-footer-toolbar')}>
|
||||
<div className={cx('CalendarMobile-footer-ranges')}>
|
||||
{footerExtra}
|
||||
</div>
|
||||
{confirm && !embed && (
|
||||
<a
|
||||
className={cx('Button', 'Button--primary', 'date-range-confirm', {
|
||||
'is-disabled': !startDate || !(endDate || isDatePicker)
|
||||
})}
|
||||
onClick={() => {
|
||||
confirm(startDate, endDate);
|
||||
close && close();
|
||||
}}
|
||||
>
|
||||
{__('confirm')}
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx(
|
||||
'CalendarMobile',
|
||||
embed ? 'CalendarMobile-embed' : '',
|
||||
className
|
||||
)}
|
||||
>
|
||||
<div className={cx('CalendarMobile-wrap')}>
|
||||
{header}
|
||||
{this.renderMobileCalendarBody()}
|
||||
{footer}
|
||||
</div>
|
||||
{showToast ? (
|
||||
<div className={cx('CalendarMobile-toast')}>
|
||||
{__('Calendar.toast')}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<PopUp
|
||||
className={cx(`DatePicker-popup DatePicker-mobile`)}
|
||||
container={popOverContainer}
|
||||
isShow={isPopupOpen}
|
||||
showClose={false}
|
||||
onHide={this.closePopup}
|
||||
>
|
||||
<Calendar
|
||||
value={currentDate}
|
||||
onChange={this.handleDateChange}
|
||||
requiredConfirm={false}
|
||||
isValidDate={this.checkIsValidDate}
|
||||
viewMode="months"
|
||||
timeConstraints={timeConstraints}
|
||||
input={false}
|
||||
onClose={this.closePopup}
|
||||
locale={locale}
|
||||
minDate={minDate}
|
||||
maxDate={maxDate}
|
||||
mobileUI
|
||||
/>
|
||||
</PopUp>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(localeable(CalendarMobile));
|
||||
205
packages/amis-ui/src/components/Card.tsx
Normal file
205
packages/amis-ui/src/components/Card.tsx
Normal file
@@ -0,0 +1,205 @@
|
||||
import React from 'react';
|
||||
import {isClickOnInput} from 'amis-core';
|
||||
import {ClassNamesFn, themeable, ThemeProps} from 'amis-core';
|
||||
import {buildStyle} from 'amis-core';
|
||||
export interface CardProps extends ThemeProps {
|
||||
className?: string;
|
||||
headerClassName?: string;
|
||||
titleClassName?: string;
|
||||
subTitleClassName?: string;
|
||||
descriptionClassName?: string;
|
||||
avatarTextStyle?: object;
|
||||
avatarTextClassName?: string;
|
||||
avatarClassName?: string;
|
||||
secondaryClassName?: string;
|
||||
imageClassName?: string;
|
||||
bodyClassName?: string;
|
||||
footerClassName?: string;
|
||||
media?: React.ReactNode;
|
||||
mediaPosition?: 'top' | 'left' | 'right' | 'bottom';
|
||||
mediaActionPosition?: 'outside';
|
||||
toolbar?: React.ReactNode;
|
||||
children?: React.ReactNode;
|
||||
actions?: React.ReactNode;
|
||||
title?: string | JSX.Element;
|
||||
subTitle?: string | JSX.Element;
|
||||
subTitlePlaceholder?: string | JSX.Element;
|
||||
description?: string | JSX.Element;
|
||||
descriptionPlaceholder?: string | JSX.Element;
|
||||
avatar?: string;
|
||||
avatarText?: string | JSX.Element;
|
||||
secondary?: string | JSX.Element;
|
||||
onClick?: (e: React.MouseEvent<HTMLDivElement>) => void;
|
||||
classnames: ClassNamesFn;
|
||||
data?: any;
|
||||
}
|
||||
|
||||
export class Card extends React.Component<CardProps> {
|
||||
static defaultProps: Partial<CardProps> = {
|
||||
className: '',
|
||||
avatarClassName: '',
|
||||
headerClassName: '',
|
||||
footerClassName: '',
|
||||
secondaryClassName: '',
|
||||
avatarTextClassName: '',
|
||||
bodyClassName: '',
|
||||
titleClassName: '',
|
||||
subTitleClassName: '',
|
||||
descriptionClassName: '',
|
||||
imageClassName: '',
|
||||
mediaPosition: 'left'
|
||||
};
|
||||
|
||||
constructor(props: CardProps) {
|
||||
super(props);
|
||||
this.handleClick = this.handleClick.bind(this);
|
||||
}
|
||||
|
||||
handleClick(e: React.MouseEvent<HTMLDivElement>) {
|
||||
if (isClickOnInput(e)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.props.onClick && this.props.onClick(e);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
classnames: cx,
|
||||
className,
|
||||
style,
|
||||
headerClassName,
|
||||
bodyClassName,
|
||||
titleClassName,
|
||||
subTitleClassName,
|
||||
descriptionClassName,
|
||||
avatarClassName,
|
||||
avatarTextStyle,
|
||||
imageClassName,
|
||||
avatarTextClassName,
|
||||
secondaryClassName,
|
||||
footerClassName,
|
||||
media,
|
||||
mediaPosition,
|
||||
mediaActionPosition,
|
||||
actions,
|
||||
children,
|
||||
onClick,
|
||||
toolbar,
|
||||
title,
|
||||
subTitle,
|
||||
subTitlePlaceholder,
|
||||
description,
|
||||
descriptionPlaceholder,
|
||||
secondary,
|
||||
avatar,
|
||||
avatarText,
|
||||
data
|
||||
} = this.props;
|
||||
|
||||
let heading = null;
|
||||
const isShowHeading =
|
||||
avatar ||
|
||||
avatarText ||
|
||||
title ||
|
||||
subTitle ||
|
||||
subTitlePlaceholder ||
|
||||
description ||
|
||||
descriptionPlaceholder ||
|
||||
toolbar;
|
||||
if (isShowHeading) {
|
||||
heading = (
|
||||
<div className={cx('Card-heading', headerClassName)}>
|
||||
{avatar ? (
|
||||
<span className={cx('Card-avtar', avatarClassName)}>
|
||||
<img className={cx('Card-img', imageClassName)} src={avatar} />
|
||||
</span>
|
||||
) : avatarText ? (
|
||||
<span
|
||||
className={cx('Card-avtarText', avatarTextClassName)}
|
||||
style={buildStyle(avatarTextStyle, data)}
|
||||
>
|
||||
{avatarText}
|
||||
</span>
|
||||
) : null}
|
||||
<div className={cx('Card-meta')}>
|
||||
{title ? (
|
||||
<div className={cx('Card-title', titleClassName)}>{title}</div>
|
||||
) : null}
|
||||
{subTitle || subTitlePlaceholder ? (
|
||||
<div className={cx('Card-subTitle', subTitleClassName)}>
|
||||
{subTitle
|
||||
? subTitle
|
||||
: subTitlePlaceholder
|
||||
? subTitlePlaceholder
|
||||
: null}
|
||||
</div>
|
||||
) : null}
|
||||
{description || descriptionPlaceholder ? (
|
||||
<div className={cx('Card-desc', descriptionClassName)}>
|
||||
{description
|
||||
? description
|
||||
: descriptionPlaceholder
|
||||
? descriptionPlaceholder
|
||||
: null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
{toolbar}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const body = children;
|
||||
|
||||
const actionView =
|
||||
secondary || actions ? (
|
||||
<div className={cx('Card-footer-wrapper', footerClassName)}>
|
||||
{secondary ? (
|
||||
<div className={cx('Card-secondary', secondaryClassName)}>
|
||||
{secondary}
|
||||
</div>
|
||||
) : null}
|
||||
{actions ? (
|
||||
<div className={cx('Card-actions-wrapper')}>{actions}</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null;
|
||||
|
||||
return (
|
||||
<div
|
||||
onClick={this.handleClick}
|
||||
className={cx('Card', className, {
|
||||
'Card--link': onClick
|
||||
})}
|
||||
style={style}
|
||||
>
|
||||
{media ? (
|
||||
<>
|
||||
<div className={cx(`Card-multiMedia--${mediaPosition}`)}>
|
||||
{media}
|
||||
<div className={cx('Card-multiMedia-flex')}>
|
||||
{heading}
|
||||
{body ? (
|
||||
<div className={cx('Card-body', bodyClassName)}>{body}</div>
|
||||
) : null}
|
||||
{!mediaActionPosition ? actionView : null}
|
||||
</div>
|
||||
</div>
|
||||
{mediaActionPosition === 'outside' ? actionView : null}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{heading}
|
||||
{body ? (
|
||||
<div className={cx('Card-body', bodyClassName)}>{body}</div>
|
||||
) : null}
|
||||
{actionView}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(Card);
|
||||
618
packages/amis-ui/src/components/Cascader.tsx
Normal file
618
packages/amis-ui/src/components/Cascader.tsx
Normal file
@@ -0,0 +1,618 @@
|
||||
/**
|
||||
* @file Cascader
|
||||
* @author fex
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import {autobind, getTreeAncestors} from 'amis-core';
|
||||
import {themeable} from 'amis-core';
|
||||
import {Option, Options} from './Select';
|
||||
import intersectionBy from 'lodash/intersectionBy';
|
||||
import compact from 'lodash/compact';
|
||||
import find from 'lodash/find';
|
||||
import uniqBy from 'lodash/uniqBy';
|
||||
import Button from './Button';
|
||||
import Checkbox from './Checkbox';
|
||||
import {flattenTree, findTree, getTreeDepth} from 'amis-core';
|
||||
import type {OptionsControlProps} from 'amis-core';
|
||||
import {Icon} from './icons';
|
||||
|
||||
export type CascaderOption = {
|
||||
text?: string;
|
||||
value?: string | number;
|
||||
valueField?: string;
|
||||
color?: string;
|
||||
disabled?: boolean;
|
||||
children?: Options;
|
||||
className?: string;
|
||||
[key: string]: any;
|
||||
};
|
||||
export interface CascaderProps extends OptionsControlProps {
|
||||
cascade?: boolean;
|
||||
noResultsText?: string;
|
||||
withChildren?: boolean;
|
||||
onlyChildren?: boolean;
|
||||
hideNodePathLabel?: boolean;
|
||||
mobileUI?: boolean;
|
||||
value?: (number | string)[];
|
||||
activeColor?: string;
|
||||
optionRender?: ({
|
||||
option,
|
||||
selected
|
||||
}: {
|
||||
option: CascaderOption;
|
||||
selected: boolean;
|
||||
}) => React.ReactNode;
|
||||
onClose?: () => void;
|
||||
onConfirm?: (param: any) => void;
|
||||
multiple?: boolean;
|
||||
}
|
||||
export type CascaderTab = {
|
||||
options: Options;
|
||||
};
|
||||
|
||||
export interface CascaderState {
|
||||
selectedOptions: Options;
|
||||
tabs: Array<{
|
||||
options: Options;
|
||||
}>;
|
||||
// 用于在只选择子节点模式的时候禁用按钮
|
||||
disableConfirm: boolean;
|
||||
activePaths: CascaderOption[];
|
||||
}
|
||||
|
||||
export class Cascader extends React.Component<CascaderProps, CascaderState> {
|
||||
static defaultProps = {
|
||||
labelField: 'label',
|
||||
valueField: 'value'
|
||||
};
|
||||
tabsRef: React.RefObject<HTMLDivElement> = React.createRef();
|
||||
tabRef: React.RefObject<HTMLDivElement> = React.createRef();
|
||||
constructor(props: CascaderProps) {
|
||||
super(props);
|
||||
this.state = {
|
||||
activePaths: [],
|
||||
selectedOptions: this.props.selectedOptions || [],
|
||||
tabs: [
|
||||
{
|
||||
options: this.props.options.slice() || []
|
||||
}
|
||||
],
|
||||
disableConfirm: false
|
||||
};
|
||||
}
|
||||
componentDidMount() {
|
||||
const {
|
||||
multiple,
|
||||
options,
|
||||
valueField = 'value',
|
||||
cascade,
|
||||
onlyLeaf
|
||||
} = this.props;
|
||||
let selectedOptions = this.props.selectedOptions.slice();
|
||||
let parentsCount = 0;
|
||||
let parentTree: Options = [];
|
||||
selectedOptions.forEach((item: Option) => {
|
||||
const parents = getTreeAncestors(options, item as any);
|
||||
// 获取最长路径
|
||||
if (parents && parents?.length > parentsCount) {
|
||||
parentTree = parents;
|
||||
parentsCount = parentTree.length;
|
||||
}
|
||||
});
|
||||
const selectedValues = selectedOptions.map(
|
||||
(option: Option) => option[valueField]
|
||||
);
|
||||
const tabs = parentTree.map((option: Option) => {
|
||||
if (multiple && !cascade) {
|
||||
if (
|
||||
selectedValues.includes(option[valueField]) &&
|
||||
option?.children?.length
|
||||
) {
|
||||
option.children.forEach((option: Option) => (option.disabled = true));
|
||||
}
|
||||
}
|
||||
return {
|
||||
options: option.children ? option.children : []
|
||||
};
|
||||
});
|
||||
this.setState({
|
||||
selectedOptions,
|
||||
tabs: [...this.state.tabs, ...tabs]
|
||||
});
|
||||
}
|
||||
|
||||
@autobind
|
||||
getOptionParent(option: Option) {
|
||||
const {options, valueField = 'value'} = this.props;
|
||||
let ancestors: any[] = [];
|
||||
findTree(options, (item, index, level, paths) => {
|
||||
if (item[valueField] === option[valueField]) {
|
||||
ancestors = paths;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
return ancestors.length ? ancestors[ancestors.length - 1] : null;
|
||||
}
|
||||
|
||||
@autobind
|
||||
dealParentSelect(option: Option, selectedOptions: Options): Options {
|
||||
const {valueField = 'value', onlyLeaf} = this.props;
|
||||
const parentOption = this.getOptionParent(option);
|
||||
if (parentOption && !onlyLeaf) {
|
||||
const parentChildren = parentOption?.children;
|
||||
const equalOption = intersectionBy(
|
||||
selectedOptions,
|
||||
parentChildren,
|
||||
valueField
|
||||
);
|
||||
// 包含则选中父节点
|
||||
const isParentSelected = find(selectedOptions, {
|
||||
[valueField]: parentOption[valueField]
|
||||
});
|
||||
if (equalOption.length === parentChildren?.length && !isParentSelected) {
|
||||
selectedOptions.push(parentOption);
|
||||
}
|
||||
if (equalOption.length !== parentChildren?.length && isParentSelected) {
|
||||
const index = selectedOptions.findIndex(
|
||||
(item: Option) => item[valueField] === parentOption[valueField]
|
||||
);
|
||||
selectedOptions.splice(index, 1);
|
||||
}
|
||||
return this.dealParentSelect(parentOption, selectedOptions);
|
||||
} else {
|
||||
return selectedOptions;
|
||||
}
|
||||
}
|
||||
|
||||
@autobind
|
||||
flattenTreeWithLeafNodes(option: Option) {
|
||||
return compact(
|
||||
flattenTree(Array.isArray(option) ? option : [option], node => node)
|
||||
);
|
||||
}
|
||||
|
||||
@autobind
|
||||
adjustOptionSelect(option: Option): boolean {
|
||||
const {valueField = 'value'} = this.props;
|
||||
const {selectedOptions} = this.state;
|
||||
function loop(arr: any[]): boolean {
|
||||
if (!arr.length) {
|
||||
return false;
|
||||
}
|
||||
return arr.some((item: any) => item[valueField] === option[valueField]);
|
||||
}
|
||||
return loop(selectedOptions);
|
||||
}
|
||||
|
||||
// 判断配置onlyChildren属性时节点选中情况
|
||||
@autobind
|
||||
getOnlyChildrenSelect(option: Option, selectedOptions?: Option[]) {
|
||||
const {onlyChildren} = this.props;
|
||||
selectedOptions = selectedOptions || this.state.selectedOptions;
|
||||
|
||||
return (
|
||||
onlyChildren &&
|
||||
option.children
|
||||
?.filter(option => !option.children?.length)
|
||||
.every(
|
||||
option =>
|
||||
!option.children?.length && selectedOptions?.includes(option)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@autobind
|
||||
getSelectedChildNum(option: Option): number {
|
||||
let count = 0;
|
||||
const loop = (arr: any[]) => {
|
||||
if (!arr || !arr.length) {
|
||||
return;
|
||||
}
|
||||
for (let item of arr) {
|
||||
if (item.children) {
|
||||
loop(item.children || []);
|
||||
} else {
|
||||
if (this.adjustOptionSelect(item)) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
loop(option.children || []);
|
||||
return count;
|
||||
}
|
||||
|
||||
@autobind
|
||||
dealOptionDisable(selectedOptions: Options) {
|
||||
const {
|
||||
valueField = 'value',
|
||||
options,
|
||||
cascade,
|
||||
multiple,
|
||||
onlyLeaf,
|
||||
onlyChildren // 子节点可点击
|
||||
} = this.props;
|
||||
if (!multiple || cascade || onlyChildren || onlyLeaf) {
|
||||
return;
|
||||
}
|
||||
const selectedValues = selectedOptions.map(
|
||||
(option: Option) => option[valueField]
|
||||
);
|
||||
const loop = (option: Option) => {
|
||||
if (!option.children) {
|
||||
return;
|
||||
}
|
||||
option.children &&
|
||||
option.children.forEach((childOption: Option) => {
|
||||
if (
|
||||
!selectedValues.includes(option[valueField]) &&
|
||||
!option.disabled
|
||||
) {
|
||||
childOption.disabled = false;
|
||||
}
|
||||
|
||||
if (selectedValues.includes(option[valueField]) || option.disabled) {
|
||||
childOption.disabled = true;
|
||||
}
|
||||
loop(childOption);
|
||||
});
|
||||
};
|
||||
options.forEach((option: Option) => loop(option));
|
||||
}
|
||||
|
||||
@autobind
|
||||
dealChildrenSelect(option: Option, selectedOptions: Options) {
|
||||
const {valueField = 'value', onlyChildren} = this.props;
|
||||
let index = selectedOptions.findIndex(
|
||||
(item: Option) => item[valueField] === option[valueField]
|
||||
);
|
||||
let isSelect = this.getOnlyChildrenSelect(option, selectedOptions);
|
||||
if (index !== -1) {
|
||||
selectedOptions.splice(index, 1);
|
||||
} else if (!isSelect) {
|
||||
if (!(onlyChildren && option.children?.length)) {
|
||||
selectedOptions.push(option);
|
||||
}
|
||||
}
|
||||
function loop(option: Option) {
|
||||
if (!option.children) {
|
||||
return;
|
||||
}
|
||||
option.children.forEach((item: Option) => {
|
||||
if (index !== -1 || isSelect) {
|
||||
// 删除选中节点及其子节点
|
||||
selectedOptions = selectedOptions.filter(
|
||||
(sItem: Option) => sItem[valueField] !== item[valueField]
|
||||
);
|
||||
} else {
|
||||
// 添加节点及其子节点
|
||||
if (!(onlyChildren && item.children?.length)) {
|
||||
selectedOptions.push(item);
|
||||
}
|
||||
}
|
||||
loop(item);
|
||||
});
|
||||
}
|
||||
loop(option);
|
||||
return selectedOptions;
|
||||
}
|
||||
|
||||
getParentTree = (option: Option, arr: Options): Options => {
|
||||
const parentOption = this.getOptionParent(option);
|
||||
if (parentOption) {
|
||||
arr.push(parentOption);
|
||||
return this.getParentTree(parentOption, arr);
|
||||
}
|
||||
return arr;
|
||||
};
|
||||
|
||||
@autobind
|
||||
onSelect(option: CascaderOption, tabIndex: number) {
|
||||
const {
|
||||
multiple,
|
||||
valueField = 'value',
|
||||
cascade,
|
||||
onlyLeaf,
|
||||
onlyChildren,
|
||||
withChildren
|
||||
} = this.props;
|
||||
let selectedOptions = this.state.selectedOptions;
|
||||
const isDisable = option.disabled;
|
||||
if (!isDisable) {
|
||||
if (multiple) {
|
||||
// 父子级分离
|
||||
if (cascade) {
|
||||
let index = selectedOptions.findIndex(
|
||||
(item: Option) => item[valueField] === option[valueField]
|
||||
);
|
||||
if (index !== -1) {
|
||||
selectedOptions.splice(index, 1);
|
||||
} else {
|
||||
selectedOptions.push(option);
|
||||
}
|
||||
} else {
|
||||
if (withChildren || onlyChildren) {
|
||||
selectedOptions = this.dealChildrenSelect(option, selectedOptions);
|
||||
} else {
|
||||
let index = selectedOptions.findIndex(
|
||||
(item: Option) => item[valueField] === option[valueField]
|
||||
);
|
||||
if (index !== -1) {
|
||||
selectedOptions.splice(index, 1);
|
||||
} else {
|
||||
selectedOptions.push(option);
|
||||
}
|
||||
}
|
||||
selectedOptions = this.dealParentSelect(option, selectedOptions);
|
||||
}
|
||||
} else {
|
||||
// 单选
|
||||
if (onlyLeaf) {
|
||||
if (!option.children?.length) {
|
||||
selectedOptions = [option];
|
||||
}
|
||||
} else {
|
||||
selectedOptions = [option];
|
||||
}
|
||||
}
|
||||
}
|
||||
this.dealOptionDisable(selectedOptions);
|
||||
|
||||
let disableConfirm = false;
|
||||
if (onlyLeaf && selectedOptions.length && selectedOptions[0].children) {
|
||||
disableConfirm = true;
|
||||
}
|
||||
|
||||
this.setState({
|
||||
selectedOptions,
|
||||
disableConfirm
|
||||
});
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleExpand(option: Option, tabIndex: number) {
|
||||
const activePaths = this.state.activePaths.slice();
|
||||
|
||||
if (option.children?.length) {
|
||||
activePaths[tabIndex] = option;
|
||||
} else {
|
||||
activePaths.splice(tabIndex);
|
||||
}
|
||||
|
||||
let tabs = this.state.tabs.slice();
|
||||
if (tabs.length > tabIndex + 1) {
|
||||
tabs = tabs.slice(0, tabIndex + 1);
|
||||
}
|
||||
|
||||
if (option?.children) {
|
||||
const nextTab = {
|
||||
options: option.children
|
||||
};
|
||||
if (tabs[tabIndex + 1]) {
|
||||
tabs[tabIndex + 1] = nextTab;
|
||||
} else {
|
||||
tabs.push(nextTab);
|
||||
}
|
||||
}
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
const tabWidth = this.tabRef.current?.offsetWidth || 1;
|
||||
const parentTree = this.getParentTree(option, [option]);
|
||||
const scrollLeft = (parentTree.length - 2) * tabWidth;
|
||||
if (scrollLeft !== 0) {
|
||||
(this.tabsRef.current as HTMLElement)?.scrollTo(scrollLeft, 0);
|
||||
}
|
||||
});
|
||||
|
||||
this.setState({
|
||||
activePaths,
|
||||
tabs
|
||||
});
|
||||
}
|
||||
|
||||
@autobind
|
||||
getSubmitOptions(selectedOptions: Options): Options {
|
||||
const _selectedOptions: Options = [];
|
||||
const {
|
||||
multiple,
|
||||
options,
|
||||
valueField = 'value',
|
||||
cascade,
|
||||
onlyChildren,
|
||||
withChildren
|
||||
} = this.props;
|
||||
if (cascade || onlyChildren || withChildren || !multiple) {
|
||||
return selectedOptions;
|
||||
}
|
||||
const selectedValues = selectedOptions.map(
|
||||
(option: Option) => option[valueField]
|
||||
);
|
||||
function loop(options: Options) {
|
||||
if (!options || !options.length) {
|
||||
return;
|
||||
}
|
||||
options.forEach((option: Option) => {
|
||||
if (selectedValues.includes(option[valueField])) {
|
||||
_selectedOptions.push(option);
|
||||
} else {
|
||||
loop(option.children ? option.children : []);
|
||||
}
|
||||
});
|
||||
}
|
||||
loop(options);
|
||||
return _selectedOptions;
|
||||
}
|
||||
|
||||
@autobind
|
||||
confirm() {
|
||||
const {onChange, onClose, onlyLeaf} = this.props;
|
||||
const selectedOptions = this.getSelectedOptions();
|
||||
if (onlyLeaf && selectedOptions.length && selectedOptions[0].children) {
|
||||
return;
|
||||
}
|
||||
onChange(selectedOptions);
|
||||
onClose && onClose();
|
||||
}
|
||||
|
||||
@autobind
|
||||
getSelectedOptions() {
|
||||
return uniqBy(
|
||||
this.getSubmitOptions(this.state.selectedOptions),
|
||||
this.props.valueField
|
||||
);
|
||||
}
|
||||
|
||||
@autobind
|
||||
renderOption(option: CascaderOption, tabIndex: number) {
|
||||
const {
|
||||
onlyLeaf,
|
||||
activeColor,
|
||||
optionRender,
|
||||
labelField,
|
||||
valueField = 'value',
|
||||
multiple,
|
||||
classnames: cx
|
||||
} = this.props;
|
||||
const {selectedOptions, activePaths} = this.state;
|
||||
const selectedValueArr = selectedOptions.map(item => item[valueField]);
|
||||
|
||||
let selfChecked = selectedValueArr.includes(option[valueField]);
|
||||
const color = option.color || (selfChecked ? activeColor : undefined);
|
||||
const Text = optionRender ? (
|
||||
optionRender({option, selected: selfChecked})
|
||||
) : (
|
||||
<span>{option[labelField]}</span>
|
||||
);
|
||||
|
||||
return (
|
||||
<li
|
||||
className={cx(
|
||||
'Cascader-option',
|
||||
{
|
||||
'selected': selfChecked,
|
||||
'disabled': option.disabled,
|
||||
'is-active': activePaths.includes(option)
|
||||
},
|
||||
option.className
|
||||
)}
|
||||
style={{color}}
|
||||
key={tabIndex + '-' + option[valueField]}
|
||||
onClick={() => {
|
||||
!multiple && this.onSelect(option, tabIndex);
|
||||
this.handleExpand(option, tabIndex);
|
||||
}}
|
||||
>
|
||||
{multiple ? (
|
||||
<Checkbox
|
||||
disabled={option.disabled || (onlyLeaf && option.children?.length)}
|
||||
checked={
|
||||
selectedOptions.includes(option) ||
|
||||
this.getOnlyChildrenSelect(option)
|
||||
}
|
||||
onChange={() => this.onSelect(option, tabIndex)}
|
||||
>
|
||||
<span className={cx('Cascader-option--text')}>{Text}</span>
|
||||
</Checkbox>
|
||||
) : (
|
||||
<span
|
||||
className={cx('Cascader-option--text', {
|
||||
disabled: onlyLeaf && option.children?.length
|
||||
})}
|
||||
>
|
||||
{Text}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{option.children?.length ? (
|
||||
<span className={cx('Cascader-option-arrow')}>
|
||||
<Icon icon="right-arrow-bold" className="icon" />
|
||||
</span>
|
||||
) : null}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
@autobind
|
||||
renderOptions(options: Options, tabIndex: number) {
|
||||
const {classnames: cx} = this.props;
|
||||
return (
|
||||
<ul key={tabIndex} className={cx('Cascader-options')}>
|
||||
{options.map(option => this.renderOption(option, tabIndex))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
@autobind
|
||||
renderTabs() {
|
||||
const {classnames: cx, options} = this.props;
|
||||
const {tabs} = this.state;
|
||||
const depth = getTreeDepth(options);
|
||||
return (
|
||||
<div
|
||||
className={cx(`Cascader-tabs`, depth > 3 ? 'scrollable' : '')}
|
||||
ref={this.tabsRef}
|
||||
>
|
||||
{tabs.map((tab: CascaderTab, tabIndex: number) => {
|
||||
const {options} = tab;
|
||||
return (
|
||||
<div
|
||||
className={cx(`Cascader-tab depth-${tabIndex}`)}
|
||||
ref={this.tabRef}
|
||||
key={tabIndex}
|
||||
>
|
||||
{this.renderOptions(options, tabIndex)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{depth <= 3 && options.length
|
||||
? Array(getTreeDepth(options) - tabs.length)
|
||||
.fill(1)
|
||||
.map((item: number, index: number) => (
|
||||
<div
|
||||
className={cx(`Cascader-tab depth-${index + 1}`)}
|
||||
key={index}
|
||||
></div>
|
||||
))
|
||||
: null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
classPrefix: ns,
|
||||
classnames: cx,
|
||||
className,
|
||||
onClose,
|
||||
valueField,
|
||||
translate: __
|
||||
} = this.props;
|
||||
|
||||
return (
|
||||
<div className={cx(`Cascader`, className)}>
|
||||
<div className={cx(`Cascader-btnGroup`)}>
|
||||
<Button
|
||||
className={cx(`Cascader-btnCancel`)}
|
||||
level="link"
|
||||
onClick={onClose}
|
||||
>
|
||||
{__('cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
className={cx(`Cascader-btnConfirm`)}
|
||||
level="link"
|
||||
onClick={this.confirm}
|
||||
disabled={this.state.disableConfirm}
|
||||
>
|
||||
{__('confirm')}
|
||||
</Button>
|
||||
</div>
|
||||
{this.renderTabs()}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(Cascader);
|
||||
144
packages/amis-ui/src/components/ChainedDropdownSelection.tsx
Normal file
144
packages/amis-ui/src/components/ChainedDropdownSelection.tsx
Normal file
@@ -0,0 +1,144 @@
|
||||
import React from 'react';
|
||||
import omit from 'lodash/omit';
|
||||
import {
|
||||
uncontrollable,
|
||||
autobind,
|
||||
ThemeProps,
|
||||
themeable,
|
||||
localeable,
|
||||
LocaleProps
|
||||
} from 'amis-core';
|
||||
|
||||
import {Options} from './Select';
|
||||
import {BaseSelection, BaseSelectionProps} from './Selection';
|
||||
|
||||
import DropDownSelection from './DropDownSelection';
|
||||
import type {TestIdBuilder} from 'amis-core';
|
||||
|
||||
export interface ChainedDropDownSelectionProps
|
||||
extends ThemeProps,
|
||||
LocaleProps,
|
||||
BaseSelectionProps {
|
||||
options: Array<any>;
|
||||
value: any;
|
||||
onChange: (value: any) => void;
|
||||
disabled?: boolean;
|
||||
searchable?: boolean;
|
||||
popOverContainer?: any;
|
||||
testIdBuilder?: TestIdBuilder;
|
||||
}
|
||||
|
||||
interface ChainedDropdownSelectionState {
|
||||
stacks: Array<Options>;
|
||||
values: Array<string>;
|
||||
}
|
||||
|
||||
export class ChainedDropdownSelection extends BaseSelection<
|
||||
ChainedDropDownSelectionProps,
|
||||
ChainedDropdownSelectionState
|
||||
> {
|
||||
constructor(props: ChainedDropDownSelectionProps) {
|
||||
super(props);
|
||||
|
||||
this.state = this.computed(props.value, props.options);
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps: ChainedDropDownSelectionProps) {
|
||||
const {options, value} = this.props;
|
||||
if (options !== prevProps.options || prevProps.value !== value) {
|
||||
this.setState(this.computed(value, options));
|
||||
}
|
||||
}
|
||||
|
||||
computed(value: string, options: Options) {
|
||||
const {valueField} = this.props;
|
||||
let values: Array<string> = [];
|
||||
const getValues = (opts: Options, arr: Array<string> = []) => {
|
||||
opts.forEach(item => {
|
||||
const cValue = valueField ? item[valueField] : item?.value ?? '';
|
||||
if (cValue === value) {
|
||||
values = [...arr, cValue];
|
||||
} else if (item.children) {
|
||||
getValues(item.children, [...arr, cValue]);
|
||||
}
|
||||
});
|
||||
};
|
||||
getValues(options);
|
||||
return {
|
||||
values,
|
||||
stacks: this.computedStask(values)
|
||||
};
|
||||
}
|
||||
|
||||
getFlatOptions(options: Options) {
|
||||
return options.map(item => omit(item, 'children'));
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleSelect(index: number, value: string) {
|
||||
// 当前层级点击时,需要重新设置下values的值,以及重新计算stacks列表
|
||||
const {values} = this.state;
|
||||
values.splice(index, values.length - index);
|
||||
value && values.push(value);
|
||||
const stacks = this.computedStask(values);
|
||||
this.setState(
|
||||
{
|
||||
stacks,
|
||||
values
|
||||
},
|
||||
() => {
|
||||
this.props?.onChange?.(value);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
// 根据树结构层级,寻找最后一层
|
||||
computedStask(values: string[]) {
|
||||
const {options, valueField} = this.props;
|
||||
const getDeep = (opts: Options, index: number, tems: Array<Options>) => {
|
||||
tems.push(this.getFlatOptions(opts));
|
||||
opts.forEach(op => {
|
||||
const cValue = valueField ? op[valueField] : op?.value ?? '';
|
||||
if (
|
||||
cValue === values[index] &&
|
||||
op.children &&
|
||||
values.length - 1 >= index
|
||||
) {
|
||||
getDeep(op.children, index + 1, tems);
|
||||
}
|
||||
});
|
||||
return tems;
|
||||
};
|
||||
|
||||
return getDeep(options, 0, []);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {stacks, values} = this.state;
|
||||
const {className, classnames: cx, testIdBuilder} = this.props;
|
||||
|
||||
return (
|
||||
<div className={cx('ChainedDropdownSelection', className)}>
|
||||
{stacks.map((item, index) => (
|
||||
<div className={cx('ChainedDropdownSelection-item')} key={index}>
|
||||
<DropDownSelection
|
||||
{...this.props}
|
||||
value={values[index]}
|
||||
options={item}
|
||||
onChange={value => this.handleSelect(index, value)}
|
||||
testIdBuilder={testIdBuilder?.getChild(`chained-${index}`)}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(
|
||||
localeable(
|
||||
uncontrollable(ChainedDropdownSelection, {
|
||||
value: 'onChange'
|
||||
})
|
||||
)
|
||||
);
|
||||
412
packages/amis-ui/src/components/ChainedSelection.tsx
Normal file
412
packages/amis-ui/src/components/ChainedSelection.tsx
Normal file
@@ -0,0 +1,412 @@
|
||||
/**
|
||||
* 级联多选框,支持无限极。从左侧到右侧一层层点选。
|
||||
*/
|
||||
import {BaseSelection, BaseSelectionProps} from './Selection';
|
||||
import {themeable} from 'amis-core';
|
||||
import React from 'react';
|
||||
import {uncontrollable} from 'amis-core';
|
||||
import Checkbox from './Checkbox';
|
||||
import {Option} from './Select';
|
||||
import {getTreeDepth} from 'amis-core';
|
||||
import times from 'lodash/times';
|
||||
import Spinner, {SpinnerExtraProps} from './Spinner';
|
||||
import {localeable} from 'amis-core';
|
||||
import VirtualList, {AutoSizer} from './virtual-list';
|
||||
|
||||
export interface ChainedSelectionProps
|
||||
extends BaseSelectionProps,
|
||||
SpinnerExtraProps {
|
||||
defaultSelectedIndex?: string;
|
||||
}
|
||||
|
||||
export interface ChainedSelectionState {
|
||||
selected: Array<string>;
|
||||
}
|
||||
|
||||
export class ChainedSelection extends BaseSelection<
|
||||
ChainedSelectionProps,
|
||||
ChainedSelectionState
|
||||
> {
|
||||
valueArray: Array<Option>;
|
||||
state: ChainedSelectionState = {
|
||||
selected: []
|
||||
};
|
||||
|
||||
componentDidMount() {
|
||||
const defaultSelectedIndex = this.props.defaultSelectedIndex;
|
||||
|
||||
// todo 以后支持自动展开
|
||||
if (defaultSelectedIndex !== undefined) {
|
||||
this.setState({
|
||||
selected: [`${defaultSelectedIndex}`]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
selectOption(option: Option, depth: number, id: string) {
|
||||
const {onDeferLoad, deferField = 'defer'} = this.props;
|
||||
|
||||
const selected = this.state.selected.concat();
|
||||
selected.splice(depth, selected.length - depth);
|
||||
selected.push(id);
|
||||
|
||||
this.setState(
|
||||
{
|
||||
selected
|
||||
},
|
||||
option[deferField] && onDeferLoad ? () => onDeferLoad(option) : undefined
|
||||
);
|
||||
}
|
||||
|
||||
renderItem(
|
||||
option: Option,
|
||||
index: number,
|
||||
depth: number,
|
||||
id: string,
|
||||
styles: object = {}
|
||||
) {
|
||||
const {
|
||||
labelClassName,
|
||||
disabled,
|
||||
classnames: cx,
|
||||
itemClassName,
|
||||
itemRender,
|
||||
multiple,
|
||||
labelField,
|
||||
testIdBuilder
|
||||
} = this.props;
|
||||
const valueArray = this.valueArray;
|
||||
const itemTIB = testIdBuilder?.getChild(`item-${option.value || index}`);
|
||||
|
||||
return (
|
||||
<div
|
||||
style={styles}
|
||||
key={index}
|
||||
className={cx(
|
||||
'ChainedSelection-item',
|
||||
itemClassName,
|
||||
option.className,
|
||||
disabled || option.disabled ? 'is-disabled' : '',
|
||||
!!~valueArray.indexOf(option) ? 'is-active' : ''
|
||||
)}
|
||||
onClick={() => this.toggleOption(option)}
|
||||
>
|
||||
{multiple ? (
|
||||
<Checkbox
|
||||
size="sm"
|
||||
checked={!!~valueArray.indexOf(option)}
|
||||
disabled={disabled || option.disabled}
|
||||
labelClassName={labelClassName}
|
||||
description={option.description}
|
||||
testIdBuilder={itemTIB}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<div className={cx('ChainedSelection-itemLabel')}>
|
||||
{itemRender(option, {
|
||||
index: index,
|
||||
multiple: multiple,
|
||||
checked: !!~valueArray.indexOf(option),
|
||||
onChange: () => this.toggleOption(option),
|
||||
disabled: disabled || option.disabled,
|
||||
labelField,
|
||||
classnames: cx
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
renderOption(
|
||||
option: Option,
|
||||
index: number,
|
||||
depth: number,
|
||||
id: string,
|
||||
styles: object = {}
|
||||
) {
|
||||
const {
|
||||
labelClassName,
|
||||
disabled,
|
||||
classnames: cx,
|
||||
itemClassName,
|
||||
itemRender,
|
||||
multiple,
|
||||
labelField,
|
||||
deferField = 'defer',
|
||||
loadingConfig,
|
||||
testIdBuilder
|
||||
} = this.props;
|
||||
const valueArray = this.valueArray;
|
||||
const itemTIB = testIdBuilder?.getChild(`item-${option.value || index}`);
|
||||
|
||||
if (Array.isArray(option.children) || option[deferField]) {
|
||||
return (
|
||||
<div
|
||||
style={styles}
|
||||
key={index}
|
||||
className={cx(
|
||||
'ChainedSelection-item',
|
||||
itemClassName,
|
||||
option.className,
|
||||
disabled || option.disabled ? 'is-disabled' : '',
|
||||
~this.state.selected.indexOf(id) ? 'is-active' : ''
|
||||
)}
|
||||
onClick={() => this.selectOption(option, depth, id)}
|
||||
{...itemTIB?.getTestId()}
|
||||
>
|
||||
<div className={cx('ChainedSelection-itemLabel')}>
|
||||
{itemRender(option, {
|
||||
index: index,
|
||||
multiple: multiple,
|
||||
checked: !!~this.state.selected.indexOf(id),
|
||||
onChange: () => this.selectOption(option, depth, id),
|
||||
disabled: disabled || option.disabled,
|
||||
labelField,
|
||||
classnames: cx
|
||||
})}
|
||||
</div>
|
||||
|
||||
{option[deferField] && option.loading ? (
|
||||
<Spinner loadingConfig={loadingConfig} size="sm" show />
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return this.renderItem(option, index, depth, id, styles);
|
||||
}
|
||||
|
||||
renderCheckAll() {
|
||||
const {
|
||||
multiple,
|
||||
checkAll,
|
||||
checkAllLabel,
|
||||
classnames: cx,
|
||||
translate: __,
|
||||
labelClassName,
|
||||
itemClassName
|
||||
} = this.props;
|
||||
|
||||
if (!multiple || !checkAll) {
|
||||
return null;
|
||||
}
|
||||
const availableOptions = this.getAvailableOptions();
|
||||
|
||||
const valueArray = this.valueArray;
|
||||
|
||||
const checkedAll = availableOptions.every(
|
||||
option => valueArray.indexOf(option) > -1
|
||||
);
|
||||
const checkedPartial = availableOptions.some(
|
||||
option => valueArray.indexOf(option) > -1
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx(
|
||||
'ChainedSelection-item',
|
||||
'ChainedSelection-checkAll',
|
||||
itemClassName
|
||||
)}
|
||||
onClick={this.toggleAll}
|
||||
>
|
||||
<Checkbox
|
||||
checked={checkedPartial}
|
||||
partial={checkedPartial && !checkedAll}
|
||||
size="sm"
|
||||
labelClassName={labelClassName}
|
||||
/>
|
||||
|
||||
<div className={cx('ChainedSelection-itemLabel')}>
|
||||
<span>{__(checkAllLabel)}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
value,
|
||||
options,
|
||||
className,
|
||||
placeholder,
|
||||
classnames: cx,
|
||||
option2value,
|
||||
itemRender,
|
||||
translate: __,
|
||||
virtualThreshold = 1000,
|
||||
itemHeight = 32,
|
||||
virtualListHeight,
|
||||
testIdBuilder
|
||||
} = this.props;
|
||||
|
||||
this.valueArray = BaseSelection.value2array(value, options, option2value);
|
||||
let body: Array<React.ReactNode> = [];
|
||||
|
||||
if (Array.isArray(options) && options.length) {
|
||||
const selected: Array<string | null> = this.state.selected.concat();
|
||||
const depth = Math.min(getTreeDepth(options), 3);
|
||||
times(Math.max(depth - selected.length, 1), () => selected.push(null));
|
||||
|
||||
selected.reduce(
|
||||
(
|
||||
{
|
||||
body,
|
||||
options,
|
||||
subTitle,
|
||||
indexes,
|
||||
placeholder
|
||||
}: {
|
||||
body: Array<React.ReactNode>;
|
||||
options: Array<Option> | null;
|
||||
subTitle?: string;
|
||||
indexes: Array<number>;
|
||||
placeholder?: string;
|
||||
},
|
||||
selected,
|
||||
depth
|
||||
) => {
|
||||
let nextOptions: Array<Option> = [];
|
||||
let nextSubTitle: string = '';
|
||||
let nextPlaceholder: string = '';
|
||||
let nextIndexes = indexes;
|
||||
|
||||
if (Array.isArray(options) && options.length > virtualThreshold) {
|
||||
options.forEach((option, index) => {
|
||||
const id = indexes.concat(index).join('-');
|
||||
if (id === selected) {
|
||||
nextSubTitle = option.subTitle;
|
||||
nextOptions = option.children!;
|
||||
nextIndexes = indexes.concat(index);
|
||||
nextPlaceholder = option.placeholder;
|
||||
}
|
||||
});
|
||||
|
||||
const finalOptions = options.concat();
|
||||
if (subTitle) {
|
||||
finalOptions.unshift({
|
||||
type: 'chainedSelection-subTitle',
|
||||
value: subTitle
|
||||
});
|
||||
}
|
||||
|
||||
body.push(
|
||||
<div key={depth} className={cx('ChainedSelection-col')}>
|
||||
<AutoSizer minHeight={virtualListHeight}>
|
||||
{({height}: {height: number}) => (
|
||||
<VirtualList
|
||||
height={height}
|
||||
itemCount={finalOptions.length}
|
||||
itemSize={itemHeight}
|
||||
renderItem={({
|
||||
index,
|
||||
style
|
||||
}: {
|
||||
index: number;
|
||||
style?: object;
|
||||
}) => {
|
||||
const option = finalOptions[index];
|
||||
if (!option) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (option?.type === 'chainedSelection-subTitle') {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
...style,
|
||||
width: '100%'
|
||||
}}
|
||||
key={indexes.join('-') + 'subTitle'}
|
||||
className={cx('ChainedSelection-subTitle')}
|
||||
>
|
||||
{option.value}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
index = subTitle ? index - 1 : index;
|
||||
|
||||
const id = indexes.concat(index).join('-');
|
||||
return this.renderOption(option, index, depth, id, {
|
||||
...style,
|
||||
width: '100%'
|
||||
});
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</AutoSizer>
|
||||
</div>
|
||||
);
|
||||
} else {
|
||||
body.push(
|
||||
<div key={depth} className={cx('ChainedSelection-col')}>
|
||||
{subTitle ? (
|
||||
<div className={cx('ChainedSelection-subTitle')}>
|
||||
{subTitle}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{Array.isArray(options) && options.length ? (
|
||||
options.map((option, index) => {
|
||||
const id = indexes.concat(index).join('-');
|
||||
|
||||
if (id === selected) {
|
||||
nextSubTitle = option.subTitle;
|
||||
nextOptions = option.children!;
|
||||
nextIndexes = indexes.concat(index);
|
||||
nextPlaceholder = option.placeholder;
|
||||
}
|
||||
|
||||
return this.renderOption(option, index, depth, id);
|
||||
})
|
||||
) : (
|
||||
<div className={cx('ChainedSelection-placeholder')}>
|
||||
{__(placeholder)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
options: nextOptions,
|
||||
subTitle: nextSubTitle,
|
||||
placeholder: nextPlaceholder,
|
||||
indexes: nextIndexes,
|
||||
body: body
|
||||
};
|
||||
},
|
||||
{
|
||||
options,
|
||||
body,
|
||||
indexes: [],
|
||||
placeholder
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cx('ChainedSelection', className)}>
|
||||
{body && body.length ? (
|
||||
<>
|
||||
{this.renderCheckAll()}
|
||||
{body}
|
||||
</>
|
||||
) : (
|
||||
<div className={cx('ChainedSelection-placeholder')}>
|
||||
{__(placeholder)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(
|
||||
localeable(
|
||||
uncontrollable(ChainedSelection, {
|
||||
value: 'onChange'
|
||||
})
|
||||
)
|
||||
);
|
||||
156
packages/amis-ui/src/components/Checkbox.tsx
Normal file
156
packages/amis-ui/src/components/Checkbox.tsx
Normal file
@@ -0,0 +1,156 @@
|
||||
/**
|
||||
* @file Checkbox
|
||||
* @author fex
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import {TestIdBuilder, ThemeProps, themeable} from 'amis-core';
|
||||
import {autobind} from 'amis-core';
|
||||
import Icon from './icons';
|
||||
|
||||
const preventEvent = (e: any) => e.stopPropagation();
|
||||
|
||||
interface CheckboxProps extends ThemeProps {
|
||||
type: 'checkbox' | 'radio';
|
||||
size?: 'sm' | 'lg' | 'small' | 'large';
|
||||
label?: string;
|
||||
labelClassName?: string;
|
||||
className?: string;
|
||||
onChange?: (value: any, shift?: boolean) => void;
|
||||
value?: boolean | string | number;
|
||||
inline?: boolean;
|
||||
trueValue?: boolean | string | number;
|
||||
falseValue?: boolean | string | number;
|
||||
disabled?: boolean;
|
||||
readOnly?: boolean;
|
||||
checked?: boolean;
|
||||
name?: string;
|
||||
description?: string;
|
||||
partial?: boolean;
|
||||
optionType?: 'default' | 'button';
|
||||
children?: React.ReactNode | Array<React.ReactNode>;
|
||||
testIdBuilder?: TestIdBuilder;
|
||||
dataName?: string;
|
||||
}
|
||||
|
||||
export class Checkbox extends React.Component<CheckboxProps, any> {
|
||||
static defaultProps: Pick<
|
||||
CheckboxProps,
|
||||
'trueValue' | 'falseValue' | 'type'
|
||||
> = {
|
||||
trueValue: true,
|
||||
falseValue: false,
|
||||
type: 'checkbox'
|
||||
};
|
||||
labelRef: React.RefObject<HTMLLabelElement> = React.createRef();
|
||||
@autobind
|
||||
handleCheck(e: React.ChangeEvent<any>) {
|
||||
const {trueValue, falseValue, onChange} = this.props;
|
||||
|
||||
if (!onChange) {
|
||||
return;
|
||||
}
|
||||
|
||||
onChange(
|
||||
e.currentTarget.checked ? trueValue : falseValue,
|
||||
(e.nativeEvent as MouseEvent).shiftKey
|
||||
);
|
||||
}
|
||||
|
||||
@autobind
|
||||
setClassName(className: string) {
|
||||
this.setState({
|
||||
className
|
||||
});
|
||||
}
|
||||
|
||||
render() {
|
||||
let {
|
||||
size,
|
||||
className,
|
||||
classnames: cx,
|
||||
value,
|
||||
label,
|
||||
partial,
|
||||
trueValue,
|
||||
children,
|
||||
disabled,
|
||||
description,
|
||||
readOnly,
|
||||
checked,
|
||||
type,
|
||||
name,
|
||||
labelClassName,
|
||||
optionType = 'default',
|
||||
mobileUI,
|
||||
testIdBuilder
|
||||
} = this.props;
|
||||
const {className: stateClassName} = this.state || {};
|
||||
const _checked =
|
||||
typeof checked !== 'undefined'
|
||||
? checked
|
||||
: typeof value === 'undefined'
|
||||
? value
|
||||
: value == trueValue;
|
||||
|
||||
return (
|
||||
<label
|
||||
className={cx(
|
||||
'Checkbox',
|
||||
`Checkbox--${type}--${optionType}`,
|
||||
className,
|
||||
stateClassName,
|
||||
{
|
||||
'Checkbox--partial': partial,
|
||||
[`Checkbox--${size}`]: size,
|
||||
'is-mobile': mobileUI,
|
||||
'disabled': disabled,
|
||||
'checked': _checked,
|
||||
[`Checkbox--${type}--${optionType}--checked`]:
|
||||
!disabled && _checked,
|
||||
[`Checkbox--${type}--${optionType}--disabled--unchecked`]:
|
||||
disabled && !_checked,
|
||||
[`Checkbox--${type}--${optionType}--disabled--checked`]:
|
||||
disabled && _checked
|
||||
}
|
||||
)}
|
||||
data-role="checkbox"
|
||||
{...testIdBuilder?.getTestId()}
|
||||
data-amis-name={this.props.dataName}
|
||||
ref={this.labelRef}
|
||||
>
|
||||
<input
|
||||
type={type}
|
||||
checked={
|
||||
typeof checked !== 'undefined'
|
||||
? checked
|
||||
: typeof value === 'undefined'
|
||||
? value
|
||||
: value == trueValue
|
||||
}
|
||||
onChange={this.handleCheck}
|
||||
onClick={
|
||||
preventEvent // 当点击 i 的时候,这个地方也会触发 click,很奇怪,干脆禁掉
|
||||
}
|
||||
disabled={disabled}
|
||||
readOnly={readOnly}
|
||||
name={name}
|
||||
/>
|
||||
<i {...testIdBuilder?.getChild('input').getTestId()}>
|
||||
<Icon iconContent={`${type}-icon`} className="icon" />
|
||||
</i>
|
||||
<span
|
||||
className={cx(labelClassName)}
|
||||
{...testIdBuilder?.getChild('label').getTestId()}
|
||||
>
|
||||
{children || label}
|
||||
</span>
|
||||
{description ? (
|
||||
<div className={cx('Checkbox-desc')}>{description}</div>
|
||||
) : null}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(Checkbox);
|
||||
330
packages/amis-ui/src/components/CityArea.tsx
Normal file
330
packages/amis-ui/src/components/CityArea.tsx
Normal file
@@ -0,0 +1,330 @@
|
||||
/**
|
||||
* @file 移动端城市选择器
|
||||
*/
|
||||
import React, {useEffect, useState, memo} from 'react';
|
||||
|
||||
import Picker from './Picker';
|
||||
import ResultBox from './ResultBox';
|
||||
import {useSetState, useUpdateEffect} from '../hooks';
|
||||
import {localeable, LocaleProps} from 'amis-core';
|
||||
import {themeable, ThemeProps} from 'amis-core';
|
||||
import {uncontrollable} from 'amis-core';
|
||||
import PopUp from './PopUp';
|
||||
import {PickerObjectOption} from './PickerColumn';
|
||||
|
||||
export type AreaColumnOption = {
|
||||
text: string;
|
||||
value: number;
|
||||
};
|
||||
|
||||
export interface AreaProps extends LocaleProps, ThemeProps {
|
||||
value: any;
|
||||
/**
|
||||
* 允许选择城市?
|
||||
*/
|
||||
allowCity?: boolean;
|
||||
/**
|
||||
* 允许选择地区?
|
||||
*/
|
||||
allowDistrict?: boolean;
|
||||
/**
|
||||
* 允许选择街道?
|
||||
*/
|
||||
allowStreet?: boolean;
|
||||
/**
|
||||
* 开启后只会存城市的 code 信息
|
||||
*/
|
||||
extractValue?: boolean;
|
||||
/**
|
||||
* 是否将各个信息拼接成字符串。
|
||||
*/
|
||||
joinValues?: boolean;
|
||||
/**
|
||||
* 拼接的符号是啥?
|
||||
*/
|
||||
delimiter?: string;
|
||||
/**
|
||||
* 是否禁用
|
||||
*/
|
||||
disabled?: boolean;
|
||||
mobileUI?: boolean;
|
||||
onChange: (value: any) => void;
|
||||
/** 点击完成按钮时触发 */
|
||||
onConfirm?: (result: AreaColumnOption[], index: number) => void;
|
||||
/** 点击取消按钮时触发 */
|
||||
onCancel?: (...args: unknown[]) => void;
|
||||
|
||||
popOverContainer?: any;
|
||||
}
|
||||
/**
|
||||
* 街道
|
||||
*/
|
||||
type district = {
|
||||
[propName: number]: {
|
||||
[propName: number]: Array<number>;
|
||||
};
|
||||
};
|
||||
interface DbState {
|
||||
province: number[];
|
||||
district: district;
|
||||
[key: number]: string;
|
||||
city: {
|
||||
[key: number]: number[];
|
||||
};
|
||||
}
|
||||
interface StateObj {
|
||||
columns: {options: Array<AreaColumnOption>}[];
|
||||
}
|
||||
|
||||
const CityArea = memo<AreaProps>(props => {
|
||||
const {
|
||||
joinValues = true,
|
||||
extractValue = true,
|
||||
delimiter = ',',
|
||||
allowCity = true,
|
||||
allowDistrict = true,
|
||||
allowStreet = false,
|
||||
// 默认北京东城区
|
||||
value = 110101,
|
||||
classnames: cx,
|
||||
style,
|
||||
translate: __,
|
||||
disabled = false,
|
||||
popOverContainer,
|
||||
mobileUI
|
||||
} = props;
|
||||
|
||||
const [values, setValues] = useState<Array<number>>([]);
|
||||
const [street, setStreet] = useState('');
|
||||
const [confirmValues, setConfirmValues] =
|
||||
useState<Array<PickerObjectOption>>();
|
||||
const [db, updateDb] = useSetState<DbState>();
|
||||
const [state, updateState] = useSetState<StateObj>({
|
||||
columns: []
|
||||
});
|
||||
const [isOpened, setIsOpened] = useState(false);
|
||||
|
||||
const onChange = (columnValues: Array<number>, columnIndex: number) => {
|
||||
// 清空后面的值
|
||||
while (columnValues[columnIndex++]) {
|
||||
columnValues[columnIndex++] = -1;
|
||||
}
|
||||
let [provience, city, district] = columnValues;
|
||||
if (city === -1) {
|
||||
city = db.city?.[provience]?.[0];
|
||||
}
|
||||
if (district === -1) {
|
||||
district = db.district?.[provience]?.[city]?.[0];
|
||||
}
|
||||
let tempValues = [provience, city, district];
|
||||
if (!allowDistrict) {
|
||||
tempValues.splice(2, 1);
|
||||
}
|
||||
if (!allowCity) {
|
||||
tempValues.splice(1, 1);
|
||||
}
|
||||
setValues(tempValues);
|
||||
};
|
||||
|
||||
const propsChange = () => {
|
||||
const {onChange} = props;
|
||||
const [province, city, district] = values;
|
||||
const code =
|
||||
allowDistrict && district
|
||||
? district
|
||||
: allowCity && city
|
||||
? city
|
||||
: province;
|
||||
if (typeof extractValue === 'undefined' ? joinValues : extractValue) {
|
||||
code
|
||||
? onChange(
|
||||
allowStreet && street
|
||||
? [code, street].join(delimiter)
|
||||
: String(code)
|
||||
)
|
||||
: onChange('');
|
||||
} else {
|
||||
onChange({
|
||||
code,
|
||||
provinceCode: province,
|
||||
province: db[province],
|
||||
cityCode: city,
|
||||
city: db[city],
|
||||
districtCode: district,
|
||||
district: db[district],
|
||||
street
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const onConfirm = () => {
|
||||
const confirmValues = values.map((item: number) => ({
|
||||
text: db[item],
|
||||
value: item
|
||||
}));
|
||||
setConfirmValues(confirmValues);
|
||||
propsChange();
|
||||
setIsOpened(false);
|
||||
};
|
||||
|
||||
const onCancel = () => {
|
||||
setIsOpened(false);
|
||||
if (props.onCancel) props.onCancel();
|
||||
};
|
||||
|
||||
const getPropsValue = () => {
|
||||
// 最后一项的值、默认北京东城区
|
||||
let code =
|
||||
(value && value.code) ||
|
||||
(typeof value === 'number' && value) ||
|
||||
(typeof value === 'string' && /(\d{6})/.test(value) && RegExp.$1) ||
|
||||
110101;
|
||||
const values: Array<number> = [];
|
||||
if (code && db[code]) {
|
||||
code = parseInt(code, 10);
|
||||
let provinceCode = code - (code % 10000);
|
||||
let cityCode = code - (code % 100);
|
||||
if (db[provinceCode]) {
|
||||
values[0] = provinceCode;
|
||||
}
|
||||
if (db[cityCode] && allowCity) {
|
||||
values[1] = cityCode;
|
||||
} else if (~db.city[provinceCode]?.indexOf(code) && allowCity) {
|
||||
values[1] = code;
|
||||
}
|
||||
|
||||
if (code % 100 && allowDistrict) {
|
||||
values[2] = code;
|
||||
}
|
||||
setValues(values);
|
||||
|
||||
if (props.value) {
|
||||
const confirmValues = values.map((item: number) => ({
|
||||
text: db[item],
|
||||
value: item
|
||||
}));
|
||||
setConfirmValues(confirmValues);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const updateColumns = () => {
|
||||
if (!db) {
|
||||
return;
|
||||
}
|
||||
let [provience, city, district] = values;
|
||||
const provienceColumn = db.province.map((code: number) => {
|
||||
return {text: db[code], value: code, disabled};
|
||||
});
|
||||
const cityColumn = city
|
||||
? db.city[provience].map((code: number) => {
|
||||
return {text: db[code], value: code, disabled};
|
||||
})
|
||||
: [];
|
||||
const districtColumn =
|
||||
city && district
|
||||
? db.district[provience][city].map((code: number) => {
|
||||
return {text: db[code], value: code, disabled};
|
||||
})
|
||||
: [];
|
||||
const columns = [
|
||||
{options: provienceColumn},
|
||||
{options: cityColumn},
|
||||
{options: districtColumn}
|
||||
];
|
||||
if (!allowDistrict || !allowCity) {
|
||||
columns.splice(2, 1);
|
||||
}
|
||||
if (!allowCity) {
|
||||
columns.splice(1, 1);
|
||||
}
|
||||
updateState({columns});
|
||||
};
|
||||
|
||||
const loadDb = () => {
|
||||
import('./CityDB').then(db => {
|
||||
updateDb({
|
||||
...db.default,
|
||||
province: db.province as any,
|
||||
city: db.city,
|
||||
district: db.district as district
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
loadDb();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
db && (props.value || isOpened) && getPropsValue();
|
||||
}, [db, isOpened, props.value]);
|
||||
|
||||
useEffect(() => {
|
||||
street && propsChange();
|
||||
}, [street]);
|
||||
|
||||
useUpdateEffect(() => {
|
||||
values.length && updateColumns();
|
||||
}, [values]);
|
||||
|
||||
const result = confirmValues
|
||||
?.filter(item => item?.value)
|
||||
?.map(item => item.text)
|
||||
.join(delimiter);
|
||||
|
||||
return (
|
||||
<div className={cx(`CityArea`)} style={style}>
|
||||
<ResultBox
|
||||
className={cx('CityArea-Input', isOpened ? 'is-active' : '')}
|
||||
allowInput={false}
|
||||
result={result}
|
||||
onResultChange={() => {}}
|
||||
onResultClick={() => setIsOpened(!isOpened)}
|
||||
placeholder={__('Select.placeholder')}
|
||||
mobileUI={mobileUI}
|
||||
disabled={disabled}
|
||||
></ResultBox>
|
||||
{allowStreet && values[0] ? (
|
||||
<input
|
||||
className={cx('CityArea-Input')}
|
||||
value={street}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
|
||||
setStreet(e.currentTarget.value)
|
||||
}
|
||||
placeholder={__('City.street')}
|
||||
disabled={disabled}
|
||||
readOnly={true}
|
||||
/>
|
||||
) : null}
|
||||
<PopUp
|
||||
className={cx(`CityArea-popup`)}
|
||||
container={popOverContainer}
|
||||
isShow={isOpened}
|
||||
showConfirm
|
||||
onConfirm={onConfirm}
|
||||
onHide={onCancel}
|
||||
>
|
||||
<Picker
|
||||
className={'CityArea-picker'}
|
||||
columns={state.columns}
|
||||
onChange={onChange as any}
|
||||
showToolbar={false}
|
||||
labelField="text"
|
||||
itemHeight={40}
|
||||
value={values}
|
||||
classnames={props.classnames}
|
||||
classPrefix={props.classPrefix}
|
||||
/>
|
||||
</PopUp>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
export default themeable(
|
||||
localeable(
|
||||
uncontrollable(CityArea, {
|
||||
value: 'onChange'
|
||||
})
|
||||
)
|
||||
);
|
||||
3950
packages/amis-ui/src/components/CityDB.ts
Normal file
3950
packages/amis-ui/src/components/CityDB.ts
Normal file
File diff suppressed because it is too large
Load Diff
124
packages/amis-ui/src/components/CodeMirror.tsx
Normal file
124
packages/amis-ui/src/components/CodeMirror.tsx
Normal file
@@ -0,0 +1,124 @@
|
||||
import React from 'react';
|
||||
// import 'codemirror/lib/codemirror.css';
|
||||
import type CodeMirror from 'codemirror';
|
||||
import {autobind, changedEffect} from 'amis-core';
|
||||
import {resizeSensor} from 'amis-core';
|
||||
|
||||
export interface CodeMirrorEditorProps {
|
||||
className?: string;
|
||||
style?: any;
|
||||
value?: string;
|
||||
readOnly?: boolean;
|
||||
onChange?: (value: string) => void;
|
||||
onFocus?: (e: any) => void;
|
||||
onBlur?: (e: any) => void;
|
||||
editorFactory?: (
|
||||
dom: HTMLElement,
|
||||
cm: typeof CodeMirror,
|
||||
props?: any
|
||||
) => CodeMirror.Editor;
|
||||
editorDidMount?: (cm: typeof CodeMirror, editor: CodeMirror.Editor) => void;
|
||||
editorWillUnMount?: (
|
||||
cm: typeof CodeMirror,
|
||||
editor: CodeMirror.Editor
|
||||
) => void;
|
||||
}
|
||||
|
||||
export class CodeMirrorEditor extends React.Component<CodeMirrorEditorProps> {
|
||||
dom = React.createRef<HTMLDivElement>();
|
||||
|
||||
editor?: CodeMirror.Editor;
|
||||
toDispose: Array<() => void> = [];
|
||||
unmounted = false;
|
||||
async componentDidMount() {
|
||||
const cm = (await import('codemirror')).default;
|
||||
// @ts-ignore
|
||||
await import('codemirror/mode/javascript/javascript');
|
||||
// @ts-ignore
|
||||
await import('codemirror/mode/htmlmixed/htmlmixed');
|
||||
await import('codemirror/addon/mode/simple');
|
||||
await import('codemirror/addon/mode/multiplex');
|
||||
await import('codemirror/addon/display/placeholder');
|
||||
if (this.unmounted) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.dom.current!.innerHTML = '';
|
||||
this.editor =
|
||||
this.props.editorFactory?.(this.dom.current!, cm, this.props) ??
|
||||
cm(this.dom.current!, {
|
||||
value: this.props.value || '',
|
||||
readOnly: this.props.readOnly ? 'nocursor' : false,
|
||||
autofocus: false
|
||||
});
|
||||
|
||||
this.props.editorDidMount?.(cm, this.editor);
|
||||
this.editor.on('change', this.handleChange);
|
||||
this.editor.on('blur', this.handleBlur);
|
||||
this.editor.on('focus', this.handleFocus);
|
||||
|
||||
this.props.value && this.setValue(this.props.value);
|
||||
|
||||
this.toDispose.push(
|
||||
resizeSensor(this.dom.current as HTMLElement, () =>
|
||||
this.editor?.refresh()
|
||||
)
|
||||
);
|
||||
// todo 以后优化这个,解决弹窗里面默认光标太小的问题
|
||||
setTimeout(() => this.editor?.refresh(), 350);
|
||||
this.toDispose.push(() => {
|
||||
this.props.editorWillUnMount?.(cm, this.editor!);
|
||||
});
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps: CodeMirrorEditorProps) {
|
||||
const props = this.props;
|
||||
|
||||
if (props.value !== prevProps.value) {
|
||||
this.editor && this.setValue(props.value);
|
||||
}
|
||||
|
||||
changedEffect(['readOnly'], prevProps, this.props, (changes: any) => {
|
||||
this.editor?.setOption('readOnly', changes.readOnly ? 'nocursor' : false);
|
||||
});
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.unmounted = true;
|
||||
this.editor?.off('change', this.handleChange);
|
||||
this.editor?.off('blur', this.handleBlur);
|
||||
this.editor?.off('focus', this.handleFocus);
|
||||
this.toDispose.forEach(fn => fn());
|
||||
this.toDispose = [];
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleChange(editor: any) {
|
||||
this.props.onChange?.(editor.getValue());
|
||||
}
|
||||
@autobind
|
||||
handleBlur(editor: any) {
|
||||
this.props.onBlur?.(editor);
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleFocus(editor: any) {
|
||||
this.props.onFocus?.(editor);
|
||||
}
|
||||
|
||||
setValue(value?: string) {
|
||||
const doc = this.editor!.getDoc();
|
||||
if (value !== doc.getValue()) {
|
||||
const cursor = doc.getCursor();
|
||||
doc.setValue(value || '');
|
||||
doc.setCursor(cursor);
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
const {className, style} = this.props;
|
||||
return <div className={className} style={style} ref={this.dom}></div>;
|
||||
}
|
||||
}
|
||||
|
||||
export default CodeMirrorEditor;
|
||||
296
packages/amis-ui/src/components/Collapse.tsx
Normal file
296
packages/amis-ui/src/components/Collapse.tsx
Normal file
@@ -0,0 +1,296 @@
|
||||
/**
|
||||
* @file Collapse
|
||||
* @description
|
||||
* @author fex
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import {ClassNamesFn, ThemeProps, themeable} from 'amis-core';
|
||||
import Transition, {
|
||||
EXITED,
|
||||
ENTERING,
|
||||
EXITING
|
||||
} from 'react-transition-group/Transition';
|
||||
import {autobind} from 'amis-core';
|
||||
import {isClickOnInput} from 'amis-core';
|
||||
import {TranslateFn} from 'amis-core';
|
||||
import {Icon} from './icons';
|
||||
|
||||
const collapseStyles: {
|
||||
[propName: string]: string;
|
||||
} = {
|
||||
[EXITED]: 'out',
|
||||
[EXITING]: 'out',
|
||||
[ENTERING]: 'in'
|
||||
};
|
||||
|
||||
export interface CollapseProps extends ThemeProps {
|
||||
id?: string;
|
||||
key?: string;
|
||||
collapseId?: string;
|
||||
propKey?: string;
|
||||
mountOnEnter?: boolean;
|
||||
unmountOnExit?: boolean;
|
||||
className?: string;
|
||||
style?: any;
|
||||
headerPosition?: 'top' | 'bottom';
|
||||
header?: React.ReactNode;
|
||||
body: any;
|
||||
bodyClassName?: string;
|
||||
disabled?: boolean;
|
||||
collapsable?: boolean;
|
||||
collapsed?: boolean;
|
||||
showArrow?: boolean;
|
||||
expandIcon?: React.ReactElement | null;
|
||||
headingClassName?: string;
|
||||
collapseHeader?: React.ReactElement | null;
|
||||
size?: 'xs' | 'sm' | 'md' | 'lg' | 'base';
|
||||
onCollapse?: (collapsed: boolean) => void;
|
||||
wrapperComponent?: any;
|
||||
headingComponent?: any;
|
||||
translate?: TranslateFn;
|
||||
propsUpdate?: boolean;
|
||||
partial?: boolean;
|
||||
children?: React.ReactNode | Array<React.ReactNode>;
|
||||
divideLine?: boolean;
|
||||
/** 当Collapse作为Form组件的子元素时,开启该属性后组件样式设置为FieldSet组件的样式,默认开启 */
|
||||
enableFieldSetStyle?: boolean;
|
||||
}
|
||||
|
||||
export interface CollapseState {
|
||||
collapsed: boolean;
|
||||
}
|
||||
|
||||
export class Collapse extends React.Component<CollapseProps, CollapseState> {
|
||||
static defaultProps: Partial<CollapseProps> = {
|
||||
mountOnEnter: false,
|
||||
unmountOnExit: false,
|
||||
headerPosition: 'top',
|
||||
wrapperComponent: 'div',
|
||||
headingComponent: 'div',
|
||||
className: '',
|
||||
headingClassName: '',
|
||||
bodyClassName: '',
|
||||
collapsable: true,
|
||||
disabled: false,
|
||||
showArrow: true,
|
||||
propsUpdate: false,
|
||||
enableFieldSetStyle: true
|
||||
};
|
||||
|
||||
state: CollapseState = {
|
||||
collapsed: false
|
||||
};
|
||||
|
||||
constructor(props: CollapseProps) {
|
||||
super(props);
|
||||
|
||||
this.toggleCollapsed = this.toggleCollapsed.bind(this);
|
||||
this.state.collapsed = props.collapsable ? !!props.collapsed : false;
|
||||
}
|
||||
|
||||
static getDerivedStateFromProps(
|
||||
nextProps: CollapseProps,
|
||||
preState: CollapseState
|
||||
) {
|
||||
if (nextProps.propsUpdate && nextProps.collapsed !== preState.collapsed) {
|
||||
return {
|
||||
collapsed: !!nextProps.collapsed
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
toggleCollapsed(e: React.MouseEvent<HTMLElement>) {
|
||||
if (isClickOnInput(e)) {
|
||||
return;
|
||||
}
|
||||
const props = this.props;
|
||||
if (props.disabled || props.collapsable === false) {
|
||||
return;
|
||||
}
|
||||
const newCollapsed = !this.state.collapsed;
|
||||
props.onCollapse?.(newCollapsed);
|
||||
this.setState({
|
||||
collapsed: newCollapsed
|
||||
});
|
||||
}
|
||||
|
||||
/** 变更组件的折叠状态 */
|
||||
@autobind
|
||||
changeCollapsedState(targetState: boolean) {
|
||||
const {disabled, collapsable} = this.props;
|
||||
const {collapsed: currentState} = this.state;
|
||||
|
||||
if (disabled || collapsable === false || currentState === targetState) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.setState(
|
||||
{
|
||||
collapsed: targetState
|
||||
},
|
||||
() => {
|
||||
this.props.onCollapse?.(targetState);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
contentDom: any;
|
||||
contentRef = (ref: any) => (this.contentDom = ref);
|
||||
|
||||
@autobind
|
||||
handleEnter(elem: HTMLElement) {
|
||||
elem.style['height'] = '';
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleEntering(elem: HTMLElement) {
|
||||
elem.style['height'] = `${elem['scrollHeight']}px`;
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleEntered(elem: HTMLElement) {
|
||||
elem.style['height'] = '';
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleExit(elem: HTMLElement) {
|
||||
let offsetHeight = elem['offsetHeight'];
|
||||
const height =
|
||||
offsetHeight +
|
||||
parseInt(getComputedStyle(elem).getPropertyValue('margin-top'), 10) +
|
||||
parseInt(getComputedStyle(elem).getPropertyValue('margin-bottom'), 10);
|
||||
elem.style['height'] = `${height}px`;
|
||||
// trigger browser reflow
|
||||
elem.offsetHeight;
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleExiting(elem: HTMLElement) {
|
||||
elem.style['height'] = '';
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
classnames: cx,
|
||||
mountOnEnter,
|
||||
unmountOnExit,
|
||||
classPrefix: ns,
|
||||
size,
|
||||
wrapperComponent: WrapperComponent,
|
||||
headingComponent: HeadingComponent,
|
||||
className,
|
||||
style,
|
||||
headingClassName,
|
||||
headerPosition,
|
||||
collapseHeader,
|
||||
header,
|
||||
body,
|
||||
bodyClassName,
|
||||
collapsable,
|
||||
translate: __,
|
||||
showArrow,
|
||||
expandIcon,
|
||||
disabled,
|
||||
children,
|
||||
mobileUI,
|
||||
enableFieldSetStyle
|
||||
} = this.props;
|
||||
|
||||
const finalHeader = this.state.collapsed
|
||||
? header
|
||||
: collapseHeader || header;
|
||||
|
||||
let dom = [
|
||||
<HeadingComponent
|
||||
key="header"
|
||||
onClick={this.toggleCollapsed}
|
||||
className={cx(
|
||||
`Collapse-header`,
|
||||
{'is-mobile': mobileUI},
|
||||
headingClassName,
|
||||
{noTitle: !finalHeader}
|
||||
)}
|
||||
>
|
||||
{showArrow && collapsable ? (
|
||||
expandIcon ? (
|
||||
React.cloneElement(expandIcon, {
|
||||
...expandIcon.props,
|
||||
className: cx(
|
||||
'Collapse-icon-tranform',
|
||||
expandIcon.props?.className
|
||||
)
|
||||
})
|
||||
) : (
|
||||
<span className={cx('Collapse-arrow-wrap')}>
|
||||
<Icon
|
||||
icon="right-arrow-bold"
|
||||
className={cx('Collapse-arrow', 'icon')}
|
||||
classNameProp={cx('Collapse-arrow')}
|
||||
iconContent="Collapse-arrow"
|
||||
/>
|
||||
</span>
|
||||
)
|
||||
) : (
|
||||
''
|
||||
)}
|
||||
{finalHeader}
|
||||
</HeadingComponent>,
|
||||
<Transition
|
||||
key="body"
|
||||
mountOnEnter={mountOnEnter}
|
||||
unmountOnExit={unmountOnExit}
|
||||
in={!this.state.collapsed}
|
||||
timeout={300}
|
||||
onEnter={this.handleEnter}
|
||||
onEntering={this.handleEntering}
|
||||
onEntered={this.handleEntered}
|
||||
onExit={this.handleExit}
|
||||
onExiting={this.handleExiting}
|
||||
>
|
||||
{(status: string) => {
|
||||
if (status === ENTERING) {
|
||||
this.contentDom.offsetWidth;
|
||||
}
|
||||
return (
|
||||
<div
|
||||
className={cx('Collapse-contentWrapper', collapseStyles[status])}
|
||||
ref={this.contentRef}
|
||||
>
|
||||
<div className={cx('Collapse-body', bodyClassName)}>
|
||||
<div className={cx('Collapse-content')}>{body || children}</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
</Transition>
|
||||
];
|
||||
|
||||
if (headerPosition === 'bottom') {
|
||||
dom.reverse();
|
||||
}
|
||||
|
||||
return (
|
||||
<WrapperComponent
|
||||
className={cx(
|
||||
`Collapse`,
|
||||
{
|
||||
'is-mobile': mobileUI,
|
||||
'is-active': !this.state.collapsed,
|
||||
[`Collapse--${size}`]: size,
|
||||
'Collapse--disabled': disabled,
|
||||
'Collapse--title-bottom': headerPosition === 'bottom',
|
||||
'Collapse-fieldset--disabled': enableFieldSetStyle === false
|
||||
},
|
||||
className
|
||||
)}
|
||||
style={style}
|
||||
>
|
||||
{dom}
|
||||
</WrapperComponent>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(Collapse);
|
||||
172
packages/amis-ui/src/components/CollapseGroup.tsx
Normal file
172
packages/amis-ui/src/components/CollapseGroup.tsx
Normal file
@@ -0,0 +1,172 @@
|
||||
/**
|
||||
* @file CollapseGroup
|
||||
* @description 折叠面板group
|
||||
* @author hongyang03
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
|
||||
// @todo 丰富这个
|
||||
export interface CollapseItem {
|
||||
[propName: string]: any;
|
||||
}
|
||||
|
||||
import {ClassNamesFn, themeable, autobind} from 'amis-core';
|
||||
import type {SchemaNode, ThemeProps} from 'amis-core';
|
||||
import isEqual from 'lodash/isEqual';
|
||||
|
||||
export interface CollapseGroupProps extends ThemeProps {
|
||||
defaultActiveKey?: Array<string | number | never> | string | number;
|
||||
accordion?: boolean;
|
||||
expandIcon?: SchemaNode;
|
||||
expandIconPosition?: 'left' | 'right';
|
||||
body?: Array<React.ReactElement>;
|
||||
className?: string;
|
||||
style?: any;
|
||||
children?: React.ReactNode | Array<React.ReactNode>;
|
||||
onCollapseChange?: (
|
||||
activeKeys: Array<string | number>,
|
||||
collapseId: string | number,
|
||||
collapsed: boolean
|
||||
) => void;
|
||||
}
|
||||
|
||||
export interface CollapseGroupState {
|
||||
activeKeys: Array<string | number | never>;
|
||||
}
|
||||
|
||||
class CollapseGroup extends React.Component<
|
||||
CollapseGroupProps,
|
||||
CollapseGroupState
|
||||
> {
|
||||
static defaultProps: Partial<CollapseGroupProps> = {
|
||||
className: '',
|
||||
accordion: false,
|
||||
expandIconPosition: 'left'
|
||||
};
|
||||
|
||||
constructor(props: CollapseGroupProps) {
|
||||
super(props);
|
||||
// 传入的activeKey会被自动转换为defaultActiveKey
|
||||
this.updateActiveKey(props.defaultActiveKey, true);
|
||||
}
|
||||
|
||||
UNSAFE_componentWillReceiveProps(nextProps: CollapseGroupProps) {
|
||||
const props = this.props;
|
||||
|
||||
if (!isEqual(props.defaultActiveKey, nextProps.defaultActiveKey)) {
|
||||
this.updateActiveKey(nextProps.defaultActiveKey);
|
||||
}
|
||||
}
|
||||
|
||||
@autobind
|
||||
updateActiveKey(propsActiveKey: any, isInit?: boolean) {
|
||||
const props = this.props;
|
||||
let curActiveKey = propsActiveKey;
|
||||
|
||||
if (!Array.isArray(curActiveKey)) {
|
||||
curActiveKey = curActiveKey ? [curActiveKey] : [];
|
||||
}
|
||||
if (props.accordion) {
|
||||
// 手风琴模式下只展开第一个元素
|
||||
curActiveKey = curActiveKey.length ? [curActiveKey[0]] : [];
|
||||
}
|
||||
|
||||
if (isInit) {
|
||||
this.state = {
|
||||
activeKeys: curActiveKey.map((key: number | string) => String(key))
|
||||
};
|
||||
} else {
|
||||
this.setState({
|
||||
activeKeys: curActiveKey.map((key: number | string) => String(key))
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
collapseChange(collapseId: string, collapsed: boolean) {
|
||||
let activeKeys = this.state.activeKeys.concat();
|
||||
if (collapsed) {
|
||||
// 设置成折叠状态
|
||||
if (this.props.accordion) {
|
||||
activeKeys = [];
|
||||
} else {
|
||||
const activeKeyIndex = activeKeys.indexOf(collapseId);
|
||||
if (activeKeyIndex !== -1) {
|
||||
activeKeys.splice(activeKeyIndex, 1); // 剔除开启状态
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 展开折叠器
|
||||
if (this.props.accordion) {
|
||||
activeKeys = [collapseId as string];
|
||||
} else if (activeKeys.indexOf(collapseId) === -1) {
|
||||
activeKeys.push(collapseId as string);
|
||||
}
|
||||
}
|
||||
this.props.onCollapseChange?.(
|
||||
activeKeys,
|
||||
collapseId,
|
||||
activeKeys.indexOf(collapseId) === -1
|
||||
);
|
||||
this.setState({
|
||||
activeKeys
|
||||
});
|
||||
}
|
||||
|
||||
getItems = (children: React.ReactNode) => {
|
||||
if (!Array.isArray(children)) {
|
||||
return children;
|
||||
}
|
||||
|
||||
return children.map((child: React.ReactElement, index: number) => {
|
||||
let props = child.props;
|
||||
|
||||
const collapseId = props.propKey || String(index);
|
||||
// 判断是否折叠
|
||||
const collapsed = this.state.activeKeys.indexOf(collapseId) === -1;
|
||||
|
||||
return React.cloneElement(child as any, {
|
||||
...props,
|
||||
key: collapseId,
|
||||
collapseId,
|
||||
collapsed,
|
||||
expandIcon: this.props.expandIcon,
|
||||
propsUpdate: true,
|
||||
onCollapse: (collapsed: boolean) =>
|
||||
this.collapseChange(collapseId, collapsed)
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
render() {
|
||||
const {
|
||||
classnames: cx,
|
||||
className,
|
||||
style,
|
||||
expandIconPosition,
|
||||
children,
|
||||
mobileUI
|
||||
} = this.props;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx(
|
||||
`CollapseGroup`,
|
||||
{
|
||||
'icon-position-right': expandIconPosition === 'right'
|
||||
},
|
||||
{
|
||||
'is-mobile': mobileUI
|
||||
},
|
||||
className
|
||||
)}
|
||||
style={style}
|
||||
data-role="container"
|
||||
>
|
||||
{this.getItems(children)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(CollapseGroup);
|
||||
452
packages/amis-ui/src/components/ColorPicker.tsx
Normal file
452
packages/amis-ui/src/components/ColorPicker.tsx
Normal file
@@ -0,0 +1,452 @@
|
||||
/**
|
||||
* @file ColorPicker
|
||||
* @description 颜色选择器组件
|
||||
* @author fex
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import {findDOMNode} from 'react-dom';
|
||||
import {SketchPicker, GithubPicker, ColorResult} from 'react-color';
|
||||
import {Icon} from './icons';
|
||||
import {Overlay} from 'amis-core';
|
||||
import {uncontrollable} from 'amis-core';
|
||||
import {PopOver} from 'amis-core';
|
||||
import PopUp from './PopUp';
|
||||
import {ClassNamesFn, themeable, ThemeProps} from 'amis-core';
|
||||
import {autobind, isObject} from 'amis-core';
|
||||
import {localeable, LocaleProps} from 'amis-core';
|
||||
|
||||
export type PresetColor = {color: string; title: string} | string;
|
||||
|
||||
export interface ColorProps extends LocaleProps, ThemeProps {
|
||||
placeholder?: string;
|
||||
format: string;
|
||||
// closeOnSelect:boolean;
|
||||
clearable: boolean;
|
||||
className?: string;
|
||||
popoverClassName?: string;
|
||||
disabled?: boolean;
|
||||
popOverContainer?: any;
|
||||
popOverContainerSelector?: string;
|
||||
placement?: string;
|
||||
value?: any;
|
||||
onChange: (value: any) => void;
|
||||
presetColors?: PresetColor[];
|
||||
resetValue?: string;
|
||||
allowCustomColor?: boolean;
|
||||
}
|
||||
|
||||
export interface ColorControlState {
|
||||
isOpened: boolean;
|
||||
isFocused: boolean;
|
||||
inputValue: string;
|
||||
tempValue: string;
|
||||
}
|
||||
|
||||
export class ColorControl extends React.PureComponent<
|
||||
ColorProps,
|
||||
ColorControlState
|
||||
> {
|
||||
static defaultProps = {
|
||||
format: 'hex',
|
||||
clearable: true,
|
||||
placeholder: 'ColorPicker.placeholder',
|
||||
allowCustomColor: true
|
||||
// closeOnSelect: true
|
||||
};
|
||||
state = {
|
||||
isOpened: false,
|
||||
isFocused: false,
|
||||
inputValue: this.props.value || '',
|
||||
tempValue: this.props.value || ''
|
||||
};
|
||||
popover: any;
|
||||
closeTimer: number;
|
||||
preview: React.RefObject<HTMLElement>;
|
||||
input: React.RefObject<HTMLInputElement>;
|
||||
constructor(props: ColorProps) {
|
||||
super(props);
|
||||
|
||||
this.open = this.open.bind(this);
|
||||
this.close = this.close.bind(this);
|
||||
this.focus = this.focus.bind(this);
|
||||
this.blur = this.blur.bind(this);
|
||||
this.handleChange = this.handleChange.bind(this);
|
||||
this.handleTempChange = this.handleTempChange.bind(this);
|
||||
this.handleConfirm = this.handleConfirm.bind(this);
|
||||
this.handleFocus = this.handleFocus.bind(this);
|
||||
this.handleBlur = this.handleBlur.bind(this);
|
||||
this.clearValue = this.clearValue.bind(this);
|
||||
this.handleInputChange = this.handleInputChange.bind(this);
|
||||
this.handleClick = this.handleClick.bind(this);
|
||||
this.preview = React.createRef();
|
||||
this.input = React.createRef();
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps: ColorProps) {
|
||||
const props = this.props;
|
||||
|
||||
if (prevProps.value !== props.value) {
|
||||
this.setState({
|
||||
inputValue: props.value || ''
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
handleFocus() {
|
||||
this.setState({
|
||||
isFocused: true
|
||||
});
|
||||
}
|
||||
|
||||
handleBlur() {
|
||||
this.setState({
|
||||
isFocused: false,
|
||||
inputValue: this.props.value
|
||||
});
|
||||
}
|
||||
|
||||
focus() {
|
||||
this.input.current && this.input.current.focus();
|
||||
}
|
||||
|
||||
blur() {
|
||||
this.input.current && this.input.current.blur();
|
||||
}
|
||||
|
||||
open(fn?: () => void) {
|
||||
if (this.props.disabled) {
|
||||
return;
|
||||
}
|
||||
this.setState(
|
||||
{
|
||||
isOpened: true
|
||||
},
|
||||
fn
|
||||
);
|
||||
}
|
||||
|
||||
close() {
|
||||
this.setState({
|
||||
isOpened: false
|
||||
});
|
||||
}
|
||||
|
||||
clearValue() {
|
||||
const {onChange, resetValue} = this.props;
|
||||
onChange(resetValue || '');
|
||||
}
|
||||
|
||||
handleClick() {
|
||||
this.state.isOpened ? this.close() : this.open(this.focus);
|
||||
}
|
||||
|
||||
handleInputChange(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
if (!this.props.allowCustomColor) {
|
||||
return;
|
||||
}
|
||||
|
||||
const onChange = this.props.onChange;
|
||||
|
||||
this.setState(
|
||||
{
|
||||
inputValue: e.currentTarget.value
|
||||
},
|
||||
() => {
|
||||
let isValidated = this.validateColor(this.state.inputValue);
|
||||
if (isValidated) {
|
||||
onChange(this.state.inputValue);
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@autobind
|
||||
validateColor(value: string) {
|
||||
if (value === '') {
|
||||
return false;
|
||||
}
|
||||
if (value === 'inherit') {
|
||||
return false;
|
||||
}
|
||||
if (value === 'transparent') {
|
||||
return false;
|
||||
}
|
||||
|
||||
let image = document.createElement('img');
|
||||
image.style.color = 'rgb(0, 0, 0)';
|
||||
image.style.color = value;
|
||||
if (image.style.color !== 'rgb(0, 0, 0)') {
|
||||
return true;
|
||||
}
|
||||
image.style.color = 'rgb(255, 255, 255)';
|
||||
image.style.color = value;
|
||||
return image.style.color !== 'rgb(255, 255, 255)';
|
||||
}
|
||||
|
||||
handleChange(color: ColorResult) {
|
||||
const {
|
||||
onChange,
|
||||
format
|
||||
// closeOnSelect
|
||||
} = this.props;
|
||||
|
||||
if (format === 'rgba') {
|
||||
onChange(
|
||||
`rgba(${color.rgb.r}, ${color.rgb.g}, ${color.rgb.b}, ${color.rgb.a})`
|
||||
);
|
||||
} else if (format === 'rgb') {
|
||||
onChange(`rgb(${color.rgb.r}, ${color.rgb.g}, ${color.rgb.b})`);
|
||||
} else if (format === 'hexa') {
|
||||
onChange(
|
||||
this.rgbaToHex(color.rgb.r, color.rgb.g, color.rgb.b, color.rgb.a)
|
||||
);
|
||||
} else if (format === 'hsl') {
|
||||
onChange(
|
||||
`hsl(${Math.round(color.hsl.h)}, ${Math.round(
|
||||
color.hsl.s * 100
|
||||
)}%, ${Math.round(color.hsl.l * 100)}%)`
|
||||
);
|
||||
} else {
|
||||
onChange(color.hex);
|
||||
}
|
||||
|
||||
// closeOnSelect && this.close();
|
||||
}
|
||||
|
||||
handleTempChange(color: ColorResult) {
|
||||
let {tempValue} = this.state;
|
||||
const {format} = this.props;
|
||||
|
||||
if (format === 'rgba') {
|
||||
tempValue = `rgba(${color.rgb.r}, ${color.rgb.g}, ${color.rgb.b}, ${color.rgb.a})`;
|
||||
} else if (format === 'rgb') {
|
||||
tempValue = `rgb(${color.rgb.r}, ${color.rgb.g}, ${color.rgb.b})`;
|
||||
} else if (format === 'hexa') {
|
||||
tempValue = this.rgbaToHex(
|
||||
color.rgb.r,
|
||||
color.rgb.g,
|
||||
color.rgb.b,
|
||||
color.rgb.a
|
||||
);
|
||||
} else if (format === 'hsl') {
|
||||
tempValue = `hsl(${Math.round(color.hsl.h)}, ${Math.round(
|
||||
color.hsl.s * 100
|
||||
)}%, ${Math.round(color.hsl.l * 100)}%)`;
|
||||
} else {
|
||||
tempValue = color.hex;
|
||||
}
|
||||
this.setState({tempValue});
|
||||
}
|
||||
|
||||
handleConfirm() {
|
||||
const {onChange} = this.props;
|
||||
const {tempValue} = this.state;
|
||||
onChange(tempValue);
|
||||
this.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an RGBA color to an 8-digit hex color.
|
||||
*
|
||||
* @param r - Red component (0-255)
|
||||
* @param g - Green component (0-255)
|
||||
* @param b - Blue component (0-255)
|
||||
* @param a - Alpha component (1-100)
|
||||
* @returns The hex color string in the format #RRGGBBAA
|
||||
*/
|
||||
rgbaToHex(r: number, g: number, b: number, a: number | undefined): string {
|
||||
if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) {
|
||||
return `#00000000`;
|
||||
}
|
||||
if (typeof a === 'undefined' || a > 1) {
|
||||
a = 1;
|
||||
}
|
||||
if (a < 0.01) {
|
||||
a = 0;
|
||||
}
|
||||
|
||||
const toHex = (n: number) => n.toString(16).padStart(2, '0').toUpperCase();
|
||||
|
||||
const alphaHex = toHex(Math.round(a * 255));
|
||||
const redHex = toHex(r);
|
||||
const greenHex = toHex(g);
|
||||
const blueHex = toHex(b);
|
||||
|
||||
return `#${redHex}${greenHex}${blueHex}${alphaHex}`;
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
classPrefix: ns,
|
||||
className,
|
||||
popoverClassName,
|
||||
value,
|
||||
placeholder,
|
||||
disabled,
|
||||
popOverContainer,
|
||||
popOverContainerSelector,
|
||||
format,
|
||||
clearable,
|
||||
placement,
|
||||
classnames: cx,
|
||||
presetColors,
|
||||
allowCustomColor,
|
||||
mobileUI
|
||||
} = this.props;
|
||||
|
||||
const __ = this.props.translate;
|
||||
const isOpened = this.state.isOpened;
|
||||
const isFocused = this.state.isFocused;
|
||||
const tempValue = this.state.tempValue;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx(
|
||||
`ColorPicker`,
|
||||
{
|
||||
'is-disabled': disabled,
|
||||
'is-focused': isFocused,
|
||||
'is-opened': isOpened
|
||||
},
|
||||
className
|
||||
)}
|
||||
>
|
||||
<span onClick={this.handleClick} className={cx('ColorPicker-preview')}>
|
||||
<i
|
||||
ref={this.preview}
|
||||
className={`${ns}ColorPicker-previewIcon`}
|
||||
style={{background: this.state.inputValue || '#ccc'}}
|
||||
/>
|
||||
</span>
|
||||
|
||||
<input
|
||||
ref={this.input}
|
||||
type="text"
|
||||
autoComplete="off"
|
||||
size={10}
|
||||
className={cx('ColorPicker-input')}
|
||||
value={this.state.inputValue || ''}
|
||||
placeholder={__(placeholder)}
|
||||
disabled={disabled}
|
||||
onChange={this.handleInputChange}
|
||||
onFocus={this.handleFocus}
|
||||
onBlur={this.handleBlur}
|
||||
onClick={this.handleClick}
|
||||
readOnly={mobileUI}
|
||||
/>
|
||||
|
||||
{clearable && !disabled && value ? (
|
||||
<a onClick={this.clearValue} className={cx('ColorPicker-clear')}>
|
||||
<Icon icon="input-clear" className="icon" />
|
||||
</a>
|
||||
) : null}
|
||||
|
||||
<span className={cx('ColorPicker-arrow')}>
|
||||
<Icon
|
||||
icon="right-arrow-bold"
|
||||
className="icon"
|
||||
onClick={this.handleClick}
|
||||
/>
|
||||
</span>
|
||||
|
||||
{!mobileUI && isOpened ? (
|
||||
<Overlay
|
||||
placement={placement || 'auto'}
|
||||
target={() => findDOMNode(this)}
|
||||
onHide={this.close}
|
||||
container={popOverContainer || (() => findDOMNode(this))}
|
||||
containerSelector={popOverContainerSelector}
|
||||
rootClose={false}
|
||||
show
|
||||
>
|
||||
<PopOver
|
||||
classPrefix={ns}
|
||||
className={cx('ColorPicker-popover', popoverClassName)}
|
||||
onHide={this.close}
|
||||
overlay
|
||||
>
|
||||
{allowCustomColor ? (
|
||||
<SketchPicker
|
||||
styles={{}}
|
||||
disableAlpha={!!~['rgb', 'hex'].indexOf(format as string)}
|
||||
color={value}
|
||||
presetColors={presetColors}
|
||||
onChangeComplete={this.handleChange}
|
||||
/>
|
||||
) : (
|
||||
<GithubPicker
|
||||
color={value}
|
||||
colors={
|
||||
Array.isArray(presetColors)
|
||||
? (presetColors
|
||||
.filter(
|
||||
item => typeof item === 'string' || isObject(item)
|
||||
)
|
||||
.map(item =>
|
||||
typeof item === 'string'
|
||||
? item
|
||||
: isObject(item)
|
||||
? item?.color
|
||||
: item
|
||||
) as string[])
|
||||
: undefined
|
||||
}
|
||||
onChangeComplete={this.handleChange}
|
||||
/>
|
||||
)}
|
||||
</PopOver>
|
||||
</Overlay>
|
||||
) : null}
|
||||
{mobileUI && (
|
||||
<PopUp
|
||||
className={cx(`${ns}ColorPicker-popup`)}
|
||||
container={popOverContainer}
|
||||
isShow={isOpened}
|
||||
onHide={this.handleClick}
|
||||
showConfirm
|
||||
onConfirm={this.handleConfirm}
|
||||
>
|
||||
{allowCustomColor ? (
|
||||
<SketchPicker
|
||||
styles={{}}
|
||||
disableAlpha={!!~['rgb', 'hex'].indexOf(format as string)}
|
||||
color={tempValue}
|
||||
presetColors={presetColors}
|
||||
onChangeComplete={this.handleTempChange}
|
||||
/>
|
||||
) : (
|
||||
<GithubPicker
|
||||
color={tempValue}
|
||||
colors={
|
||||
Array.isArray(presetColors)
|
||||
? (presetColors
|
||||
.filter(
|
||||
item => typeof item === 'string' || isObject(item)
|
||||
)
|
||||
.map(item =>
|
||||
typeof item === 'string'
|
||||
? item
|
||||
: isObject(item)
|
||||
? item?.color
|
||||
: item
|
||||
) as string[])
|
||||
: undefined
|
||||
}
|
||||
onChangeComplete={this.handleTempChange}
|
||||
/>
|
||||
)}
|
||||
</PopUp>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(
|
||||
localeable(
|
||||
uncontrollable(ColorControl, {
|
||||
value: 'onChange'
|
||||
})
|
||||
)
|
||||
);
|
||||
372
packages/amis-ui/src/components/Combo.tsx
Normal file
372
packages/amis-ui/src/components/Combo.tsx
Normal file
@@ -0,0 +1,372 @@
|
||||
/**
|
||||
* 纯组件版本的 combo 实现
|
||||
*
|
||||
* 只能用在 <Form> 里面。
|
||||
*
|
||||
* 示例:
|
||||
*
|
||||
* <Form
|
||||
* defaultValues={{a: 1, b: 2, arr: [{a: 1, b: 2}]}}
|
||||
* onSubmit={values => console.log(values)}
|
||||
* >
|
||||
* {({control, getValues, setValue, handleSubmit}) => (
|
||||
* <>
|
||||
* <Combo
|
||||
* name="arr"
|
||||
* control={control}
|
||||
* label="Combo"
|
||||
* mode="horizontal"
|
||||
* itemRender={({
|
||||
* control,
|
||||
* getValues,
|
||||
* setValue,
|
||||
* handleSubmit
|
||||
* }) => (
|
||||
* <>
|
||||
* <Controller
|
||||
* name="a"
|
||||
* label="A"
|
||||
* mode="horizontal"
|
||||
* horizontal={{justify: true}}
|
||||
* control={control}
|
||||
* rules={{maxLength: 20}}
|
||||
* render={({field, fieldState}) => (
|
||||
* <InputBox
|
||||
* {...field}
|
||||
* hasError={fieldState.error}
|
||||
* disabled={false}
|
||||
* />
|
||||
* )}
|
||||
* />
|
||||
*
|
||||
* <Controller
|
||||
* name="b"
|
||||
* control={control}
|
||||
* rules={{maxLength: 20}}
|
||||
* render={({field, fieldState}) => (
|
||||
* <InputBox
|
||||
* {...field}
|
||||
* hasError={fieldState.error}
|
||||
* disabled={false}
|
||||
* />
|
||||
* )}
|
||||
* />
|
||||
* </>
|
||||
* )}
|
||||
* />
|
||||
* </>
|
||||
* )}
|
||||
* </Form>
|
||||
*/
|
||||
|
||||
import {
|
||||
ClassNamesFn,
|
||||
localeable,
|
||||
LocaleProps,
|
||||
themeable,
|
||||
ThemeProps,
|
||||
TranslateFn
|
||||
} from 'amis-core';
|
||||
import React from 'react';
|
||||
import {
|
||||
Control,
|
||||
RegisterOptions,
|
||||
useFieldArray,
|
||||
UseFieldArrayProps,
|
||||
useFormContext,
|
||||
UseFormReturn,
|
||||
useFormState
|
||||
} from 'react-hook-form';
|
||||
import useSubForm from '../hooks/use-sub-form';
|
||||
import Button from './Button';
|
||||
import FormField, {FormFieldProps} from './FormField';
|
||||
import {Icon} from './icons';
|
||||
|
||||
export interface ComboProps<T = any>
|
||||
extends ThemeProps,
|
||||
LocaleProps,
|
||||
Omit<FormFieldProps, 'children' | 'errors' | 'hasError' | 'className'>,
|
||||
UseFieldArrayProps {
|
||||
itemRender: (methods: UseFormReturn, index: number) => JSX.Element | null;
|
||||
control: Control<any>;
|
||||
fieldClassName?: string;
|
||||
|
||||
rules?: Omit<
|
||||
RegisterOptions,
|
||||
'valueAsNumber' | 'valueAsDate' | 'setValueAs' | 'disabled'
|
||||
> & {
|
||||
[propName: string]: any;
|
||||
};
|
||||
|
||||
/**
|
||||
* 要不要包裹 label 之类的
|
||||
*/
|
||||
wrap?: boolean;
|
||||
|
||||
/**
|
||||
* 是否多行模式
|
||||
*/
|
||||
multiLine?: boolean;
|
||||
|
||||
itemsWrapperClassName?: string;
|
||||
itemClassName?: string;
|
||||
|
||||
scaffold?: Record<string, any>;
|
||||
addButtonClassName?: string;
|
||||
addButtonText?: string;
|
||||
addButtonLevel?: string;
|
||||
addButtonSize?: string;
|
||||
addable?: boolean;
|
||||
// draggable?: boolean;
|
||||
// draggableTip?: string;
|
||||
maxLength?: number;
|
||||
minLength?: number;
|
||||
removable?: boolean;
|
||||
}
|
||||
|
||||
export function Combo({
|
||||
control,
|
||||
name,
|
||||
wrap,
|
||||
mode,
|
||||
label,
|
||||
labelAlign,
|
||||
labelClassName,
|
||||
description,
|
||||
fieldClassName,
|
||||
className,
|
||||
style,
|
||||
multiLine,
|
||||
itemsWrapperClassName,
|
||||
itemClassName,
|
||||
addButtonClassName,
|
||||
addButtonLevel,
|
||||
addButtonSize,
|
||||
itemRender,
|
||||
translate: __,
|
||||
classnames: cx,
|
||||
addable,
|
||||
scaffold,
|
||||
addButtonText,
|
||||
removable,
|
||||
rules,
|
||||
isRequired,
|
||||
minLength,
|
||||
maxLength
|
||||
}: ComboProps) {
|
||||
const subForms = React.useRef<Record<any, UseFormReturn>>({});
|
||||
const subFormRef = React.useCallback(
|
||||
(subform: UseFormReturn | null, index: number) => {
|
||||
if (subform) {
|
||||
subForms.current[index] = subform;
|
||||
} else {
|
||||
delete subForms.current[index];
|
||||
}
|
||||
},
|
||||
[subForms]
|
||||
);
|
||||
let finalRules: any = {...rules};
|
||||
|
||||
if (isRequired) {
|
||||
finalRules.required = true;
|
||||
}
|
||||
|
||||
if (minLength) {
|
||||
finalRules.minLength = minLength;
|
||||
}
|
||||
|
||||
if (maxLength) {
|
||||
finalRules.maxLength = maxLength;
|
||||
}
|
||||
|
||||
finalRules.validate = React.useCallback(
|
||||
async (items: Array<any>) => {
|
||||
const map = subForms.current;
|
||||
|
||||
if (typeof rules?.validate === 'function') {
|
||||
const result = await rules.validate(items);
|
||||
if (result) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
for (let key of Object.keys(map)) {
|
||||
const valid = await (function (methods) {
|
||||
return new Promise<boolean>(resolve => {
|
||||
methods.handleSubmit(
|
||||
() => resolve(true),
|
||||
() => resolve(false)
|
||||
)();
|
||||
});
|
||||
})(map[key]);
|
||||
|
||||
if (!valid) {
|
||||
return __('validateFailed');
|
||||
}
|
||||
}
|
||||
},
|
||||
[subForms]
|
||||
);
|
||||
const {fields, append, update, remove} = useFieldArray({
|
||||
control,
|
||||
name: name,
|
||||
shouldUnregister: true,
|
||||
rules: finalRules
|
||||
});
|
||||
|
||||
const {trigger, setValue} = useFormContext();
|
||||
|
||||
// useFieldArray 的 update 会更新行 id,导致重新渲染
|
||||
// 正在编辑中的元素失去焦点,所以自己写一个
|
||||
const lightUpdate = React.useCallback(
|
||||
(index: number, value: any) => {
|
||||
// const arr = control._getFieldArray(name);
|
||||
// arr[index] = {...value};
|
||||
// control._updateFieldArray(name, arr);
|
||||
// trigger(name);
|
||||
// control._subjects.watch.next({});
|
||||
setValue(`${name}.${index}`, value);
|
||||
},
|
||||
[control]
|
||||
);
|
||||
|
||||
function renderBody() {
|
||||
return (
|
||||
<div
|
||||
className={cx(
|
||||
`Combo Combo--multi`,
|
||||
className,
|
||||
multiLine ? `Combo--ver` : `Combo--hor`
|
||||
)}
|
||||
// style={style}
|
||||
>
|
||||
<div className={cx(`Combo-items`, itemsWrapperClassName)}>
|
||||
{fields.map((field, index) => (
|
||||
<div key={field.id} className={cx(`Combo-item`, itemClassName)}>
|
||||
<ComboItem
|
||||
control={control}
|
||||
update={lightUpdate}
|
||||
index={index}
|
||||
value={field}
|
||||
itemRender={itemRender}
|
||||
translate={__}
|
||||
classnames={cx}
|
||||
formRef={subFormRef}
|
||||
/>
|
||||
<a
|
||||
onClick={() => remove(index)}
|
||||
key="delete"
|
||||
className={cx(
|
||||
`Combo-delBtn ${
|
||||
removable === false ||
|
||||
(minLength && fields.length <= minLength)
|
||||
? 'is-disabled'
|
||||
: ''
|
||||
}`
|
||||
)}
|
||||
data-tooltip={__('delete')}
|
||||
data-position="bottom"
|
||||
>
|
||||
<Icon icon="status-close" className="icon" />
|
||||
</a>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{addable !== false && (!maxLength || fields.length < maxLength) ? (
|
||||
<div className={cx(`Combo-toolbar`)}>
|
||||
<Button
|
||||
className={cx(`Combo-addBtn`, addButtonClassName)}
|
||||
level={addButtonLevel ?? 'primary'}
|
||||
onClick={() => append({...scaffold})}
|
||||
size={(addButtonSize as any) ?? 'sm'}
|
||||
>
|
||||
<Icon icon="plus" className="icon" />
|
||||
<span>{__(addButtonText || 'add')}</span>
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const {errors} = useFormState({
|
||||
control
|
||||
});
|
||||
|
||||
return wrap === false ? (
|
||||
renderBody()
|
||||
) : (
|
||||
<FormField
|
||||
className={fieldClassName}
|
||||
style={style}
|
||||
label={label}
|
||||
labelAlign={labelAlign}
|
||||
labelClassName={labelClassName}
|
||||
description={description}
|
||||
mode={mode}
|
||||
isRequired={isRequired}
|
||||
hasError={!!errors[name]?.message}
|
||||
errors={errors[name]?.message as any}
|
||||
>
|
||||
{renderBody()}
|
||||
</FormField>
|
||||
);
|
||||
}
|
||||
|
||||
export interface ComboItemProps {
|
||||
value: any;
|
||||
control: Control<any>;
|
||||
itemRender: (methods: UseFormReturn, index: number) => JSX.Element | null;
|
||||
update: (index: number, data: Record<string, any>) => void;
|
||||
index: number;
|
||||
translate: TranslateFn;
|
||||
classnames: ClassNamesFn;
|
||||
formRef: (form: UseFormReturn | null, index: number) => void;
|
||||
}
|
||||
|
||||
export function ComboItem({
|
||||
value,
|
||||
itemRender,
|
||||
index,
|
||||
translate,
|
||||
update,
|
||||
classnames: cx,
|
||||
formRef
|
||||
}: ComboItemProps) {
|
||||
const indexRef = React.useRef(index);
|
||||
React.useEffect(() => {
|
||||
indexRef.current = index;
|
||||
}, [index]);
|
||||
const methods = useSubForm(value, translate, (data: any) =>
|
||||
update(indexRef.current!, data)
|
||||
);
|
||||
React.useEffect(() => {
|
||||
formRef?.(methods, index);
|
||||
return () => {
|
||||
formRef?.(null, index);
|
||||
};
|
||||
}, [methods]);
|
||||
|
||||
let child: any = itemRender(methods, index);
|
||||
if (child?.type === React.Fragment) {
|
||||
child = child.props.children;
|
||||
}
|
||||
if (Array.isArray(child)) {
|
||||
child = (
|
||||
<div className={cx('Form-row')}>
|
||||
{child.map((child, index) => (
|
||||
<div
|
||||
className={cx('Form-col', child?.props.columnClassName)}
|
||||
key={child.key || index}
|
||||
>
|
||||
{child}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return <div className={cx('Combo-itemInner')}>{child}</div>;
|
||||
}
|
||||
|
||||
export default themeable(localeable(Combo));
|
||||
3
packages/amis-ui/src/components/ConditionBuilder.tsx
Normal file
3
packages/amis-ui/src/components/ConditionBuilder.tsx
Normal file
@@ -0,0 +1,3 @@
|
||||
import ConditionBuilder from './condition-builder/index';
|
||||
|
||||
export default ConditionBuilder;
|
||||
251
packages/amis-ui/src/components/ConfirmBox.tsx
Normal file
251
packages/amis-ui/src/components/ConfirmBox.tsx
Normal file
@@ -0,0 +1,251 @@
|
||||
import React from 'react';
|
||||
import Modal from './Modal';
|
||||
import Button from './Button';
|
||||
import Drawer from './Drawer';
|
||||
import {localeable, LocaleProps, themeable, ThemeProps} from 'amis-core';
|
||||
import Spinner from './Spinner';
|
||||
import PopUp from './PopUp';
|
||||
import {findDOMNode} from 'react-dom';
|
||||
import type {TestIdBuilder} from 'amis-core';
|
||||
|
||||
export interface ConfirmBoxProps extends LocaleProps, ThemeProps {
|
||||
show?: boolean;
|
||||
disabled?: boolean;
|
||||
closeOnEsc?: boolean;
|
||||
beforeConfirm?: (bodyRef?: any) => any;
|
||||
onConfirm?: (data: any) => void;
|
||||
onCancel?: () => void;
|
||||
title?: string;
|
||||
showTitle?: boolean;
|
||||
showFooter?: boolean;
|
||||
children?:
|
||||
| JSX.Element
|
||||
| ((methods: {
|
||||
loading?: boolean;
|
||||
bodyRef: React.MutableRefObject<
|
||||
| {
|
||||
submit: () => Promise<Record<string, any>>;
|
||||
}
|
||||
| undefined
|
||||
>;
|
||||
popOverContainer: () => HTMLElement | null | undefined;
|
||||
onConfirm: () => void;
|
||||
}) => JSX.Element);
|
||||
popOverContainer?: any;
|
||||
size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl' | 'full';
|
||||
position?: 'top' | 'right' | 'bottom' | 'left';
|
||||
resizable?: boolean;
|
||||
type: 'dialog' | 'drawer';
|
||||
className?: string;
|
||||
headerClassName?: string;
|
||||
bodyClassName?: string;
|
||||
footerClassName?: string;
|
||||
testIdBuilder?: TestIdBuilder;
|
||||
onExited?: () => void;
|
||||
onEntered?: () => void;
|
||||
}
|
||||
|
||||
export function ConfirmBox({
|
||||
type,
|
||||
size,
|
||||
closeOnEsc,
|
||||
show,
|
||||
onCancel,
|
||||
title,
|
||||
showTitle,
|
||||
headerClassName,
|
||||
translate: __,
|
||||
children,
|
||||
showFooter,
|
||||
onConfirm,
|
||||
beforeConfirm,
|
||||
popOverContainer,
|
||||
position,
|
||||
resizable,
|
||||
classnames: cx,
|
||||
className,
|
||||
bodyClassName,
|
||||
footerClassName,
|
||||
mobileUI,
|
||||
disabled,
|
||||
testIdBuilder,
|
||||
onEntered,
|
||||
onExited
|
||||
}: ConfirmBoxProps) {
|
||||
const [loading, setLoading] = React.useState<boolean>();
|
||||
const [error, setError] = React.useState<string>();
|
||||
const bodyRef = React.useRef<
|
||||
{submit: () => Promise<Record<string, any>>} | undefined
|
||||
>();
|
||||
const bodyDomRef = React.useRef<HTMLElement | null>();
|
||||
const getPopOverContainer = React.useCallback(() => {
|
||||
const dom =
|
||||
bodyDomRef.current && !(bodyDomRef.current as HTMLElement).nodeType
|
||||
? findDOMNode(bodyDomRef.current)
|
||||
: null;
|
||||
return dom?.parentElement;
|
||||
}, []);
|
||||
const handleConfirm = React.useCallback(async () => {
|
||||
setError('');
|
||||
setLoading(true);
|
||||
try {
|
||||
const ret = beforeConfirm
|
||||
? await beforeConfirm?.(bodyRef.current)
|
||||
: await bodyRef.current?.submit?.();
|
||||
|
||||
if (ret === false) {
|
||||
return;
|
||||
} else if (typeof ret === 'string') {
|
||||
setError(ret);
|
||||
return;
|
||||
}
|
||||
|
||||
await onConfirm?.(ret);
|
||||
} catch (e) {
|
||||
setError(e.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setTimeout(() => setError(''), 5000);
|
||||
}
|
||||
}, [onConfirm, beforeConfirm]);
|
||||
React.useEffect(() => {
|
||||
show && setError('');
|
||||
}, [show]);
|
||||
|
||||
function renderDialog() {
|
||||
return mobileUI ? (
|
||||
<PopUp
|
||||
isShow={show}
|
||||
showConfirm
|
||||
onConfirm={handleConfirm}
|
||||
onHide={onCancel}
|
||||
container={popOverContainer}
|
||||
onEntered={onEntered}
|
||||
onExited={onExited}
|
||||
>
|
||||
{typeof children === 'function'
|
||||
? children({
|
||||
bodyRef: bodyRef,
|
||||
loading,
|
||||
popOverContainer: getPopOverContainer,
|
||||
onConfirm: handleConfirm
|
||||
})
|
||||
: children}
|
||||
</PopUp>
|
||||
) : (
|
||||
<Modal
|
||||
size={size}
|
||||
closeOnEsc={closeOnEsc}
|
||||
show={show}
|
||||
onHide={onCancel!}
|
||||
container={popOverContainer}
|
||||
className={className}
|
||||
onEntered={onEntered}
|
||||
onExited={onExited}
|
||||
>
|
||||
{showTitle !== false && title ? (
|
||||
<Modal.Header onClose={onCancel} className={headerClassName}>
|
||||
{title}
|
||||
</Modal.Header>
|
||||
) : null}
|
||||
<Modal.Body ref={bodyDomRef as any} className={bodyClassName}>
|
||||
{typeof children === 'function'
|
||||
? children({
|
||||
bodyRef: bodyRef,
|
||||
loading,
|
||||
onConfirm: handleConfirm,
|
||||
popOverContainer: getPopOverContainer
|
||||
})
|
||||
: children}
|
||||
</Modal.Body>
|
||||
{showFooter ?? true ? (
|
||||
<Modal.Footer className={footerClassName}>
|
||||
{loading || error ? (
|
||||
<div className={cx('Dialog-info')}>
|
||||
<Spinner size="sm" key="info" show={loading} />
|
||||
{error ? (
|
||||
<span className={cx('Dialog-error')}>{error}</span>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
<Button
|
||||
disabled={loading}
|
||||
onClick={onCancel}
|
||||
testIdBuilder={testIdBuilder?.getChild('cancel')}
|
||||
>
|
||||
{__('cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
disabled={loading || disabled}
|
||||
onClick={handleConfirm}
|
||||
level="primary"
|
||||
testIdBuilder={testIdBuilder?.getChild('confirm')}
|
||||
>
|
||||
{__('confirm')}
|
||||
</Button>
|
||||
</Modal.Footer>
|
||||
) : null}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function renderDrawer() {
|
||||
return (
|
||||
<Drawer
|
||||
size={size}
|
||||
closeOnEsc={closeOnEsc}
|
||||
show={show}
|
||||
onHide={onCancel!}
|
||||
container={popOverContainer}
|
||||
position={position}
|
||||
resizable={resizable}
|
||||
showCloseButton={false}
|
||||
className={className}
|
||||
>
|
||||
{showTitle !== false && title ? (
|
||||
<div className={cx('Drawer-header', headerClassName)}>
|
||||
<div className={cx('Drawer-title')}>{title}</div>
|
||||
</div>
|
||||
) : null}
|
||||
<div
|
||||
ref={bodyDomRef as any}
|
||||
className={cx('Drawer-body', bodyClassName)}
|
||||
>
|
||||
{typeof children === 'function'
|
||||
? children({
|
||||
bodyRef: bodyRef,
|
||||
loading,
|
||||
popOverContainer: getPopOverContainer,
|
||||
onConfirm: handleConfirm
|
||||
})
|
||||
: children}
|
||||
</div>
|
||||
{showFooter ?? true ? (
|
||||
<div className={cx('Drawer-footer', footerClassName)}>
|
||||
{loading || error ? (
|
||||
<div className={cx('Drawer-info')}>
|
||||
<Spinner size="sm" key="info" show={loading} />
|
||||
{error ? (
|
||||
<span className={cx('Drawer-error')}>{error}</span>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
<Button onClick={handleConfirm} level="primary">
|
||||
{__('confirm')}
|
||||
</Button>
|
||||
<Button onClick={onCancel}>{__('cancel')}</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
|
||||
return type === 'drawer' ? renderDrawer() : renderDialog();
|
||||
}
|
||||
|
||||
ConfirmBox.defaultProps = {
|
||||
type: 'dialog' as 'dialog',
|
||||
position: 'right' as 'right'
|
||||
};
|
||||
|
||||
export default localeable(themeable(ConfirmBox));
|
||||
417
packages/amis-ui/src/components/ContextMenu.tsx
Normal file
417
packages/amis-ui/src/components/ContextMenu.tsx
Normal file
@@ -0,0 +1,417 @@
|
||||
import {ClassNamesFn, themeable} from 'amis-core';
|
||||
import React, {version} from 'react';
|
||||
import {render} from 'react-dom';
|
||||
import {autobind, calculatePosition} from 'amis-core';
|
||||
import Transition, {
|
||||
ENTERED,
|
||||
ENTERING,
|
||||
EXITING
|
||||
} from 'react-transition-group/Transition';
|
||||
import debounce from 'lodash/debounce';
|
||||
import type {DebouncedFunc} from 'lodash';
|
||||
// import {createRoot} from 'react-dom/client';
|
||||
const fadeStyles: {
|
||||
[propName: string]: string;
|
||||
} = {
|
||||
[ENTERING]: 'in',
|
||||
[ENTERED]: 'in',
|
||||
[EXITING]: 'out'
|
||||
};
|
||||
|
||||
interface ContextMenuProps {
|
||||
className?: string;
|
||||
classPrefix: string;
|
||||
classnames: ClassNamesFn;
|
||||
container?: HTMLElement | null | (() => HTMLElement);
|
||||
}
|
||||
|
||||
export type MenuItem = {
|
||||
id?: string;
|
||||
label: string | React.ReactNode;
|
||||
icon?: string;
|
||||
disabled?: boolean;
|
||||
children?: Array<MenuItem | MenuDivider>;
|
||||
data?: any;
|
||||
className?: string;
|
||||
selected?: boolean;
|
||||
onSelect?: (data: any) => void;
|
||||
onHighlight?: (isHiglight: boolean, data: any) => void;
|
||||
};
|
||||
|
||||
export type MenuDivider = '|';
|
||||
|
||||
interface ContextMenuState {
|
||||
isOpened: boolean;
|
||||
menus: Array<MenuItem | MenuDivider> | (() => JSX.Element);
|
||||
x: number;
|
||||
y: number;
|
||||
cursorX: number;
|
||||
cursorY: number;
|
||||
align?: 'left' | 'right';
|
||||
onClose?: (ctx: ContextMenu) => void;
|
||||
contentClassName?: string;
|
||||
preventClose?: (e?: Event) => boolean;
|
||||
}
|
||||
|
||||
export class ContextMenu extends React.Component<
|
||||
ContextMenuProps,
|
||||
ContextMenuState
|
||||
> {
|
||||
static instance: any = null;
|
||||
debounceCalculatePosition: DebouncedFunc<(menu: HTMLElement) => void>;
|
||||
static async getInstance() {
|
||||
if (!ContextMenu.instance || ContextMenu.instance.unmount) {
|
||||
const container = document.body;
|
||||
const div = document.createElement('div');
|
||||
container.appendChild(div);
|
||||
|
||||
// if (parseInt(version.split('.')[0], 10) >= 18) {
|
||||
// const root = createRoot(div);
|
||||
// await new Promise<void>(resolve =>
|
||||
// root.render(<ThemedContextMenu ref={() => resolve()} />)
|
||||
// );
|
||||
// } else {
|
||||
render(<ThemedContextMenu />, div);
|
||||
// }
|
||||
}
|
||||
|
||||
return ContextMenu.instance;
|
||||
}
|
||||
|
||||
state: ContextMenuState = {
|
||||
isOpened: false,
|
||||
menus: [],
|
||||
x: -99999,
|
||||
y: -99999,
|
||||
cursorX: -99999,
|
||||
cursorY: -99999
|
||||
};
|
||||
|
||||
menuRef: React.RefObject<HTMLDivElement> = React.createRef();
|
||||
contentRef: React.RefObject<HTMLDivElement> = React.createRef();
|
||||
originInstance: this | null;
|
||||
prevInfo: {
|
||||
// 记录当前右键位置: 方便下一次做对比
|
||||
x: number;
|
||||
y: number;
|
||||
} | null;
|
||||
|
||||
unmount = false;
|
||||
menuEntered = false;
|
||||
constructor(props: ContextMenuProps) {
|
||||
super(props);
|
||||
|
||||
this.originInstance = ContextMenu.instance;
|
||||
ContextMenu.instance = this;
|
||||
this.debounceCalculatePosition = debounce(
|
||||
this.autoCalculatePosition.bind(this),
|
||||
200
|
||||
);
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
document.body.addEventListener('click', this.handleOutClick, true);
|
||||
document.addEventListener('keydown', this.handleKeyDown);
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.unmount = true;
|
||||
this.debounceCalculatePosition.cancel();
|
||||
ContextMenu.instance = this.originInstance;
|
||||
document.body.removeEventListener('click', this.handleOutClick, true);
|
||||
document.removeEventListener('keydown', this.handleKeyDown);
|
||||
|
||||
// @ts-ignore
|
||||
delete this.originInstance;
|
||||
}
|
||||
|
||||
@autobind
|
||||
openContextMenus(
|
||||
info: {x: number; y: number},
|
||||
menus: Array<MenuItem>,
|
||||
onClose?: (ctx: ContextMenu) => void,
|
||||
options?: {
|
||||
contentClassName?: string;
|
||||
preventClose?: (e?: Event) => boolean;
|
||||
}
|
||||
) {
|
||||
if (this.state.isOpened) {
|
||||
const {x, y} = this.state;
|
||||
const cursorX =
|
||||
x + (info.x - (this.prevInfo && this.prevInfo.x ? this.prevInfo.x : 0));
|
||||
const cursorY =
|
||||
y + (info.y - (this.prevInfo && this.prevInfo.y ? this.prevInfo.y : 0));
|
||||
// 避免 二次触发未进行智能定位 导致遮挡问题
|
||||
this.setState(
|
||||
{
|
||||
x: cursorX,
|
||||
y: cursorY,
|
||||
cursorX,
|
||||
cursorY,
|
||||
menus: menus,
|
||||
onClose,
|
||||
contentClassName: options?.contentClassName,
|
||||
preventClose: options?.preventClose
|
||||
},
|
||||
() => {
|
||||
this.handleEnter(this.menuRef.current as HTMLElement);
|
||||
}
|
||||
);
|
||||
} else {
|
||||
this.setState({
|
||||
isOpened: true,
|
||||
x: info.x,
|
||||
y: info.y,
|
||||
cursorX: info.x,
|
||||
cursorY: info.y,
|
||||
menus: menus,
|
||||
onClose,
|
||||
contentClassName: options?.contentClassName,
|
||||
preventClose: options?.preventClose
|
||||
});
|
||||
}
|
||||
this.prevInfo = info;
|
||||
}
|
||||
|
||||
@autobind
|
||||
close(e?: Event) {
|
||||
if (this.state.preventClose?.(e)) {
|
||||
return;
|
||||
}
|
||||
e?.preventDefault?.();
|
||||
this.menuEntered = false;
|
||||
this.resizeObserver?.disconnect();
|
||||
const onClose = this.state.onClose;
|
||||
this.setState(
|
||||
{
|
||||
isOpened: false,
|
||||
x: -99999,
|
||||
y: -99999,
|
||||
cursorX: -99999,
|
||||
cursorY: -99999,
|
||||
menus: [],
|
||||
contentClassName: '',
|
||||
preventClose: undefined
|
||||
},
|
||||
() => {
|
||||
onClose?.(this);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleOutClick(e: Event) {
|
||||
if (
|
||||
!this.menuEntered ||
|
||||
!e.target ||
|
||||
!this.menuRef.current ||
|
||||
this.menuRef.current.contains(e.target as HTMLElement)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (this.state.isOpened) {
|
||||
this.close(e);
|
||||
}
|
||||
}
|
||||
|
||||
handleClick(item: MenuItem) {
|
||||
const onClose = this.state.onClose;
|
||||
item.disabled ||
|
||||
(Array.isArray(item.children) && item.children.length) ||
|
||||
this.setState(
|
||||
{
|
||||
isOpened: false,
|
||||
x: -99999,
|
||||
y: -99999,
|
||||
cursorX: -99999,
|
||||
cursorY: -99999,
|
||||
menus: []
|
||||
},
|
||||
() => {
|
||||
item.onSelect?.(item.data);
|
||||
onClose?.(this);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleKeyDown(e: KeyboardEvent) {
|
||||
if (e.keyCode === 27 && this.state.isOpened) {
|
||||
this.close(e);
|
||||
}
|
||||
}
|
||||
|
||||
handleMouseEnter(item: MenuItem) {
|
||||
item.disabled || !item.onHighlight || item.onHighlight(true, item.data);
|
||||
}
|
||||
|
||||
handleMouseLeave(item: MenuItem) {
|
||||
item.disabled || !item.onHighlight || item.onHighlight(false, item.data);
|
||||
}
|
||||
|
||||
resizeObserver: null | ResizeObserver = null;
|
||||
|
||||
@autobind
|
||||
handleEnter(menu: HTMLElement) {
|
||||
this.autoCalculatePosition(menu);
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleEntered(menu: HTMLElement) {
|
||||
this.menuEntered = true;
|
||||
if (!this.contentRef.current || !window.ResizeObserver) {
|
||||
return;
|
||||
}
|
||||
// 监听菜单大小变化,并自动重新计算位置
|
||||
this.resizeObserver = new ResizeObserver(entries => {
|
||||
entries.length && this.debounceCalculatePosition(menu);
|
||||
});
|
||||
this.resizeObserver.observe(this.contentRef.current);
|
||||
}
|
||||
|
||||
@autobind
|
||||
autoCalculatePosition(menu: HTMLElement) {
|
||||
const lastChild = menu.lastChild as HTMLElement;
|
||||
|
||||
// 因为 debounce 的原因,可能menu 已经被卸载了。
|
||||
if (!lastChild?.offsetWidth) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 智能定位,选择一个合适的对齐方式。
|
||||
const info = calculatePosition(
|
||||
'asContextMenu',
|
||||
lastChild,
|
||||
menu.children[1] as HTMLElement,
|
||||
menu.children[0]
|
||||
);
|
||||
|
||||
const align =
|
||||
info.positionLeft + 300 < window.innerWidth ? 'right' : 'left';
|
||||
|
||||
this.setState({
|
||||
x: info.positionLeft,
|
||||
y: info.positionTop,
|
||||
align
|
||||
});
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleSelfContextMenu(e: React.MouseEvent) {
|
||||
e.preventDefault();
|
||||
}
|
||||
|
||||
renderMenus(menus: Array<MenuItem | MenuDivider>) {
|
||||
const {classnames: cx} = this.props;
|
||||
|
||||
return menus.map((item, index) => {
|
||||
if (item === '|') {
|
||||
return <li key={index} className={cx('ContextMenu-divider')} />;
|
||||
}
|
||||
|
||||
const hasChildren = Array.isArray(item.children) && item.children.length;
|
||||
return (
|
||||
<li
|
||||
key={`${item.label}-${index}`}
|
||||
className={cx('ContextMenu-item', item.className, {
|
||||
'has-child': hasChildren,
|
||||
'is-disabled': item.disabled,
|
||||
'is-active': item.selected
|
||||
})}
|
||||
>
|
||||
<a
|
||||
onClick={this.handleClick.bind(this, item)}
|
||||
onMouseEnter={this.handleMouseEnter.bind(this, item)}
|
||||
onMouseLeave={this.handleMouseLeave.bind(this, item)}
|
||||
>
|
||||
{item.icon ? (
|
||||
<span className={cx('ContextMenu-itemIcon', item.icon)} />
|
||||
) : null}
|
||||
{item.label}
|
||||
{hasChildren ? <i className="fas fa-chevron-right" /> : null}
|
||||
{item.selected ? <i className="fas fa-check" /> : null}
|
||||
</a>
|
||||
{hasChildren ? (
|
||||
<ul className={cx('ContextMenu-subList')}>
|
||||
{this.renderMenus(item.children!)}
|
||||
</ul>
|
||||
) : null}
|
||||
</li>
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
render() {
|
||||
const {className, container, classnames: cx} = this.props;
|
||||
|
||||
return (
|
||||
<Transition
|
||||
mountOnEnter
|
||||
unmountOnExit
|
||||
onEnter={this.handleEnter}
|
||||
in={this.state.isOpened}
|
||||
timeout={500}
|
||||
onEntered={this.handleEntered}
|
||||
>
|
||||
{(status: string) => (
|
||||
<div
|
||||
ref={this.menuRef}
|
||||
role="contextmenu"
|
||||
className={cx(
|
||||
'ContextMenu',
|
||||
{
|
||||
'ContextMenu--left': this.state.align === 'left'
|
||||
},
|
||||
className,
|
||||
this.state.contentClassName
|
||||
)}
|
||||
onContextMenu={this.handleSelfContextMenu}
|
||||
>
|
||||
<div className={cx(`ContextMenu-overlay`, fadeStyles[status])} />
|
||||
<div
|
||||
className={cx(`ContextMenu-cursor`)}
|
||||
style={{
|
||||
left: `${this.state.cursorX}px`,
|
||||
top: `${this.state.cursorY}px`
|
||||
}}
|
||||
/>
|
||||
<div
|
||||
ref={this.contentRef}
|
||||
style={{left: `${this.state.x}px`, top: `${this.state.y}px`}}
|
||||
className={cx(`ContextMenu-menu`, fadeStyles[status])}
|
||||
>
|
||||
{typeof this.state.menus === 'function' ? (
|
||||
this.state.menus()
|
||||
) : (
|
||||
<ul className={cx('ContextMenu-list')}>
|
||||
{this.renderMenus(this.state.menus)}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Transition>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const ThemedContextMenu = themeable(ContextMenu);
|
||||
export default ThemedContextMenu;
|
||||
|
||||
export async function openContextMenus(
|
||||
info: Event | {x: number; y: number},
|
||||
menus: Array<MenuItem | MenuDivider> | (() => React.ReactNode),
|
||||
onClose?: (ctx: ContextMenu) => void,
|
||||
options?: {
|
||||
contentClassName?: string;
|
||||
preventClose?: (e?: Event) => boolean;
|
||||
}
|
||||
) {
|
||||
return ContextMenu.getInstance().then(instance =>
|
||||
instance.openContextMenus(info, menus, onClose, options)
|
||||
);
|
||||
}
|
||||
|
||||
export async function closeContextMenus() {
|
||||
return ContextMenu.getInstance().then(instance => instance?.close());
|
||||
}
|
||||
1249
packages/amis-ui/src/components/DatePicker.tsx
Normal file
1249
packages/amis-ui/src/components/DatePicker.tsx
Normal file
File diff suppressed because it is too large
Load Diff
2204
packages/amis-ui/src/components/DateRangePicker.tsx
Normal file
2204
packages/amis-ui/src/components/DateRangePicker.tsx
Normal file
File diff suppressed because it is too large
Load Diff
128
packages/amis-ui/src/components/DiffEditor.tsx
Normal file
128
packages/amis-ui/src/components/DiffEditor.tsx
Normal file
@@ -0,0 +1,128 @@
|
||||
import React from 'react';
|
||||
import Editor, {EditorBaseProps} from './Editor';
|
||||
import {autobind} from 'amis-core';
|
||||
|
||||
export interface DiffEditorProps extends EditorBaseProps {
|
||||
originValue?: string;
|
||||
}
|
||||
|
||||
export default class DiffEditor extends React.Component<DiffEditorProps> {
|
||||
editor: any;
|
||||
monaco: any;
|
||||
originalEditor: any;
|
||||
modifiedEditor: any;
|
||||
toDispose: Array<Function> = [];
|
||||
domRef = React.createRef<any>();
|
||||
|
||||
componentDidUpdate(prevProps: any) {
|
||||
const {value, originValue} = this.props;
|
||||
|
||||
if (this.originalEditor && originValue !== prevProps.originValue) {
|
||||
this.originalEditor.getModel().setValue(originValue || '');
|
||||
}
|
||||
|
||||
if (this.modifiedEditor && value !== prevProps.value) {
|
||||
const editorValue = this.modifiedEditor.getModel().getValue();
|
||||
editorValue !== value &&
|
||||
this.modifiedEditor.getModel().setValue(value || '');
|
||||
}
|
||||
|
||||
if (this.props.disabled !== prevProps.disabled && this.modifiedEditor) {
|
||||
this.modifiedEditor.updateOptions?.({
|
||||
readOnly: this.props.disabled
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.toDispose.forEach(fn => fn());
|
||||
}
|
||||
|
||||
prevHeight = 0;
|
||||
@autobind
|
||||
updateContainerSize(editor: any, monaco: any) {
|
||||
const dom = this.domRef.current?.getDom();
|
||||
if (!dom) {
|
||||
return;
|
||||
}
|
||||
|
||||
const lineHeight = editor.getOption(monaco.editor.EditorOption.lineHeight);
|
||||
const lineCount = editor.getModel()?.getLineCount() || 1;
|
||||
const height = editor.getTopForLineNumber(lineCount + 1) + lineHeight;
|
||||
|
||||
if (this.prevHeight !== height && dom.parentElement) {
|
||||
this.prevHeight = height;
|
||||
dom.parentElement.style.height = `${height}px`;
|
||||
editor.layout();
|
||||
}
|
||||
}
|
||||
|
||||
@autobind
|
||||
editorFactory(containerElement: any, monaco: any, options: any) {
|
||||
if (this.props.editorFactory) {
|
||||
return this.props.editorFactory(containerElement, monaco, options);
|
||||
}
|
||||
return monaco.editor.createDiffEditor(containerElement, options);
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleModifiedEditorChange(e: any) {
|
||||
const {onChange} = this.props;
|
||||
const value = this.modifiedEditor.getModel().getValue();
|
||||
value !== this.props.value && onChange?.(value, e);
|
||||
}
|
||||
|
||||
@autobind
|
||||
editorDidMount(editor: any, monaco: any) {
|
||||
const {value, originValue, language, onFocus, onBlur, editorDidMount} =
|
||||
this.props;
|
||||
editorDidMount?.(editor, monaco);
|
||||
|
||||
this.monaco = monaco;
|
||||
this.editor = editor;
|
||||
this.modifiedEditor = editor.getModifiedEditor();
|
||||
this.originalEditor = editor.getOriginalEditor();
|
||||
|
||||
onFocus &&
|
||||
this.toDispose.push(
|
||||
this.modifiedEditor.onDidFocusEditorWidget(onFocus).dispose
|
||||
);
|
||||
onBlur &&
|
||||
this.toDispose.push(
|
||||
this.modifiedEditor.onDidBlurEditorWidget(onBlur).dispose
|
||||
);
|
||||
|
||||
this.toDispose.push(
|
||||
this.modifiedEditor.onDidChangeModelDecorations(() => {
|
||||
this.updateContainerSize(this.modifiedEditor, monaco); // typing
|
||||
requestAnimationFrame(
|
||||
this.updateContainerSize.bind(this, this.modifiedEditor, monaco)
|
||||
); // folding
|
||||
}).dispose
|
||||
);
|
||||
|
||||
this.toDispose.push(
|
||||
this.modifiedEditor.onDidChangeModelContent(
|
||||
this.handleModifiedEditorChange
|
||||
).dispose
|
||||
);
|
||||
|
||||
this.editor.setModel({
|
||||
original: this.monaco.editor.createModel(originValue || '', language),
|
||||
modified: this.monaco.editor.createModel(value, language)
|
||||
});
|
||||
}
|
||||
|
||||
render() {
|
||||
const {value, originValue, options, ...rest} = this.props;
|
||||
return (
|
||||
<Editor
|
||||
{...rest}
|
||||
ref={this.domRef}
|
||||
editorDidMount={this.editorDidMount}
|
||||
editorFactory={this.editorFactory}
|
||||
isDiffEditor
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
102
packages/amis-ui/src/components/DndContainer.tsx
Normal file
102
packages/amis-ui/src/components/DndContainer.tsx
Normal file
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* @file DndContainer
|
||||
* @desc 可拖拽容器
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import Draggable from 'react-draggable';
|
||||
import {localeable, LocaleProps, themeable, ThemeProps} from 'amis-core';
|
||||
|
||||
import type {
|
||||
DraggableEvent,
|
||||
DraggableData,
|
||||
DraggableBounds
|
||||
} from 'react-draggable';
|
||||
|
||||
export interface DndContainerProps extends LocaleProps, ThemeProps {
|
||||
/**
|
||||
* 可拖拽的方向, 默认为所有方向, 支持设置为X或Y轴
|
||||
*/
|
||||
axis?: 'both' | 'x' | 'y' | 'none';
|
||||
/** 元素的位置 */
|
||||
position?: {x: number; y: number};
|
||||
/** 元素的起始位置 */
|
||||
defaultPosition?: {x: number; y: number};
|
||||
/**
|
||||
* 拖拽的边界, 可以设置坐标, 也可以设置父级元素的选择器
|
||||
*/
|
||||
bounds?: DraggableBounds | string;
|
||||
/** 以网格范围拖拽的步长 */
|
||||
grid?: [number, number];
|
||||
/** 初始化拖拽的选择器 */
|
||||
handle?: string;
|
||||
/** 禁止拖拽的选择器 */
|
||||
cancel?: string;
|
||||
/** 拖拽距离的缩放比, 默认为1 */
|
||||
scale?: number;
|
||||
/** 是否禁止拖拽 */
|
||||
draggable?: boolean;
|
||||
/** 默认设置容器内部为'user-select:none', 可以设置true关闭 */
|
||||
enableUserSelect?: boolean;
|
||||
nodeRef?: React.RefObject<HTMLElement>;
|
||||
children?: React.ReactElement<any>;
|
||||
onStart?: (event: DraggableEvent, data: DraggableData) => void | false;
|
||||
onDrag?: (event: DraggableEvent, data: DraggableData) => void | false;
|
||||
onStop?: (event: DraggableEvent, data: DraggableData) => void | false;
|
||||
}
|
||||
|
||||
const DndContainer: React.FC<DndContainerProps> = (
|
||||
props: DndContainerProps
|
||||
) => {
|
||||
const {
|
||||
className,
|
||||
classnames: cx,
|
||||
children,
|
||||
axis,
|
||||
position,
|
||||
defaultPosition,
|
||||
bounds,
|
||||
grid,
|
||||
handle,
|
||||
cancel,
|
||||
draggable,
|
||||
scale,
|
||||
enableUserSelect,
|
||||
nodeRef,
|
||||
onDrag,
|
||||
onStart,
|
||||
onStop
|
||||
} = props;
|
||||
|
||||
return (
|
||||
<Draggable
|
||||
axis={axis}
|
||||
position={position}
|
||||
defaultPosition={defaultPosition}
|
||||
bounds={bounds}
|
||||
grid={grid}
|
||||
handle={handle}
|
||||
cancel={cancel}
|
||||
disabled={!draggable}
|
||||
scale={scale}
|
||||
enableUserSelectHack={!enableUserSelect}
|
||||
nodeRef={nodeRef}
|
||||
defaultClassName={cx(className)}
|
||||
defaultClassNameDragging={cx('DndContainer--dragging')}
|
||||
defaultClassNameDragged={cx('DndContainer--dragged')}
|
||||
onStart={onStart}
|
||||
onDrag={onDrag}
|
||||
onStop={onStop}
|
||||
>
|
||||
{children}
|
||||
</Draggable>
|
||||
);
|
||||
};
|
||||
|
||||
DndContainer.defaultProps = {
|
||||
axis: 'both',
|
||||
scale: 1,
|
||||
enableUserSelect: false
|
||||
};
|
||||
|
||||
export default localeable(themeable(DndContainer));
|
||||
409
packages/amis-ui/src/components/Drawer.tsx
Normal file
409
packages/amis-ui/src/components/Drawer.tsx
Normal file
@@ -0,0 +1,409 @@
|
||||
/**
|
||||
* @file Drawer
|
||||
* @description
|
||||
* @author fex
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import Transition, {
|
||||
ENTERED,
|
||||
ENTERING,
|
||||
EXITING,
|
||||
EXITED
|
||||
} from 'react-transition-group/Transition';
|
||||
import Portal from 'react-overlays/Portal';
|
||||
import {Icon} from './icons';
|
||||
import cx from 'classnames';
|
||||
import {current, addModal, removeModal} from './ModalManager';
|
||||
import {ClassNamesFn, themeable} from 'amis-core';
|
||||
import {noop, autobind, getScrollbarWidth} from 'amis-core';
|
||||
import {getContainerWithFullscreen} from './Modal';
|
||||
|
||||
type DrawerPosition = 'top' | 'right' | 'bottom' | 'left';
|
||||
|
||||
export interface DrawerProps {
|
||||
className?: string;
|
||||
bodyClassName?: string;
|
||||
size: any;
|
||||
overlay: boolean;
|
||||
onHide: (e: any) => void;
|
||||
closeOnEsc?: boolean;
|
||||
container: any;
|
||||
show?: boolean;
|
||||
showCloseButton?: boolean;
|
||||
width?: number | string;
|
||||
height?: number | string;
|
||||
position: DrawerPosition;
|
||||
disabled?: boolean;
|
||||
closeOnOutside?: boolean;
|
||||
classPrefix: string;
|
||||
resizable?: boolean;
|
||||
classnames: ClassNamesFn;
|
||||
children?: React.ReactNode | Array<React.ReactNode>;
|
||||
onExited?: () => void;
|
||||
onEntered?: () => void;
|
||||
drawerClassName?: string;
|
||||
drawerMaskClassName?: string;
|
||||
mobileUI?: boolean;
|
||||
onDragging?: (value: boolean) => void;
|
||||
}
|
||||
|
||||
export interface DrawerState {}
|
||||
|
||||
const fadeStyles: {
|
||||
[propName: string]: string;
|
||||
} = {
|
||||
[ENTERING]: 'in',
|
||||
[ENTERED]: 'in'
|
||||
};
|
||||
|
||||
export class Drawer extends React.Component<DrawerProps, DrawerState> {
|
||||
static defaultProps: Pick<
|
||||
DrawerProps,
|
||||
'container' | 'position' | 'size' | 'overlay' | 'showCloseButton'
|
||||
> = {
|
||||
container: document.body,
|
||||
position: 'left',
|
||||
size: 'md',
|
||||
showCloseButton: true,
|
||||
overlay: true
|
||||
};
|
||||
|
||||
modalDom: HTMLElement;
|
||||
contentDom: HTMLElement;
|
||||
isRootClosed = false;
|
||||
resizer = React.createRef<HTMLDivElement>();
|
||||
resizeCoord: number = 0;
|
||||
|
||||
componentDidMount() {
|
||||
if (this.props.show) {
|
||||
this.handleEntered();
|
||||
}
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps: DrawerProps) {
|
||||
// jest 里面没有触发 entered 导致后续的逻辑错误,
|
||||
// 所以直接 300 ms 后触发
|
||||
if (
|
||||
typeof jest !== 'undefined' &&
|
||||
prevProps.show !== this.props.show &&
|
||||
this.props.show
|
||||
) {
|
||||
setTimeout(() => {
|
||||
this.handleEntered();
|
||||
}, 300);
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
if (this.props.show) {
|
||||
this.handleExited();
|
||||
}
|
||||
}
|
||||
|
||||
contentRef = (ref: any) => (this.contentDom = ref);
|
||||
|
||||
handleEnter = () => {
|
||||
document.body.classList.add(`is-modalOpened`);
|
||||
if (
|
||||
window.innerWidth - document.documentElement.clientWidth > 0 ||
|
||||
document.body.scrollHeight > document.body.clientHeight
|
||||
) {
|
||||
const scrollbarWidth = getScrollbarWidth();
|
||||
if (scrollbarWidth) {
|
||||
document.body.style.width = `calc(100% - ${scrollbarWidth}px)`;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
handleEntered = () => {
|
||||
const onEntered = this.props.onEntered;
|
||||
|
||||
document.body.addEventListener(
|
||||
'mousedown',
|
||||
this.handleRootMouseDownCapture,
|
||||
true
|
||||
);
|
||||
document.body.addEventListener(
|
||||
'mouseup',
|
||||
this.handleRootMouseUpCapture,
|
||||
true
|
||||
);
|
||||
document.body.addEventListener('mouseup', this.handleRootMouseUp);
|
||||
|
||||
onEntered && onEntered();
|
||||
};
|
||||
handleExited = () => {
|
||||
const onExited = this.props.onExited;
|
||||
document.activeElement && (document.activeElement as HTMLElement)?.blur?.();
|
||||
|
||||
document.body.removeEventListener('mouseup', this.handleRootMouseUp);
|
||||
document.body.removeEventListener(
|
||||
'mouseup',
|
||||
this.handleRootMouseUpCapture,
|
||||
true
|
||||
);
|
||||
document.body.removeEventListener(
|
||||
'mousedown',
|
||||
this.handleRootMouseDownCapture,
|
||||
true
|
||||
);
|
||||
|
||||
onExited && onExited();
|
||||
setTimeout(() => {
|
||||
if (!document.querySelector('.amis-dialog-widget')) {
|
||||
document.body.classList.remove(`is-modalOpened`);
|
||||
document.body.style.width = '';
|
||||
}
|
||||
}, 200);
|
||||
};
|
||||
|
||||
modalRef = (ref: any) => {
|
||||
this.modalDom = ref;
|
||||
if (ref) {
|
||||
addModal(this);
|
||||
(ref as HTMLElement).classList.add(
|
||||
`${this.props.classPrefix}Modal--${current()}th`
|
||||
);
|
||||
} else {
|
||||
removeModal(this);
|
||||
}
|
||||
};
|
||||
|
||||
@autobind
|
||||
handleRootMouseDownCapture(e: MouseEvent) {
|
||||
const target = e.target as HTMLElement;
|
||||
const {closeOnOutside, classPrefix: ns, mobileUI} = this.props;
|
||||
const isLeftButton =
|
||||
(e.button === 1 && window.event !== null) || e.button === 0;
|
||||
|
||||
this.isRootClosed = !!(
|
||||
isLeftButton &&
|
||||
closeOnOutside &&
|
||||
target &&
|
||||
this.modalDom &&
|
||||
((!mobileUI &&
|
||||
!this.modalDom.contains(target) &&
|
||||
!target.closest('[role=dialog]')) ||
|
||||
(target.matches(`.${ns}Drawer-overlay`) &&
|
||||
target.parentElement === this.modalDom))
|
||||
); // 干脆过滤掉来自弹框里面的点击
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleRootMouseUpCapture(e: MouseEvent) {
|
||||
// mousedown 的时候不在弹窗里面,则不需要判断了
|
||||
if (!this.isRootClosed) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 再判断 mouseup 的时候是不是在弹窗里面
|
||||
this.handleRootMouseDownCapture(e);
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleRootMouseUp(e: MouseEvent) {
|
||||
const {onHide} = this.props;
|
||||
|
||||
this.isRootClosed && !e.defaultPrevented && onHide(e);
|
||||
}
|
||||
|
||||
getDrawerStyle() {
|
||||
const {width, height, position} = this.props;
|
||||
const offsetStyle: {
|
||||
width?: number | string;
|
||||
height?: number | string;
|
||||
} = {};
|
||||
if ((position === 'left' || position === 'right') && width !== undefined) {
|
||||
offsetStyle.width = width;
|
||||
} else if (
|
||||
(position === 'top' || position === 'bottom') &&
|
||||
height !== undefined
|
||||
) {
|
||||
offsetStyle.height = height;
|
||||
}
|
||||
return offsetStyle;
|
||||
}
|
||||
|
||||
@autobind
|
||||
resizeMouseDown(e: React.MouseEvent<any>) {
|
||||
const {position, classPrefix: ns, onDragging} = this.props;
|
||||
onDragging && onDragging(true);
|
||||
const drawer = this.contentDom;
|
||||
const resizer = this.resizer.current!;
|
||||
|
||||
const drawerWidth = getComputedStyle(drawer).width as string;
|
||||
const drawerHeight = getComputedStyle(drawer).height as string;
|
||||
|
||||
this.resizeCoord =
|
||||
(position === 'left' &&
|
||||
e.clientX -
|
||||
resizer.offsetWidth -
|
||||
parseInt(drawerWidth.substring(0, drawerWidth.length - 2))) ||
|
||||
(position === 'right' &&
|
||||
document.body.offsetWidth -
|
||||
e.clientX -
|
||||
resizer.offsetWidth -
|
||||
parseInt(drawerWidth.substring(0, drawerWidth.length - 2))) ||
|
||||
(position === 'top' &&
|
||||
e.clientY -
|
||||
resizer.offsetHeight -
|
||||
parseInt(drawerHeight.substring(0, drawerHeight.length - 2))) ||
|
||||
(position === 'bottom' &&
|
||||
document.body.offsetHeight -
|
||||
e.clientY -
|
||||
resizer.offsetHeight -
|
||||
parseInt(drawerHeight.substring(0, drawerHeight.length - 2))) ||
|
||||
0;
|
||||
|
||||
document.body.addEventListener('mousemove', this.bindResize);
|
||||
document.body.addEventListener('mouseup', this.removeResize);
|
||||
}
|
||||
|
||||
@autobind
|
||||
bindResize(e: any) {
|
||||
const {position} = this.props;
|
||||
const maxWH = 'calc(100% - 50px)';
|
||||
const drawer = this.contentDom;
|
||||
const drawerStyle = drawer.style;
|
||||
let wh =
|
||||
(position === 'left' && e.clientX) ||
|
||||
(position === 'right' && document.body.offsetWidth - e.clientX) ||
|
||||
(position === 'top' && e.clientY) ||
|
||||
(position === 'bottom' && document.body.offsetHeight - e.clientY) ||
|
||||
0;
|
||||
wh = wh - this.resizeCoord + 'px';
|
||||
|
||||
if (position === 'left' || position === 'right') {
|
||||
drawerStyle.maxWidth = maxWH;
|
||||
drawerStyle.width = wh;
|
||||
}
|
||||
|
||||
if (position === 'top' || position === 'bottom') {
|
||||
drawerStyle.maxHeight = maxWH;
|
||||
drawerStyle.height = wh;
|
||||
}
|
||||
}
|
||||
|
||||
@autobind
|
||||
removeResize() {
|
||||
const {onDragging} = this.props;
|
||||
onDragging && onDragging(false);
|
||||
document.body.removeEventListener('mousemove', this.bindResize);
|
||||
document.body.removeEventListener('mouseup', this.removeResize);
|
||||
}
|
||||
|
||||
renderResizeCtrl() {
|
||||
const {classnames: cx} = this.props;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx('Drawer-resizeCtrl')}
|
||||
ref={this.resizer}
|
||||
onMouseDown={this.resizeMouseDown}
|
||||
>
|
||||
<div className={cx('Drawer-resizeIcon')}>···</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
classPrefix: ns,
|
||||
className,
|
||||
children,
|
||||
container,
|
||||
show,
|
||||
showCloseButton,
|
||||
position,
|
||||
size,
|
||||
onHide,
|
||||
disabled,
|
||||
overlay,
|
||||
bodyClassName,
|
||||
resizable,
|
||||
drawerClassName,
|
||||
drawerMaskClassName
|
||||
} = this.props;
|
||||
|
||||
const bodyStyle = this.getDrawerStyle();
|
||||
|
||||
return (
|
||||
<Portal container={getContainerWithFullscreen(container)}>
|
||||
<Transition
|
||||
mountOnEnter
|
||||
unmountOnExit
|
||||
appear
|
||||
in={show}
|
||||
timeout={500}
|
||||
onEnter={this.handleEnter}
|
||||
onExited={this.handleExited}
|
||||
onEntered={this.handleEntered}
|
||||
>
|
||||
{(status: string) => {
|
||||
if (status === ENTERING) {
|
||||
// force reflow
|
||||
// 由于从 mount 进来到加上 in 这个 class 估计是时间太短,上次的样式还没应用进去,所以这里强制reflow一把。
|
||||
// 否则看不到动画。
|
||||
this.contentDom.offsetWidth;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={this.modalRef}
|
||||
role="dialog"
|
||||
className={cx(
|
||||
`amis-dialog-widget ${ns}Drawer`,
|
||||
{
|
||||
[`${ns}Drawer--${position}`]: position,
|
||||
[`${ns}Drawer--${size}`]: size,
|
||||
[`${ns}Drawer--noOverlay`]: !overlay
|
||||
},
|
||||
className
|
||||
)}
|
||||
// onClick={this.handleWidgetClick} // 其实不需要插件,直接写逻辑吧
|
||||
>
|
||||
{overlay ? (
|
||||
<div
|
||||
className={cx(
|
||||
`${ns}Drawer-overlay`,
|
||||
fadeStyles[status],
|
||||
drawerMaskClassName
|
||||
)}
|
||||
/>
|
||||
) : null}
|
||||
<div
|
||||
ref={this.contentRef}
|
||||
style={bodyStyle}
|
||||
className={cx(
|
||||
`${ns}Drawer-content`,
|
||||
bodyClassName,
|
||||
fadeStyles[status],
|
||||
drawerClassName
|
||||
)}
|
||||
>
|
||||
{show && showCloseButton ? (
|
||||
<a
|
||||
onClick={disabled ? undefined : onHide}
|
||||
className={`${ns}Drawer-close`}
|
||||
>
|
||||
<Icon
|
||||
icon="close"
|
||||
className="icon"
|
||||
iconContent="Drawer-close"
|
||||
/>
|
||||
</a>
|
||||
) : null}
|
||||
{status === EXITED ? null : children}
|
||||
{resizable ? this.renderResizeCtrl() : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
</Transition>
|
||||
</Portal>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(Drawer);
|
||||
186
packages/amis-ui/src/components/DropDownSelection.tsx
Normal file
186
packages/amis-ui/src/components/DropDownSelection.tsx
Normal file
@@ -0,0 +1,186 @@
|
||||
import React from 'react';
|
||||
import {findDOMNode} from 'react-dom';
|
||||
import {BaseSelection, BaseSelectionProps} from './Selection';
|
||||
import {SpinnerExtraProps} from './Spinner';
|
||||
import PopOverContainer from './PopOverContainer';
|
||||
import ListSelection from './GroupedSelection';
|
||||
import TreeSelection from './TreeSelection';
|
||||
import ResultBox from './ResultBox';
|
||||
import {
|
||||
ThemeProps,
|
||||
themeable,
|
||||
localeable,
|
||||
LocaleProps,
|
||||
findTree,
|
||||
filterTree,
|
||||
noop
|
||||
} from 'amis-core';
|
||||
import {matchSorter} from 'match-sorter';
|
||||
|
||||
import {Icon} from './icons';
|
||||
import SearchBox from './SearchBox';
|
||||
import {Option} from './Select';
|
||||
import type {TestIdBuilder} from 'amis-core';
|
||||
|
||||
export interface DropDownSelectionProps
|
||||
extends ThemeProps,
|
||||
LocaleProps,
|
||||
SpinnerExtraProps,
|
||||
BaseSelectionProps {
|
||||
options: Array<any>;
|
||||
value: any;
|
||||
onChange: (value: any) => void;
|
||||
disabled?: boolean;
|
||||
searchable?: boolean;
|
||||
popOverContainer?: any;
|
||||
mode?: 'list' | 'tree';
|
||||
testIdBuilder?: TestIdBuilder;
|
||||
}
|
||||
|
||||
export interface DropDownSelectionState {
|
||||
searchText: string;
|
||||
}
|
||||
|
||||
class DropDownSelection extends BaseSelection<
|
||||
DropDownSelectionProps,
|
||||
DropDownSelectionState
|
||||
> {
|
||||
constructor(props: DropDownSelectionProps) {
|
||||
super(props);
|
||||
this.state = {
|
||||
searchText: ''
|
||||
};
|
||||
this.onSearch = this.onSearch.bind(this);
|
||||
this.filterOptions = this.filterOptions.bind(this);
|
||||
}
|
||||
|
||||
onSearch(text: string) {
|
||||
this.setState({searchText: text});
|
||||
}
|
||||
|
||||
filterOptions(options: any[]) {
|
||||
const {valueField = 'value', labelField} = this.props;
|
||||
const text = this.state.searchText;
|
||||
if (!text) {
|
||||
return this.props.options;
|
||||
}
|
||||
return filterTree(
|
||||
options,
|
||||
(option: Option, key: number, level: number, paths: Array<Option>) => {
|
||||
return !!(
|
||||
(Array.isArray(option.children) && option.children.length) ||
|
||||
!!matchSorter([option].concat(paths), text, {
|
||||
keys: [labelField || 'label', valueField || 'value'],
|
||||
threshold: matchSorter.rankings.CONTAINS
|
||||
}).length
|
||||
);
|
||||
},
|
||||
0,
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
// 选了值,还原options
|
||||
onPopClose(onClose: () => void) {
|
||||
this.setState({searchText: ''});
|
||||
onClose();
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
options,
|
||||
onChange,
|
||||
value,
|
||||
classnames: cx,
|
||||
disabled,
|
||||
translate: __,
|
||||
searchable,
|
||||
mode = 'list',
|
||||
valueField = 'value',
|
||||
option2value,
|
||||
loadingConfig,
|
||||
popOverContainer,
|
||||
testIdBuilder,
|
||||
mobileUI,
|
||||
classPrefix: ns
|
||||
} = this.props;
|
||||
|
||||
return (
|
||||
<PopOverContainer
|
||||
mobileUI={mobileUI}
|
||||
overlayWidthField="width"
|
||||
popOverContainer={popOverContainer || (() => findDOMNode(this))}
|
||||
popOverRender={({onClose}) => (
|
||||
<div>
|
||||
{searchable ? (
|
||||
<SearchBox
|
||||
className={cx(`${ns}DropDownSelection-searchbox`)}
|
||||
mini={false}
|
||||
onSearch={this.onSearch}
|
||||
testIdBuilder={testIdBuilder?.getChild('searchbox')}
|
||||
/>
|
||||
) : null}
|
||||
{mode === 'list' ? (
|
||||
<ListSelection
|
||||
multiple={false}
|
||||
onClick={() => this.onPopClose(onClose)}
|
||||
options={this.filterOptions(this.props.options)}
|
||||
value={value}
|
||||
option2value={option2value}
|
||||
testIdBuilder={testIdBuilder?.getChild('selection')}
|
||||
onChange={(value: any) => {
|
||||
onChange(Array.isArray(value) ? value[0] : value);
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<TreeSelection
|
||||
className={'is-scrollable'}
|
||||
multiple={false}
|
||||
options={this.filterOptions(this.props.options)}
|
||||
value={value}
|
||||
loadingConfig={loadingConfig}
|
||||
testIdBuilder={testIdBuilder?.getChild('selection')}
|
||||
onChange={(value: any) => {
|
||||
this.onPopClose(onClose);
|
||||
onChange(value[valueField]);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
>
|
||||
{({onClick, ref, isOpened}) => (
|
||||
<div className={cx('DropDownSelection')}>
|
||||
<ResultBox
|
||||
className={cx(
|
||||
'DropDownSelection-input',
|
||||
isOpened ? 'is-active' : ''
|
||||
)}
|
||||
ref={ref}
|
||||
allowInput={false}
|
||||
result={
|
||||
value
|
||||
? findTree(options, item => item[valueField] === value)
|
||||
: ''
|
||||
}
|
||||
onResultChange={noop}
|
||||
onResultClick={onClick}
|
||||
placeholder={__('Condition.field_placeholder')}
|
||||
disabled={disabled}
|
||||
mobileUI={mobileUI}
|
||||
testIdBuilder={testIdBuilder?.getChild('resultbox')}
|
||||
>
|
||||
{!mobileUI ? (
|
||||
<span className={cx('DropDownSelection-caret')}>
|
||||
<Icon icon="right-arrow-bold" className="icon" />
|
||||
</span>
|
||||
) : null}
|
||||
</ResultBox>
|
||||
</div>
|
||||
)}
|
||||
</PopOverContainer>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(localeable(DropDownSelection));
|
||||
174
packages/amis-ui/src/components/DropdownContextMenus.tsx
Normal file
174
packages/amis-ui/src/components/DropdownContextMenus.tsx
Normal file
@@ -0,0 +1,174 @@
|
||||
/**
|
||||
* @file DropdownContextMenus
|
||||
* @desc 下拉菜单组件,用于展示上下文菜单
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import {themeable} from 'amis-core';
|
||||
import {Icon} from './icons';
|
||||
import {ThemeProps} from 'amis-core';
|
||||
import PopOverContainer from './PopOverContainer';
|
||||
|
||||
/**
|
||||
* 菜单项配置
|
||||
*/
|
||||
export interface ContextMenu<T = any> {
|
||||
/** 菜单项 ID */
|
||||
id?: string;
|
||||
/** 菜单项文本 */
|
||||
label: string;
|
||||
/** 菜单项图标 */
|
||||
icon?: string;
|
||||
/** 菜单项等级 */
|
||||
level?: 'normal' | 'danger';
|
||||
|
||||
className?: string;
|
||||
disabled?: boolean;
|
||||
/** 点击菜单项的回调 */
|
||||
onClick?: (item: T) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 组件属性定义
|
||||
*/
|
||||
interface DropdownContextMenusProps<T = Record<string, any>>
|
||||
extends ThemeProps {
|
||||
/** 是否禁用 */
|
||||
disabled?: boolean;
|
||||
/** 上下文数据 */
|
||||
context: T;
|
||||
|
||||
/** 获取目标元素的方法 */
|
||||
getTargetElement?: (dom: HTMLElement) => HTMLElement;
|
||||
|
||||
/** 上下文菜单配置,可以是数组或返回数组的函数 */
|
||||
contextMenus: ContextMenu<T>[] | ((item: T) => ContextMenu<T>[]);
|
||||
/** 上下文菜单点击回调 */
|
||||
onContextMenu?: (item: T, menu: ContextMenu<T>) => void;
|
||||
|
||||
/** 弹出框容器 */
|
||||
popOverContainer?: React.ReactNode | (() => React.ReactNode);
|
||||
|
||||
/** 自定义样式 */
|
||||
style?: React.CSSProperties;
|
||||
/** 自定义类名 */
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 下拉菜单组件
|
||||
* 用于展示上下文菜单的弹出层组件
|
||||
*/
|
||||
export function DropdownContextMenus<T = Record<string, any>>({
|
||||
context,
|
||||
contextMenus,
|
||||
classnames: cx,
|
||||
onContextMenu,
|
||||
popOverContainer,
|
||||
getTargetElement,
|
||||
style,
|
||||
className
|
||||
}: DropdownContextMenusProps<T>) {
|
||||
const [menus, setMenus] = React.useState<ContextMenu<T>[]>([]);
|
||||
const domRef = React.useRef<HTMLElement>();
|
||||
|
||||
/** 处理菜单项点击事件 */
|
||||
const handleItemClick = React.useCallback(
|
||||
(e: React.MouseEvent) => {
|
||||
e.preventDefault();
|
||||
const index = e.currentTarget.getAttribute('data-index') || '';
|
||||
const menu = menus[parseInt(index, 10)];
|
||||
if (menu) {
|
||||
menu.onClick?.(context);
|
||||
onContextMenu?.(context, menu);
|
||||
}
|
||||
},
|
||||
[menus, onContextMenu, context]
|
||||
);
|
||||
|
||||
/** 渲染弹出层内容 */
|
||||
const popOverRender = React.useMemo(() => {
|
||||
return ({onClose}: any) => {
|
||||
return (
|
||||
<ul className={cx('ContextMenu-list')} onClick={onClose}>
|
||||
{Array.isArray(menus) && menus.length ? (
|
||||
menus.map((menu, index) => (
|
||||
<li
|
||||
key={`${index}`}
|
||||
className={cx('ContextMenu-item', menu.className, {
|
||||
[`is-${menu.level}`]: menu.level && menu.level !== 'normal',
|
||||
'is-disabled': menu.disabled
|
||||
})}
|
||||
>
|
||||
<a data-index={index} onClick={handleItemClick}>
|
||||
{menu.icon ? (
|
||||
<span className={cx('ContextMenu-itemIcon', menu.icon)} />
|
||||
) : null}
|
||||
{menu.label}
|
||||
</a>
|
||||
</li>
|
||||
))
|
||||
) : (
|
||||
<li
|
||||
onClick={handleItemClick}
|
||||
className={cx('ContextMenu-item is-disabled is-placeholder')}
|
||||
>
|
||||
<a>无</a>
|
||||
</li>
|
||||
)}
|
||||
</ul>
|
||||
);
|
||||
};
|
||||
}, [menus]);
|
||||
|
||||
/** 处理弹出层打开事件 */
|
||||
const handleOpen = React.useCallback(async () => {
|
||||
if (typeof contextMenus === 'function') {
|
||||
setMenus(await contextMenus(context));
|
||||
} else {
|
||||
setMenus(contextMenus);
|
||||
}
|
||||
}, [context, contextMenus]);
|
||||
|
||||
/** 获取弹出层容器 */
|
||||
const getContainer = React.useCallback(() => {
|
||||
return typeof popOverContainer === 'function'
|
||||
? popOverContainer()
|
||||
: popOverContainer || domRef.current;
|
||||
}, [popOverContainer]);
|
||||
|
||||
return (
|
||||
<PopOverContainer
|
||||
popOverRender={popOverRender}
|
||||
popOverContainer={getContainer}
|
||||
onOpen={handleOpen}
|
||||
>
|
||||
{({onClick, ref: targetRef, isOpened}) => {
|
||||
const filterRef = (ref: any) => {
|
||||
domRef.current = ref;
|
||||
if (ref && getTargetElement) {
|
||||
ref = getTargetElement(ref);
|
||||
}
|
||||
targetRef(ref);
|
||||
};
|
||||
|
||||
return (
|
||||
<a
|
||||
ref={filterRef}
|
||||
className={cx(
|
||||
'DropdownContextMenus',
|
||||
className,
|
||||
isOpened ? 'is-open' : ''
|
||||
)}
|
||||
onClick={onClick}
|
||||
style={style}
|
||||
>
|
||||
<Icon icon="ellipsis-v" />
|
||||
</a>
|
||||
);
|
||||
}}
|
||||
</PopOverContainer>
|
||||
);
|
||||
}
|
||||
|
||||
export default themeable(DropdownContextMenus);
|
||||
361
packages/amis-ui/src/components/Editor.tsx
Normal file
361
packages/amis-ui/src/components/Editor.tsx
Normal file
@@ -0,0 +1,361 @@
|
||||
/**
|
||||
* @file Editor
|
||||
* @description
|
||||
* @author fex
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import cx from 'classnames';
|
||||
import {ClassNamesFn, themeable, ThemeProps} from 'amis-core';
|
||||
import {autobind} from 'amis-core';
|
||||
import {Icon} from './icons';
|
||||
import {LocaleProps, localeable} from 'amis-core';
|
||||
|
||||
// 用于发布 sdk 版本的时候替换,因为不确定 sdk 版本怎么部署,而 worker 地址路径不可知。
|
||||
// 所以会被 fis3 替换成取相对的代码。
|
||||
function filterUrl(url: string) {
|
||||
return url;
|
||||
}
|
||||
if (!(window as any).MonacoEnvironment) {
|
||||
(window as any).MonacoEnvironment = {
|
||||
getWorkerUrl: function (moduleId: string, label: string) {
|
||||
let url = '/pkg/editor.worker.js';
|
||||
|
||||
if (label === 'json') {
|
||||
url = '/pkg/json.worker.js';
|
||||
} else if (label === 'css') {
|
||||
url = '/pkg/css.worker.js';
|
||||
} else if (label === 'html') {
|
||||
url = '/pkg/html.worker.js';
|
||||
} else if (label === 'typescript' || label === 'javascript') {
|
||||
url = '/pkg/ts.worker.js';
|
||||
}
|
||||
|
||||
url = filterUrl(url);
|
||||
|
||||
// url 有可能会插件替换成 cdn 地址,比如:fis3-prepackager-stand-alone-pack
|
||||
if (/^https?/.test(url)) {
|
||||
return `data:text/javascript;charset=utf-8,${encodeURIComponent(`
|
||||
importScripts('${url}');`)}
|
||||
`;
|
||||
}
|
||||
|
||||
return url;
|
||||
}
|
||||
};
|
||||
}
|
||||
export function monacoFactory(
|
||||
containerElement: HTMLElement,
|
||||
monaco: any,
|
||||
options: any
|
||||
) {
|
||||
return monaco.editor.create(containerElement, {
|
||||
'autoIndent': true,
|
||||
'formatOnType': true,
|
||||
'formatOnPaste': true,
|
||||
'selectOnLineNumbers': true,
|
||||
'scrollBeyondLastLine': false,
|
||||
'folding': true,
|
||||
'minimap': {
|
||||
enabled: false
|
||||
},
|
||||
'scrollbar': {
|
||||
alwaysConsumeMouseWheel: false
|
||||
},
|
||||
'bracketPairColorization.enabled': true,
|
||||
...options
|
||||
});
|
||||
}
|
||||
|
||||
export interface EditorBaseProps {
|
||||
value?: string;
|
||||
defaultValue?: string;
|
||||
width?: number | string;
|
||||
height?: number | string;
|
||||
onChange?: (value: string, event: any) => void;
|
||||
disabled?: boolean;
|
||||
language?: string;
|
||||
editorTheme?: string;
|
||||
allowFullscreen?: boolean;
|
||||
options: {
|
||||
[propName: string]: any;
|
||||
};
|
||||
context?: any;
|
||||
isDiffEditor?: boolean;
|
||||
placeholder?: string;
|
||||
onFocus?: (e: any) => void;
|
||||
onBlur?: (e: any) => void;
|
||||
editorDidMount?: (editor: any, monaco: any) => void;
|
||||
editorWillMount?: (monaco: any) => void;
|
||||
editorWillUnmount?: (editor: any, monaco: any) => void;
|
||||
editorFactory?: (conatainer: HTMLElement, monaco: any, options: any) => any;
|
||||
}
|
||||
|
||||
export interface EditorProps extends EditorBaseProps, LocaleProps, ThemeProps {}
|
||||
|
||||
export interface EditorState {
|
||||
isFullscreen?: boolean;
|
||||
innerWidth?: any;
|
||||
innerHeight?: any;
|
||||
}
|
||||
|
||||
export class Editor extends React.Component<EditorProps, EditorState> {
|
||||
static defaultProps = {
|
||||
language: 'javascript',
|
||||
editorTheme: 'vs',
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
allowFullscreen: false,
|
||||
options: {}
|
||||
};
|
||||
|
||||
state = {
|
||||
isFullscreen: false,
|
||||
innerWidth: 'auto',
|
||||
innerHeight: 'auto'
|
||||
};
|
||||
editor: any;
|
||||
container: any;
|
||||
currentValue: any;
|
||||
preventTriggerChangeEvent: boolean;
|
||||
disposes: Array<() => void> = [];
|
||||
constructor(props: EditorProps) {
|
||||
super(props);
|
||||
|
||||
this.wrapperRef = this.wrapperRef.bind(this);
|
||||
this.getDom = this.getDom.bind(this);
|
||||
this.currentValue = props.value;
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps: EditorProps) {
|
||||
if (
|
||||
this.props.value !== this.currentValue &&
|
||||
this.editor &&
|
||||
!this.props.isDiffEditor
|
||||
) {
|
||||
let value = String(this.props.value);
|
||||
|
||||
if (this.props.language === 'json') {
|
||||
try {
|
||||
value = JSON.stringify(JSON.parse(value), null, 2);
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
this.preventTriggerChangeEvent = true;
|
||||
const eidtor = this.editor.getModifiedEditor
|
||||
? this.editor.getModifiedEditor()
|
||||
: this.editor;
|
||||
const model = eidtor.getModel();
|
||||
eidtor.pushUndoStop();
|
||||
// pushEditOperations says it expects a cursorComputer, but doesn't seem to need one.
|
||||
model.pushEditOperations(
|
||||
[],
|
||||
[
|
||||
{
|
||||
range: model.getFullModelRange(),
|
||||
text: value
|
||||
}
|
||||
]
|
||||
);
|
||||
eidtor.pushUndoStop();
|
||||
this.preventTriggerChangeEvent = false;
|
||||
}
|
||||
|
||||
if (
|
||||
this.props.options.readOnly !== prevProps.options.readOnly &&
|
||||
this.editor
|
||||
) {
|
||||
this.editor.updateOptions?.(this.props.options);
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
if (this.editor) {
|
||||
const context = this.props.context || window;
|
||||
const monaco = context.monaco || (window as any).monaco;
|
||||
const editorWillUnmount = this.props.editorWillUnmount;
|
||||
editorWillUnmount && editorWillUnmount(this.editor, monaco);
|
||||
}
|
||||
this.disposes.forEach(dispose => dispose());
|
||||
this.disposes = [];
|
||||
this.editor?.dispose();
|
||||
}
|
||||
|
||||
wrapperRef(ref: any) {
|
||||
this.container = ref;
|
||||
if (ref) {
|
||||
this.loadMonaco();
|
||||
} else {
|
||||
try {
|
||||
this.disposes.forEach(dispose => dispose());
|
||||
this.disposes = [];
|
||||
if (this.editor) {
|
||||
this.editor.getModel().dispose();
|
||||
this.editor.dispose();
|
||||
}
|
||||
this.editor = null;
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getDom() {
|
||||
return this.container;
|
||||
}
|
||||
|
||||
loadMonaco() {
|
||||
// 由于 require.config({'vs/nls': { availableLanguages: { '*': 'xxxx' }}}) 只能在初始化之前设置有用,所以这里只能用全局变量的方式来设置。
|
||||
// 另外此方式只是针对 jssdk 和平台有效,对于其他方式还需要再想想。
|
||||
(window as any).__amis_monaco_editor_locale = this.props.locale;
|
||||
import('monaco-editor').then(monaco => this.initMonaco(monaco));
|
||||
}
|
||||
|
||||
initMonaco(monaco: any) {
|
||||
let value =
|
||||
this.props.value !== null ? this.props.value : this.props.defaultValue;
|
||||
const {language, editorTheme, options, editorFactory} = this.props;
|
||||
const containerElement = this.container;
|
||||
if (!containerElement) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Before initializing monaco editor
|
||||
this.editorWillMount(monaco);
|
||||
|
||||
if (this.props.language === 'json') {
|
||||
try {
|
||||
value = JSON.stringify(
|
||||
typeof value === 'string' ? JSON.parse(value) : value,
|
||||
null,
|
||||
2
|
||||
);
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
const factory = editorFactory || monacoFactory;
|
||||
this.editor = factory(containerElement, monaco, {
|
||||
...options,
|
||||
readOnly: this.props.disabled,
|
||||
automaticLayout: true,
|
||||
value,
|
||||
language,
|
||||
editorTheme,
|
||||
theme: editorTheme
|
||||
});
|
||||
|
||||
// json 默认开启验证。
|
||||
monaco.languages.json?.jsonDefaults.setDiagnosticsOptions({
|
||||
enableSchemaRequest: true,
|
||||
validate: true,
|
||||
allowComments: true,
|
||||
...monaco.languages.json?.jsonDefaults.diagnosticsOptions
|
||||
});
|
||||
|
||||
// After initializing monaco editor
|
||||
this.editorDidMount(this.editor, monaco);
|
||||
}
|
||||
|
||||
editorWillMount(monaco: any) {
|
||||
const {editorWillMount} = this.props;
|
||||
editorWillMount && editorWillMount(monaco);
|
||||
}
|
||||
|
||||
editorDidMount(editor: any, monaco: any) {
|
||||
const {editorDidMount, onChange, onFocus, onBlur} = this.props;
|
||||
editorDidMount && editorDidMount(editor, monaco);
|
||||
editor.onDidChangeModelContent &&
|
||||
this.disposes.push(
|
||||
editor.onDidChangeModelContent((event: any) => {
|
||||
const value = editor.getValue();
|
||||
// Always refer to the latest value
|
||||
this.currentValue = value;
|
||||
|
||||
// Only invoking when user input changed
|
||||
if (!this.preventTriggerChangeEvent && onChange) {
|
||||
onChange(value, event);
|
||||
}
|
||||
}).dispose
|
||||
);
|
||||
onFocus &&
|
||||
editor.onDidFocusEditorWidget &&
|
||||
this.disposes.push(editor.onDidFocusEditorWidget(onFocus).dispose);
|
||||
onBlur &&
|
||||
editor.onDidBlurEditorWidget &&
|
||||
this.disposes.push(editor.onDidBlurEditorWidget(onBlur).dispose);
|
||||
|
||||
const {width = 'auto', height = 'auto'} =
|
||||
this?.editor?._configuration?._elementSizeObserver ?? {};
|
||||
|
||||
this.setState({innerHeight: height, innerWidth: width});
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleFullscreenModeChange() {
|
||||
this.setState(
|
||||
{isFullscreen: !this.state.isFullscreen},
|
||||
() =>
|
||||
// 退出全屏模式后需要resize一下editor的宽高,避免溢出父元素
|
||||
!this.state.isFullscreen &&
|
||||
this.editor.layout({
|
||||
width: this.state.innerWidth,
|
||||
height: this.state.innerHeight
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
className,
|
||||
width,
|
||||
height,
|
||||
translate: __,
|
||||
placeholder,
|
||||
classnames: cx,
|
||||
value
|
||||
} = this.props;
|
||||
let style = {...(this.props.style || {})};
|
||||
|
||||
style.width = width;
|
||||
style.height = height;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx(
|
||||
`MonacoEditor`,
|
||||
{'is-fullscreen': this.state.isFullscreen},
|
||||
className
|
||||
)}
|
||||
style={style}
|
||||
ref={this.wrapperRef}
|
||||
>
|
||||
{this.editor && placeholder && !value ? (
|
||||
<span className={cx('MonacoEditor-placeholder')}>{placeholder}</span>
|
||||
) : null}
|
||||
{this.editor && this.props.allowFullscreen ? (
|
||||
<div className={cx(`MonacoEditor-header`)}>
|
||||
<a
|
||||
className={cx('Modal-close', `MonacoEditor-fullscreen`)}
|
||||
data-tooltip={
|
||||
this.state.isFullscreen
|
||||
? __('Editor.exitFullscreen')
|
||||
: __('Editor.fullscreen')
|
||||
}
|
||||
data-position="left"
|
||||
onClick={this.handleFullscreenModeChange}
|
||||
>
|
||||
<Icon
|
||||
icon={this.state.isFullscreen ? 'compress-alt' : 'expand-alt'}
|
||||
className="icon"
|
||||
/>
|
||||
</a>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(localeable(Editor, ['getDom']), ['getDom']);
|
||||
140
packages/amis-ui/src/components/Form.tsx
Normal file
140
packages/amis-ui/src/components/Form.tsx
Normal file
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* @file 给组件用的,渲染器里面不要用这个
|
||||
*/
|
||||
import React from 'react';
|
||||
import {noop, themeable, ThemeProps} from 'amis-core';
|
||||
import {useForm, UseFormReturn, FormProvider} from 'react-hook-form';
|
||||
import {useValidationResolver} from '../hooks/use-validation-resolver';
|
||||
import {localeable, LocaleProps} from 'amis-core';
|
||||
import debounce from 'lodash/debounce';
|
||||
import {isObjectShallowModified} from 'amis-core';
|
||||
|
||||
export type FormRef = React.MutableRefObject<
|
||||
| {
|
||||
submit: () => void;
|
||||
}
|
||||
| undefined
|
||||
>;
|
||||
|
||||
export interface FormProps extends ThemeProps, LocaleProps {
|
||||
defaultValue?: any;
|
||||
value?: any;
|
||||
autoSubmit?: boolean;
|
||||
onValidate?: (errors: any, values: any) => Promise<void>;
|
||||
onChange?: (value: any) => void;
|
||||
onSubmit?: (value: any) => void;
|
||||
forwardRef?: FormRef;
|
||||
children?: (
|
||||
methods: UseFormReturn & {
|
||||
onSubmit: (value: any) => void;
|
||||
}
|
||||
) => JSX.Element | null;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function Form(props: FormProps) {
|
||||
const {classnames: cx, className, autoSubmit, value, onChange} = props;
|
||||
const defaultValues = props.value ?? props.defaultValue;
|
||||
const methods = useForm({
|
||||
defaultValues: defaultValues,
|
||||
resolver: useValidationResolver(props.translate, props.onValidate)
|
||||
});
|
||||
let onSubmit = React.useRef<(data: any) => void>(
|
||||
methods.handleSubmit(props.onSubmit || noop)
|
||||
);
|
||||
if (autoSubmit) {
|
||||
onSubmit = React.useRef(
|
||||
debounce(methods.handleSubmit(props.onSubmit || noop), 250, {
|
||||
leading: false,
|
||||
trailing: true
|
||||
})
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
const subscriber = methods.watch(onSubmit.current);
|
||||
return () => {
|
||||
subscriber.unsubscribe();
|
||||
// debounce 后需要销毁
|
||||
(onSubmit.current as any)?.cancel?.();
|
||||
};
|
||||
}, []);
|
||||
}
|
||||
React.useEffect(() => {
|
||||
if (value && isObjectShallowModified(value, methods.getValues(), false)) {
|
||||
Object.keys(value).forEach(key => {
|
||||
methods.setValue(key, value[key]);
|
||||
});
|
||||
}
|
||||
}, [value]);
|
||||
if (onChange) {
|
||||
React.useEffect(() => {
|
||||
const subscriber = methods.watch((value, info) => {
|
||||
onChange({...defaultValues, ...value});
|
||||
});
|
||||
return () => subscriber.unsubscribe();
|
||||
}, [onChange]);
|
||||
}
|
||||
|
||||
React.useImperativeHandle(
|
||||
props.forwardRef,
|
||||
() => {
|
||||
return {
|
||||
submit: () =>
|
||||
new Promise<any>(resolve => {
|
||||
methods.handleSubmit(
|
||||
values => {
|
||||
props.onSubmit?.(values);
|
||||
resolve(values);
|
||||
},
|
||||
e => resolve(e.customValidate?.message || false)
|
||||
)();
|
||||
}),
|
||||
validate: () =>
|
||||
new Promise<any>(resolve => {
|
||||
methods.handleSubmit(
|
||||
() => {
|
||||
resolve('');
|
||||
},
|
||||
e =>
|
||||
resolve(
|
||||
e.customValidate?.message ||
|
||||
props.translate('Form.validateFailed')
|
||||
)
|
||||
)();
|
||||
})
|
||||
};
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
return (
|
||||
<FormProvider {...methods}>
|
||||
<form
|
||||
className={cx('Form', className)}
|
||||
onSubmit={onSubmit.current}
|
||||
noValidate
|
||||
>
|
||||
{/* 实现回车自动提交 */}
|
||||
<input type="submit" style={{display: 'none'}} />
|
||||
{props.children?.({
|
||||
...methods,
|
||||
onSubmit: onSubmit.current
|
||||
})}
|
||||
</form>
|
||||
</FormProvider>
|
||||
);
|
||||
}
|
||||
|
||||
const ThemedForm = themeable(localeable(Form));
|
||||
type ThemedFormProps = Omit<
|
||||
JSX.LibraryManagedAttributes<
|
||||
typeof ThemedForm,
|
||||
React.ComponentProps<typeof ThemedForm>
|
||||
>,
|
||||
'children'
|
||||
> &
|
||||
Pick<FormProps, 'children'>;
|
||||
|
||||
export default React.forwardRef((props: ThemedFormProps, ref: FormRef) => (
|
||||
<ThemedForm {...props} forwardRef={ref} />
|
||||
));
|
||||
213
packages/amis-ui/src/components/FormField.tsx
Normal file
213
packages/amis-ui/src/components/FormField.tsx
Normal file
@@ -0,0 +1,213 @@
|
||||
/**
|
||||
* @file 给组件用的,渲染器里面不要用这个
|
||||
*/
|
||||
import React from 'react';
|
||||
import {localeable, themeable, ThemeProps, LocaleProps} from 'amis-core';
|
||||
import {
|
||||
ControllerProps as ReactHookFormControllerProps,
|
||||
Controller as ReactHookFormController,
|
||||
RegisterOptions
|
||||
} from 'react-hook-form';
|
||||
import method from 'lodash/method';
|
||||
|
||||
export interface FormFieldProps extends LocaleProps, ThemeProps {
|
||||
mode?: 'normal' | 'horizontal';
|
||||
horizontal?: {
|
||||
left?: number;
|
||||
right?: number;
|
||||
leftFixed?: boolean | number | 'xs' | 'sm' | 'md' | 'lg';
|
||||
justify?: boolean; // 两端对齐
|
||||
};
|
||||
label?: string | boolean;
|
||||
labelAlign?: 'left' | 'right';
|
||||
labelClassName?: string;
|
||||
description?: string;
|
||||
isRequired?: boolean;
|
||||
hasError?: boolean;
|
||||
errors?: string | Array<string>;
|
||||
children?: React.ReactNode | Array<React.ReactNode>;
|
||||
}
|
||||
|
||||
function FormField(props: FormFieldProps) {
|
||||
const {
|
||||
mode,
|
||||
children,
|
||||
classnames: cx,
|
||||
className,
|
||||
style,
|
||||
hasError,
|
||||
isRequired,
|
||||
label,
|
||||
labelAlign,
|
||||
labelClassName,
|
||||
description
|
||||
} = props;
|
||||
|
||||
const errors = Array.isArray(props.errors)
|
||||
? props.errors
|
||||
: props.errors
|
||||
? [props.errors]
|
||||
: [];
|
||||
|
||||
if (mode === 'horizontal') {
|
||||
const horizontal = props.horizontal || {
|
||||
leftFixed: true
|
||||
};
|
||||
return (
|
||||
<div
|
||||
data-role="form-item"
|
||||
className={cx(`Form-item Form-item--horizontal`, className, {
|
||||
'is-error': hasError,
|
||||
[`is-required`]: isRequired,
|
||||
'Form-item--horizontal-justify': horizontal.justify
|
||||
})}
|
||||
// style={style}
|
||||
>
|
||||
{label !== false ? (
|
||||
<label
|
||||
className={cx(
|
||||
`Form-label`,
|
||||
{
|
||||
[`Form-itemColumn--${
|
||||
typeof horizontal.leftFixed === 'string'
|
||||
? horizontal.leftFixed
|
||||
: 'normal'
|
||||
}`]: horizontal.leftFixed,
|
||||
[`Form-itemColumn--${horizontal.left}`]: !horizontal.leftFixed,
|
||||
'Form-label--left': labelAlign === 'left'
|
||||
},
|
||||
labelClassName
|
||||
)}
|
||||
>
|
||||
<span>
|
||||
{label}
|
||||
{isRequired && label ? (
|
||||
<span className={cx(`Form-star`)}>*</span>
|
||||
) : null}
|
||||
</span>
|
||||
</label>
|
||||
) : null}
|
||||
|
||||
<div
|
||||
className={cx(`Form-value`, {
|
||||
// [`Form-itemColumn--offset${getWidthRate(horizontal.offset)}`]: !label && label !== false,
|
||||
[`Form-itemColumn--${horizontal.right}`]:
|
||||
!horizontal.leftFixed &&
|
||||
!!horizontal.right &&
|
||||
horizontal.right !== 12 - horizontal.left!
|
||||
})}
|
||||
>
|
||||
{children}
|
||||
|
||||
{hasError && errors.length ? (
|
||||
<ul className={cx(`Form-feedback`)}>
|
||||
{errors.map((msg: string, key: number) => (
|
||||
<li key={key}>{msg}</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
|
||||
{description ? (
|
||||
<div className={cx(`Form-description`)}>{description}</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
data-role="form-item"
|
||||
className={cx(`Form-item Form-item--normal`, className, {
|
||||
'is-error': hasError,
|
||||
[`is-required`]: isRequired
|
||||
})}
|
||||
// style={style}
|
||||
>
|
||||
{label ? (
|
||||
<label className={cx(`Form-label`, labelClassName)}>
|
||||
<span>
|
||||
{label}
|
||||
{isRequired && label ? (
|
||||
<span className={cx(`Form-star`)}>*</span>
|
||||
) : null}
|
||||
</span>
|
||||
</label>
|
||||
) : null}
|
||||
|
||||
{children}
|
||||
|
||||
{hasError && errors.length ? (
|
||||
<ul className={cx(`Form-feedback`)}>
|
||||
{errors.map((msg: string, key: number) => (
|
||||
<li key={key}>{msg}</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
|
||||
{description ? (
|
||||
<div className={cx(`Form-description`)}>{description}</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ThemedFormField = themeable(localeable(React.memo(FormField)));
|
||||
|
||||
export default ThemedFormField;
|
||||
|
||||
export interface ControllerProps
|
||||
extends ReactHookFormControllerProps,
|
||||
Omit<FormFieldProps, keyof ThemeProps | keyof LocaleProps> {
|
||||
rules?: Omit<
|
||||
RegisterOptions,
|
||||
'valueAsNumber' | 'valueAsDate' | 'setValueAs' | 'disabled'
|
||||
> & {
|
||||
[propName: string]: any;
|
||||
};
|
||||
|
||||
// combo 里面有用
|
||||
columnClassName?: string;
|
||||
|
||||
className?: string;
|
||||
|
||||
/**
|
||||
* 配置成 false 则不包裹
|
||||
*/
|
||||
wrap?: boolean;
|
||||
}
|
||||
export function Controller(props: ControllerProps) {
|
||||
const {render, name, shouldUnregister, defaultValue, control, wrap, ...rest} =
|
||||
props;
|
||||
const rules = React.useMemo(() => {
|
||||
const rules = {...props.rules};
|
||||
|
||||
if (props.isRequired) {
|
||||
rules.required = true;
|
||||
}
|
||||
return rules;
|
||||
}, [props.rules, props.isRequired]);
|
||||
|
||||
return (
|
||||
<ReactHookFormController
|
||||
name={name || ''}
|
||||
rules={rules}
|
||||
shouldUnregister={shouldUnregister}
|
||||
defaultValue={defaultValue}
|
||||
control={control}
|
||||
render={methods =>
|
||||
wrap === false ? (
|
||||
render(methods)
|
||||
) : (
|
||||
<ThemedFormField
|
||||
{...rest}
|
||||
hasError={!!methods.fieldState.error}
|
||||
errors={methods.fieldState.error?.message}
|
||||
>
|
||||
{render(methods)}
|
||||
</ThemedFormField>
|
||||
)
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
2
packages/amis-ui/src/components/FormulaPicker.tsx
Normal file
2
packages/amis-ui/src/components/FormulaPicker.tsx
Normal file
@@ -0,0 +1,2 @@
|
||||
import FormulaPicker from './formula/Picker';
|
||||
export default FormulaPicker;
|
||||
243
packages/amis-ui/src/components/GaodeMapPicker.tsx
Normal file
243
packages/amis-ui/src/components/GaodeMapPicker.tsx
Normal file
@@ -0,0 +1,243 @@
|
||||
import React from 'react';
|
||||
import {ClassNamesFn, themeable} from 'amis-core';
|
||||
import {loadScript, loadStyle, autobind, uuid} from 'amis-core';
|
||||
import debounce from 'lodash/debounce';
|
||||
import {Icon} from './icons';
|
||||
|
||||
declare const AMap: any;
|
||||
|
||||
interface MapPickerProps {
|
||||
ak: string;
|
||||
coordinatesType: string;
|
||||
classnames: ClassNamesFn;
|
||||
classPrefix: string;
|
||||
value?: {
|
||||
address: string;
|
||||
lat: number;
|
||||
lng: number;
|
||||
city?: string;
|
||||
};
|
||||
onChange?: (value: any) => void;
|
||||
}
|
||||
|
||||
interface LocationItem {
|
||||
title?: string;
|
||||
address: string;
|
||||
lat: number;
|
||||
lng: number;
|
||||
city?: string;
|
||||
}
|
||||
|
||||
interface MapPickerState {
|
||||
inputValue: string;
|
||||
locIndex?: number;
|
||||
locs: Array<LocationItem>;
|
||||
sugs: Array<string>;
|
||||
}
|
||||
|
||||
export class BaiduMapPicker extends React.Component<
|
||||
MapPickerProps,
|
||||
MapPickerState
|
||||
> {
|
||||
state: MapPickerState = {
|
||||
inputValue: '',
|
||||
locs: [],
|
||||
locIndex: -1,
|
||||
sugs: []
|
||||
};
|
||||
|
||||
id = uuid();
|
||||
mapRef: React.RefObject<HTMLDivElement> = React.createRef();
|
||||
resultListRef: React.RefObject<HTMLDivElement> = React.createRef();
|
||||
placeholderInput?: HTMLInputElement;
|
||||
map: any;
|
||||
ac: any;
|
||||
geocoder: any;
|
||||
placeSearch: any;
|
||||
mark: any;
|
||||
geolocation: any;
|
||||
|
||||
search = debounce(
|
||||
() => {
|
||||
if (this.state.inputValue) {
|
||||
this.placeSearch?.search(this.state.inputValue);
|
||||
} else {
|
||||
this.setState({
|
||||
sugs: []
|
||||
});
|
||||
}
|
||||
},
|
||||
250,
|
||||
{
|
||||
trailing: true,
|
||||
leading: false
|
||||
}
|
||||
);
|
||||
convertor: any;
|
||||
|
||||
componentDidMount() {
|
||||
if ((window as any).AMap) {
|
||||
this.initMap();
|
||||
} else {
|
||||
loadStyle('https://cache.amap.com/lbs/static/main1119.css')
|
||||
loadScript(
|
||||
`//webapi.amap.com/maps?v=2.0&key=${this.props.ak}`
|
||||
).then(this.initMap);
|
||||
}
|
||||
}
|
||||
|
||||
@autobind
|
||||
async initMap() {
|
||||
const map = new AMap.Map(this.mapRef.current, {
|
||||
resizeEnable: true,
|
||||
zoom: 13,
|
||||
});
|
||||
this.map = map;
|
||||
map.plugin(["AMap.Geocoder"], () => {
|
||||
//加载地理编码插件
|
||||
this.geocoder = new AMap.Geocoder({
|
||||
radius: 1000, //以已知坐标为中心点,radius为半径,返回范围内兴趣点和道路信息
|
||||
extensions: "all", //返回地址描述以及附近兴趣点和道路信息,默认“base”
|
||||
});
|
||||
});
|
||||
|
||||
map.plugin('AMap.Geolocation', () => {
|
||||
this.geolocation = new AMap.Geolocation({
|
||||
enableHighAccuracy: true,//是否使用高精度定位,默认:true
|
||||
timeout: 10000, //超过10秒后停止定位,默认:无穷大
|
||||
maximumAge: 0, //定位结果缓存0毫秒,默认:0
|
||||
convert: true //自动偏移坐标,偏移后的坐标为高德坐标,默认:true
|
||||
});
|
||||
map.addControl(this.geolocation);
|
||||
});
|
||||
|
||||
AMap.plugin(["AMap.PlaceSearch"], () => {
|
||||
//构造地点查询类
|
||||
this.placeSearch = new AMap.PlaceSearch({
|
||||
pageSize: 5, // 单页显示结果条数
|
||||
pageIndex: 1, // 页码
|
||||
map: map, // 展现结果的地图实例
|
||||
panel: this.resultListRef.current, // 结果列表将在此容器中进行展示。
|
||||
autoFitView: true, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
|
||||
});
|
||||
|
||||
this.placeSearch.on("selectChanged", (e: any) => {
|
||||
let poi = e.selected.data.location;
|
||||
this.syncLocation({
|
||||
lng: poi.lng,
|
||||
lat: poi.lat,
|
||||
address: e.selected.data.address,
|
||||
city: e.selected.data.cityname,
|
||||
});
|
||||
});
|
||||
})
|
||||
|
||||
if (this.props.value) {
|
||||
map.setZoomAndCenter(13, [this.props.value.lng, this.props.value.lat]);
|
||||
this.mark = new AMap.Marker({
|
||||
position: [this.props.value.lng, this.props.value.lat],
|
||||
});
|
||||
this.mark.setMap(map);
|
||||
} else {
|
||||
this.geolocation.getCurrentPosition(function (status: any,result: any) {});
|
||||
}
|
||||
|
||||
map.on("click", (e: any) => {
|
||||
map.setCenter(e.lnglat);
|
||||
let marker = new AMap.Marker({
|
||||
position: [e.lnglat.lng, e.lnglat.lat],
|
||||
});
|
||||
marker.setMap(map);
|
||||
if (this.mark) {
|
||||
this.mark.setMap(null);
|
||||
}
|
||||
this.mark = marker;
|
||||
this.syncLocation(e.lnglat);
|
||||
});
|
||||
}
|
||||
|
||||
@autobind
|
||||
async syncLocation (lnglat: {
|
||||
lng: number;
|
||||
lat: number;
|
||||
address?: string;
|
||||
city?: string;
|
||||
}) {
|
||||
new Promise((resolve, reject) => {
|
||||
if (lnglat.address && lnglat.city) {
|
||||
let data = {
|
||||
lng: lnglat.lng,
|
||||
lat: lnglat.lat,
|
||||
address: lnglat.address,
|
||||
city: lnglat.city,
|
||||
vendor: "gaode",
|
||||
}
|
||||
if (this.props?.onChange) this.props?.onChange(data)
|
||||
}
|
||||
this.geocoder.getAddress(lnglat, (status: any, result: any) => {
|
||||
if (status === "complete" && result.info === "OK") {
|
||||
resolve({ status, result });
|
||||
let data = {
|
||||
lng: lnglat.lng,
|
||||
lat: lnglat.lat,
|
||||
address: result.regeocode.formattedAddress,
|
||||
city:
|
||||
result.regeocode.addressComponent.city ||
|
||||
result.regeocode.addressComponent.province ||
|
||||
result.regeocode.addressComponent.district,
|
||||
vendor: "gaode",
|
||||
};
|
||||
if (this.props?.onChange) this.props?.onChange(data)
|
||||
} else {
|
||||
reject({ status, result });
|
||||
}
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleChange(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
this.setState(
|
||||
{
|
||||
inputValue: e.currentTarget.value
|
||||
},
|
||||
this.search
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {classnames: cx} = this.props;
|
||||
const {locIndex, locs, inputValue, sugs} = this.state;
|
||||
// const hasSug = Array.isArray(sugs) && sugs.length;
|
||||
|
||||
return (
|
||||
<div className={cx('MapPicker')}>
|
||||
<div className={cx('MapPicker-search TextControl-control')}>
|
||||
<div className={cx('TextControl-input')}>
|
||||
<input
|
||||
onChange={this.handleChange}
|
||||
value={inputValue}
|
||||
placeholder="搜索地点"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
ref={this.mapRef}
|
||||
className={cx('MapPicker-map', {
|
||||
invisible: false
|
||||
})}
|
||||
/>
|
||||
|
||||
<div
|
||||
ref={this.resultListRef}
|
||||
className={cx('MapPicker-result', {
|
||||
invisible: false
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(BaiduMapPicker);
|
||||
234
packages/amis-ui/src/components/GridNav.tsx
Normal file
234
packages/amis-ui/src/components/GridNav.tsx
Normal file
@@ -0,0 +1,234 @@
|
||||
/**
|
||||
* @file GridNav
|
||||
* @description 金刚位宫格导航 参考react-vant
|
||||
*/
|
||||
|
||||
import React, {useMemo} from 'react';
|
||||
import {ClassName, ClassNamesFn} from 'amis-core';
|
||||
import {Badge, BadgeProps} from './Badge';
|
||||
|
||||
export type GridNavDirection = 'horizontal' | 'vertical';
|
||||
|
||||
export interface GridNavProps {
|
||||
/** 是否将格子固定为正方形 */
|
||||
square?: boolean;
|
||||
/** 是否将格子内容居中显示 */
|
||||
center?: boolean;
|
||||
/** 是否显示边框 */
|
||||
border?: boolean;
|
||||
/** 格子之间的间距,默认单位为`px` */
|
||||
gutter?: number;
|
||||
/** 是否调换图标和文本的位置 */
|
||||
reverse?: boolean;
|
||||
/** 图标占比,默认单位为`%` */
|
||||
iconRatio?: number;
|
||||
/** 格子内容排列的方向,可选值为 `horizontal` */
|
||||
direction?: GridNavDirection;
|
||||
/** 列数 */
|
||||
columnNum?: number;
|
||||
className?: string;
|
||||
itemClassName?: ClassName;
|
||||
classnames: ClassNamesFn;
|
||||
style?: React.CSSProperties;
|
||||
children?: React.ReactNode | Array<React.ReactNode>;
|
||||
}
|
||||
|
||||
export interface GridNavItemProps {
|
||||
/** 图标右上角徽标 */
|
||||
badge?: BadgeProps;
|
||||
/** 文字 */
|
||||
text?: string | React.ReactNode;
|
||||
/** 图标名称或图片链接 */
|
||||
icon?: string | React.ReactNode;
|
||||
className?: ClassName;
|
||||
style?: React.CSSProperties;
|
||||
contentClassName?: ClassName;
|
||||
contentStyle?: React.CSSProperties;
|
||||
children?: React.ReactNode;
|
||||
classnames: ClassNamesFn;
|
||||
onClick?: (event: React.MouseEvent) => void;
|
||||
}
|
||||
|
||||
type InternalProps = {
|
||||
parent?: GridNavProps;
|
||||
index?: number;
|
||||
};
|
||||
|
||||
function addUnit(value?: string | number): string | undefined {
|
||||
if (value === undefined || value === null) {
|
||||
return undefined;
|
||||
}
|
||||
value = String(value);
|
||||
return /^\d+(\.\d+)?$/.test(value) ? `${value}px` : value;
|
||||
}
|
||||
|
||||
export const GridNavItem: React.FC<GridNavItemProps & InternalProps> = ({
|
||||
children,
|
||||
classnames: cx,
|
||||
className,
|
||||
style,
|
||||
...props
|
||||
}) => {
|
||||
const {index = 0, parent} = props;
|
||||
if (!parent) {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(
|
||||
'[React Vant] <GridNavItem> must be a child component of <GridNav>.'
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const rootStyle = useMemo(() => {
|
||||
const {square, gutter, columnNum = 4} = parent;
|
||||
const percent = `${100 / +columnNum}%`;
|
||||
const internalStyle: React.CSSProperties = {
|
||||
...style,
|
||||
flexBasis: percent
|
||||
};
|
||||
|
||||
if (square) {
|
||||
internalStyle.paddingTop = percent;
|
||||
} else if (gutter) {
|
||||
const gutterValue = addUnit(gutter);
|
||||
internalStyle.paddingRight = gutterValue;
|
||||
|
||||
if (index >= columnNum) {
|
||||
internalStyle.marginTop = gutterValue;
|
||||
}
|
||||
}
|
||||
|
||||
return internalStyle;
|
||||
}, [parent.style, parent.gutter, parent.columnNum]);
|
||||
|
||||
const contentStyle = useMemo(() => {
|
||||
const {square, gutter} = parent;
|
||||
|
||||
if (square && gutter) {
|
||||
const gutterValue = addUnit(gutter);
|
||||
return {
|
||||
...props.contentStyle,
|
||||
right: gutterValue,
|
||||
bottom: gutterValue,
|
||||
height: 'auto'
|
||||
};
|
||||
}
|
||||
return props.contentStyle;
|
||||
}, [parent.gutter, parent.columnNum, props.contentStyle]);
|
||||
|
||||
const renderIcon = () => {
|
||||
const ratio = parent.iconRatio || 60;
|
||||
if (typeof props.icon === 'string') {
|
||||
if (props.badge) {
|
||||
return (
|
||||
<Badge {...props.badge}>
|
||||
<div className={cx('GridNavItem-image')}>
|
||||
<img src={props.icon} style={{width: ratio + '%'}} />
|
||||
</div>
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className={cx('GridNavItem-image')}>
|
||||
<img src={props.icon} style={{width: ratio + '%'}} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (React.isValidElement(props.icon)) {
|
||||
return <Badge {...(props.badge as BadgeProps)}>{props.icon}</Badge>;
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const renderText = () => {
|
||||
if (React.isValidElement(props.text)) {
|
||||
return props.text;
|
||||
}
|
||||
if (props.text) {
|
||||
return <span className={cx('GridNavItem-text')}>{props.text}</span>;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const renderContent = () => {
|
||||
if (children) {
|
||||
return children;
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{renderIcon()}
|
||||
{renderText()}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
const {center, border, square, gutter, reverse, direction} = parent;
|
||||
|
||||
const prefix = 'GridNavItem-content';
|
||||
const classes = cx(`${prefix} ${props.contentClassName || ''}`, {
|
||||
[`${prefix}--${direction}`]: !!direction,
|
||||
[`${prefix}--center`]: center,
|
||||
[`${prefix}--square`]: square,
|
||||
[`${prefix}--reverse`]: reverse,
|
||||
[`${prefix}--clickable`]: !!props.onClick,
|
||||
[`${prefix}--surround`]: border && gutter,
|
||||
[`${prefix}--border u-hairline`]: border
|
||||
});
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx(className, {'GridNavItem--square': square})}
|
||||
style={rootStyle}
|
||||
>
|
||||
<div
|
||||
role={props.onClick ? 'button' : undefined}
|
||||
className={classes}
|
||||
style={contentStyle}
|
||||
onClick={props.onClick}
|
||||
>
|
||||
{renderContent()}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const GridNav: React.FC<GridNavProps> = ({
|
||||
children,
|
||||
className,
|
||||
classnames: cx,
|
||||
itemClassName,
|
||||
style,
|
||||
...props
|
||||
}) => {
|
||||
return (
|
||||
<div
|
||||
style={{paddingLeft: addUnit(props.gutter), ...style}}
|
||||
className={cx(`GridNav ${className || ''}`, {
|
||||
'GridNav-top u-hairline': props.border && !props.gutter
|
||||
})}
|
||||
>
|
||||
{React.Children.toArray(children)
|
||||
.filter(Boolean)
|
||||
.map((child: React.ReactElement, index: number) =>
|
||||
React.cloneElement(child, {
|
||||
index,
|
||||
parent: props,
|
||||
className: itemClassName,
|
||||
classnames: cx
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
GridNav.defaultProps = {
|
||||
direction: 'vertical',
|
||||
center: true,
|
||||
border: true,
|
||||
columnNum: 4
|
||||
};
|
||||
|
||||
export default GridNav;
|
||||
3
packages/amis-ui/src/components/GridNavItem.tsx
Normal file
3
packages/amis-ui/src/components/GridNavItem.tsx
Normal file
@@ -0,0 +1,3 @@
|
||||
import {GridNavItem} from './GridNav';
|
||||
|
||||
export default GridNavItem;
|
||||
316
packages/amis-ui/src/components/GroupedSelection.tsx
Normal file
316
packages/amis-ui/src/components/GroupedSelection.tsx
Normal file
@@ -0,0 +1,316 @@
|
||||
import React from 'react';
|
||||
import {uncontrollable, flattenTree, TestIdBuilder} from 'amis-core';
|
||||
|
||||
import {BaseSelection, BaseSelectionProps} from './Selection';
|
||||
import {themeable} from 'amis-core';
|
||||
import Checkbox from './Checkbox';
|
||||
import {Option} from './Select';
|
||||
import {localeable} from 'amis-core';
|
||||
import VirtualList, {AutoSizer} from './virtual-list';
|
||||
|
||||
export class GroupedSelection extends BaseSelection<BaseSelectionProps> {
|
||||
valueArray: Array<Option>;
|
||||
|
||||
renderOption(
|
||||
option: Option,
|
||||
index: number,
|
||||
key: string = `${index}`,
|
||||
styles: object = {},
|
||||
testIdBuilder?: TestIdBuilder
|
||||
): JSX.Element {
|
||||
const {
|
||||
disabled,
|
||||
classnames: cx,
|
||||
itemRender,
|
||||
multiple,
|
||||
labelField = 'label'
|
||||
} = this.props;
|
||||
|
||||
const tBuilder = testIdBuilder?.getChild(index);
|
||||
if (Array.isArray(option.children)) {
|
||||
if (!option[labelField]) {
|
||||
return (
|
||||
<>
|
||||
{option.children.map((child: Option, index: number) =>
|
||||
this.renderOption(child, index, `${index}`, {}, tBuilder)
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
className={cx('GroupedSelection-group', option.className)}
|
||||
>
|
||||
<div className={cx('GroupedSelection-itemLabel')}>
|
||||
{itemRender(option, {
|
||||
index: index,
|
||||
multiple: multiple,
|
||||
checked: false,
|
||||
onChange: () => undefined,
|
||||
disabled: disabled || option.disabled,
|
||||
labelField,
|
||||
classnames: cx,
|
||||
testIdBuilder: tBuilder?.getChild('label')
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className={cx('GroupedSelection-items', option.className)}>
|
||||
{option.children.map((child, index) =>
|
||||
this.renderOption(child, index, `${index}`, {}, tBuilder)
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return this.renderPureOption(option, index, key, styles, tBuilder);
|
||||
}
|
||||
|
||||
renderOptionOrLabel(
|
||||
option: Option,
|
||||
index: number,
|
||||
hasParent: boolean = false,
|
||||
styles: object = {}
|
||||
): JSX.Element {
|
||||
const {
|
||||
disabled,
|
||||
classnames: cx,
|
||||
itemRender,
|
||||
multiple,
|
||||
labelField
|
||||
} = this.props;
|
||||
|
||||
if (option.children) {
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
style={styles}
|
||||
className={cx('GroupedSelection-group', option.className)}
|
||||
>
|
||||
<div className={cx('GroupedSelection-itemLabel')}>
|
||||
{itemRender(option, {
|
||||
index: index,
|
||||
multiple: multiple,
|
||||
checked: false,
|
||||
onChange: () => undefined,
|
||||
disabled: disabled || option.disabled,
|
||||
labelField,
|
||||
classnames: cx
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return hasParent ? (
|
||||
<div
|
||||
key={'group' + index}
|
||||
style={styles}
|
||||
className={cx('GroupedSelection-group', option.className)}
|
||||
>
|
||||
<div className={cx('GroupedSelection-items', option.className)}>
|
||||
{this.renderPureOption(option, index)}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
this.renderPureOption(option, index, undefined, styles)
|
||||
);
|
||||
}
|
||||
|
||||
renderPureOption(
|
||||
option: Option,
|
||||
index: number,
|
||||
key: string = `${index}`,
|
||||
styles: object = {},
|
||||
testIdBuilder?: TestIdBuilder
|
||||
): JSX.Element {
|
||||
const {
|
||||
labelClassName,
|
||||
disabled,
|
||||
classnames: cx,
|
||||
itemClassName,
|
||||
itemRender,
|
||||
multiple,
|
||||
labelField
|
||||
} = this.props;
|
||||
|
||||
const valueArray = this.valueArray;
|
||||
const itemTIB = testIdBuilder?.getChild(`item-${index}`);
|
||||
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
style={styles}
|
||||
className={cx(
|
||||
'GroupedSelection-item',
|
||||
itemClassName,
|
||||
option.className,
|
||||
disabled || option.disabled ? 'is-disabled' : '',
|
||||
!!~valueArray.indexOf(option) ? 'is-active' : ''
|
||||
)}
|
||||
onClick={() => this.toggleOption(option)}
|
||||
{...itemTIB?.getTestId()}
|
||||
>
|
||||
{multiple ? (
|
||||
<Checkbox
|
||||
size="sm"
|
||||
checked={!!~valueArray.indexOf(option)}
|
||||
disabled={disabled || option.disabled}
|
||||
labelClassName={labelClassName}
|
||||
description={option.description}
|
||||
testIdBuilder={itemTIB?.getChild('checkbox')}
|
||||
/>
|
||||
) : null}
|
||||
<div className={cx('GroupedSelection-itemLabel')}>
|
||||
{itemRender(option, {
|
||||
index: index,
|
||||
multiple: multiple,
|
||||
checked: !!~valueArray.indexOf(option),
|
||||
onChange: () => this.toggleOption(option),
|
||||
disabled: disabled || option.disabled,
|
||||
labelField,
|
||||
classnames: cx,
|
||||
testIdBuilder: itemTIB?.getChild('label')
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
renderCheckAll() {
|
||||
const {
|
||||
multiple,
|
||||
checkAll,
|
||||
checkAllLabel,
|
||||
classnames: cx,
|
||||
translate: __,
|
||||
labelClassName,
|
||||
itemClassName
|
||||
} = this.props;
|
||||
|
||||
if (!multiple || !checkAll) {
|
||||
return null;
|
||||
}
|
||||
const availableOptions = this.getAvailableOptions();
|
||||
|
||||
const valueArray = this.valueArray;
|
||||
|
||||
const checkedAll = availableOptions.every(
|
||||
option => valueArray.indexOf(option) > -1
|
||||
);
|
||||
const checkedPartial = availableOptions.some(
|
||||
option => valueArray.indexOf(option) > -1
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx('GroupedSelection-item', itemClassName)}
|
||||
onClick={this.toggleAll}
|
||||
>
|
||||
<Checkbox
|
||||
checked={checkedPartial}
|
||||
partial={checkedPartial && !checkedAll}
|
||||
size="sm"
|
||||
labelClassName={labelClassName}
|
||||
/>
|
||||
|
||||
<div className={cx('GroupedSelection-itemLabel')}>
|
||||
{__(checkAllLabel)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
value,
|
||||
options,
|
||||
className,
|
||||
placeholder,
|
||||
classnames: cx,
|
||||
option2value,
|
||||
onClick,
|
||||
placeholderRender,
|
||||
virtualThreshold = 1000,
|
||||
itemHeight = 32,
|
||||
virtualListHeight,
|
||||
testIdBuilder
|
||||
} = this.props;
|
||||
const __ = this.props.translate;
|
||||
|
||||
this.valueArray = BaseSelection.value2array(value, options, option2value);
|
||||
let body: Array<React.ReactNode> | React.ReactNode | null = null;
|
||||
|
||||
if (Array.isArray(options) && options.length) {
|
||||
const flattendOptions: Option[] = flattenTree(
|
||||
options,
|
||||
(item, index, level) => {
|
||||
return {
|
||||
option: item,
|
||||
hasParent: level > 1
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
body =
|
||||
flattendOptions.length > virtualThreshold ? (
|
||||
<AutoSizer minHeight={virtualListHeight}>
|
||||
{({height}: {height: number}) => (
|
||||
<VirtualList
|
||||
height={height}
|
||||
itemCount={flattendOptions.length}
|
||||
itemSize={itemHeight}
|
||||
prefix={this.renderCheckAll()}
|
||||
renderItem={({
|
||||
index,
|
||||
style
|
||||
}: {
|
||||
index: number;
|
||||
style?: object;
|
||||
}) => {
|
||||
const {option, hasParent} = flattendOptions[index] || {};
|
||||
if (!option) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.renderOptionOrLabel(option, index, hasParent, {
|
||||
...style,
|
||||
width: '100%'
|
||||
});
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</AutoSizer>
|
||||
) : (
|
||||
<>
|
||||
{this.renderCheckAll()}
|
||||
{options.map((option, key) =>
|
||||
this.renderOption(option, key, `${key}`, {}, testIdBuilder)
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cx('GroupedSelection', className)} onClick={onClick}>
|
||||
{body ? (
|
||||
body
|
||||
) : (
|
||||
<div className={cx('GroupedSelection-placeholder')}>
|
||||
{placeholderRender?.(this.props) ?? __(placeholder)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(
|
||||
localeable(
|
||||
uncontrollable(GroupedSelection, {
|
||||
value: 'onChange'
|
||||
})
|
||||
)
|
||||
);
|
||||
2
packages/amis-ui/src/components/HeadCellDropDown.tsx
Normal file
2
packages/amis-ui/src/components/HeadCellDropDown.tsx
Normal file
@@ -0,0 +1,2 @@
|
||||
import HeadCellDropDown from './table/HeadCellDropDown';
|
||||
export default HeadCellDropDown;
|
||||
372
packages/amis-ui/src/components/HorizontalScroll.tsx
Normal file
372
packages/amis-ui/src/components/HorizontalScroll.tsx
Normal file
@@ -0,0 +1,372 @@
|
||||
import {autobind, resizeSensor, TestIdBuilder, ThemeProps} from 'amis-core';
|
||||
import React, {ReactNode} from 'react';
|
||||
import debounce from 'lodash/debounce';
|
||||
|
||||
import {Icon} from './icons';
|
||||
|
||||
type ChildrenType =
|
||||
| React.ReactNode
|
||||
| ((showSelect: () => void) => React.ReactNode);
|
||||
|
||||
export interface HorizontalScrollProps extends ThemeProps {
|
||||
/**
|
||||
* 左右按钮图标
|
||||
*/
|
||||
icons?: ReactNode | ReactNode[];
|
||||
|
||||
/**
|
||||
* 外层容器类名
|
||||
*/
|
||||
className?: string;
|
||||
|
||||
/**
|
||||
* 左右图标类名
|
||||
*/
|
||||
iconsClassName?: string | string[];
|
||||
|
||||
/**
|
||||
* 测试ID生成器
|
||||
*/
|
||||
testIdBuilder?: TestIdBuilder;
|
||||
|
||||
children: ChildrenType;
|
||||
|
||||
/**
|
||||
* 子元素滚动容器,用于计算当前点击。默认为当前滚动容器最内层
|
||||
*/
|
||||
getScrollParentElement?: () => HTMLElement;
|
||||
|
||||
/**
|
||||
* 激活的子元素类名,如果设置,那么每次页面缩放的时候,都会让对应的位置滚动到可视区域。如果命中多个元素,则只会滚动第一个
|
||||
* 支持传入多个类名,按照传入数组中元素的顺序作为优先级顺序。[p0, p1, p2...],优先级高的类名命中元素则会停止寻找
|
||||
*/
|
||||
activeChildClassName?: string | string[];
|
||||
}
|
||||
|
||||
interface HorizontalScrollState {
|
||||
isOverflow: boolean;
|
||||
arrowLeftDisabled: boolean;
|
||||
arrowRightDisabled: boolean;
|
||||
scroll: boolean;
|
||||
}
|
||||
|
||||
export class HorizontalScroll extends React.Component<
|
||||
HorizontalScrollProps,
|
||||
HorizontalScrollState
|
||||
> {
|
||||
innerWrapper: React.RefObject<HTMLDivElement> = React.createRef(); // 内部滚动容器
|
||||
|
||||
resizeDom: React.RefObject<HTMLDivElement> = React.createRef(); // 外部容器
|
||||
|
||||
toDispose: Array<() => void> = []; // 监听函数数组
|
||||
|
||||
constructor(props: HorizontalScrollProps) {
|
||||
super(props);
|
||||
this.resizeDom = React.createRef();
|
||||
|
||||
this.state = {
|
||||
isOverflow: false,
|
||||
arrowLeftDisabled: false,
|
||||
arrowRightDisabled: false,
|
||||
scroll: false
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理箭头点击事件
|
||||
* @param type 箭头方向,'left' 表示向左,'right' 表示向右
|
||||
*/
|
||||
@autobind
|
||||
handleArrow(type: 'left' | 'right') {
|
||||
// 滚动元素的父元素
|
||||
const wrapElement =
|
||||
this.props.getScrollParentElement?.() || this.innerWrapper.current;
|
||||
|
||||
const {scrollLeft, scrollWidth, clientWidth} = wrapElement || {
|
||||
scrollLeft: 0,
|
||||
scrollWidth: 0,
|
||||
clientWidth: 0
|
||||
};
|
||||
if (type === 'left' && scrollLeft > 0) {
|
||||
const newScrollLeft = scrollLeft - clientWidth;
|
||||
|
||||
wrapElement?.scrollTo?.({
|
||||
left: newScrollLeft > 0 ? newScrollLeft : 0,
|
||||
behavior: 'smooth'
|
||||
});
|
||||
this.setState({
|
||||
arrowRightDisabled: false,
|
||||
arrowLeftDisabled: newScrollLeft <= 0
|
||||
});
|
||||
} else if (type === 'right' && scrollWidth > scrollLeft + clientWidth) {
|
||||
const newScrollLeft = scrollLeft + clientWidth;
|
||||
|
||||
wrapElement?.scrollTo?.({
|
||||
left: newScrollLeft > scrollWidth ? scrollWidth : newScrollLeft,
|
||||
behavior: 'smooth'
|
||||
});
|
||||
this.setState({
|
||||
arrowRightDisabled: newScrollLeft > scrollWidth - clientWidth,
|
||||
arrowLeftDisabled: false
|
||||
});
|
||||
}
|
||||
this.setState({
|
||||
scroll: true
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据滚动条位置更新左右箭头的禁用状态
|
||||
*/
|
||||
checkArrowStatus = debounce(
|
||||
() => {
|
||||
const wrapElement =
|
||||
this.props.getScrollParentElement?.() || this.innerWrapper.current;
|
||||
|
||||
const {scrollLeft, scrollWidth, clientWidth} = wrapElement || {
|
||||
scrollLeft: 0,
|
||||
scrollWidth: 0,
|
||||
clientWidth: 0
|
||||
};
|
||||
const {arrowRightDisabled, arrowLeftDisabled} = this.state;
|
||||
if (scrollLeft === 0 && !arrowLeftDisabled) {
|
||||
this.setState({
|
||||
arrowRightDisabled: false,
|
||||
arrowLeftDisabled: true
|
||||
});
|
||||
} else if (
|
||||
scrollWidth === scrollLeft + clientWidth &&
|
||||
!arrowRightDisabled
|
||||
) {
|
||||
this.setState({
|
||||
arrowRightDisabled: true,
|
||||
arrowLeftDisabled: false
|
||||
});
|
||||
} else if (scrollLeft !== 0 && arrowLeftDisabled) {
|
||||
this.setState({
|
||||
arrowLeftDisabled: false
|
||||
});
|
||||
} else if (
|
||||
scrollWidth !== scrollLeft + clientWidth &&
|
||||
arrowRightDisabled
|
||||
) {
|
||||
this.setState({
|
||||
arrowRightDisabled: false
|
||||
});
|
||||
}
|
||||
},
|
||||
100,
|
||||
{
|
||||
trailing: true,
|
||||
leading: false
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* 保证选中的yua始终显示在可视区域
|
||||
*/
|
||||
@autobind
|
||||
showSelected(isOverflow?: boolean) {
|
||||
const isContentOverflow =
|
||||
isOverflow === undefined ? this.state.isOverflow : isOverflow;
|
||||
|
||||
const {activeChildClassName} = this.props;
|
||||
|
||||
if (!isContentOverflow || !activeChildClassName) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 滚动子元素容器
|
||||
const wrapperDom =
|
||||
this.props.getScrollParentElement?.() || this.innerWrapper.current;
|
||||
|
||||
// 查找第一个命中的元素
|
||||
let activeElement: HTMLElement | null = null;
|
||||
const searchClassNames = Array.isArray(activeChildClassName)
|
||||
? activeChildClassName
|
||||
: [activeChildClassName];
|
||||
|
||||
// 根据传入类名数组从前到后查找是否能匹配到对应元素
|
||||
let classNameIndex = 0;
|
||||
|
||||
while (!activeElement && classNameIndex < searchClassNames.length) {
|
||||
activeElement = wrapperDom?.querySelector(
|
||||
`.${activeChildClassName[classNameIndex]}`
|
||||
) as HTMLElement;
|
||||
|
||||
classNameIndex++;
|
||||
}
|
||||
|
||||
// 检查查找到的元素是否是直接子元素,如果不是则一直向上找
|
||||
while (activeElement && activeElement.parentElement !== wrapperDom) {
|
||||
activeElement = activeElement.parentElement!;
|
||||
}
|
||||
|
||||
if (!activeElement) {
|
||||
return;
|
||||
}
|
||||
|
||||
const activeLeftOffset = activeElement?.offsetLeft;
|
||||
const activeWidth = activeElement?.clientWidth;
|
||||
const scrollLeft = wrapperDom?.scrollLeft || 0;
|
||||
const clientWidth = wrapperDom?.clientWidth || 0;
|
||||
|
||||
// 左边被遮住了
|
||||
if (scrollLeft > activeLeftOffset) {
|
||||
wrapperDom?.scrollTo?.({
|
||||
left: activeLeftOffset,
|
||||
behavior: 'smooth'
|
||||
});
|
||||
}
|
||||
// 右边被遮住了
|
||||
if (activeLeftOffset + activeWidth > scrollLeft + clientWidth) {
|
||||
wrapperDom?.scrollTo?.({
|
||||
left: activeLeftOffset + activeWidth - clientWidth,
|
||||
behavior: 'smooth'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理内容与容器之间的位置关系
|
||||
*/
|
||||
@autobind
|
||||
checkIsOverflow() {
|
||||
const navMainRef =
|
||||
this.props.getScrollParentElement?.() || this.innerWrapper.current;
|
||||
const clientWidth: number = navMainRef?.clientWidth || 0;
|
||||
const scrollWidth: number = navMainRef?.scrollWidth || 0;
|
||||
const isOverflow = scrollWidth > clientWidth;
|
||||
|
||||
// 内容超出容器长度标记溢出
|
||||
if (isOverflow !== this.state.isOverflow) {
|
||||
this.setState({isOverflow});
|
||||
}
|
||||
|
||||
if (isOverflow) {
|
||||
this.showSelected(isOverflow);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染箭头图标
|
||||
* @param type 箭头类型,'left' 表示左箭头,'right' 表示右箭头
|
||||
* @returns 返回渲染的箭头图标组件或 null
|
||||
*/
|
||||
renderArrow(type: 'left' | 'right') {
|
||||
const {classnames: cx, testIdBuilder, icons, iconsClassName} = this.props;
|
||||
const {isOverflow, arrowLeftDisabled, arrowRightDisabled} = this.state;
|
||||
const disabled = type === 'left' ? arrowLeftDisabled : arrowRightDisabled;
|
||||
|
||||
// 优先使用外部传入图标
|
||||
const [leftIcon, rightIcon] = Array.isArray(icons) ? icons : [icons, icons];
|
||||
const renderIconContent = type === 'left' ? leftIcon : rightIcon;
|
||||
|
||||
const [leftIconClassName, rightIconClassName] = Array.isArray(
|
||||
iconsClassName
|
||||
)
|
||||
? iconsClassName
|
||||
: [iconsClassName, iconsClassName];
|
||||
const renderIconClassName =
|
||||
type === 'left' ? leftIconClassName : rightIconClassName;
|
||||
|
||||
return isOverflow ? (
|
||||
<div
|
||||
onClick={() => this.handleArrow(type)}
|
||||
className={cx(
|
||||
'HorizontalScroll-arrow',
|
||||
'HorizontalScroll-arrow--' + type,
|
||||
disabled && 'HorizontalScroll-arrow--disabled'
|
||||
)}
|
||||
{...testIdBuilder?.getChild(`arrow-${type}`).getTestId()}
|
||||
>
|
||||
{renderIconContent ? (
|
||||
<Icon icon={renderIconContent} className={renderIconClassName} />
|
||||
) : (
|
||||
<Icon icon="right-arrow-bold" className="icon" />
|
||||
)}
|
||||
</div>
|
||||
) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 监听导航上的滚动事件
|
||||
*/
|
||||
@autobind
|
||||
handleWheel(e: WheelEvent) {
|
||||
const {deltaY, deltaX} = e;
|
||||
const absX = Math.abs(deltaX);
|
||||
const absY = Math.abs(deltaY);
|
||||
|
||||
// 当鼠标上下滚动时转换为左右滚动
|
||||
if (absY > absX) {
|
||||
const wrapElement =
|
||||
this.props.getScrollParentElement?.() || this.innerWrapper.current;
|
||||
|
||||
wrapElement?.scrollTo?.({
|
||||
left: wrapElement?.scrollLeft + deltaY
|
||||
});
|
||||
e.preventDefault();
|
||||
}
|
||||
this.checkArrowStatus();
|
||||
this.setState({
|
||||
scroll: true
|
||||
});
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
this.checkIsOverflow();
|
||||
|
||||
const wrapElement =
|
||||
this.props.getScrollParentElement?.() || this.innerWrapper.current;
|
||||
|
||||
if (wrapElement) {
|
||||
wrapElement.addEventListener('wheel', this.handleWheel, {
|
||||
passive: false
|
||||
});
|
||||
this.checkArrowStatus();
|
||||
}
|
||||
|
||||
this.resizeDom?.current &&
|
||||
this.toDispose.push(
|
||||
resizeSensor(this.resizeDom.current as HTMLElement, () =>
|
||||
this.checkIsOverflow()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.checkArrowStatus.cancel();
|
||||
this.toDispose.forEach(fn => fn());
|
||||
this.toDispose = [];
|
||||
}
|
||||
|
||||
render(): ReactNode {
|
||||
const {classnames: cx, children, testIdBuilder, className} = this.props;
|
||||
return (
|
||||
<div
|
||||
ref={this.resizeDom}
|
||||
className={cx('HorizontalScroll-wrapper', className)}
|
||||
>
|
||||
<div
|
||||
className={cx(
|
||||
'HorizontalScroll-Container',
|
||||
this.state.isOverflow && 'HorizontalScroll-Container--overflow'
|
||||
)}
|
||||
{...testIdBuilder?.getChild('links').getTestId()}
|
||||
>
|
||||
{this.renderArrow('left')}
|
||||
<div
|
||||
className={cx('HorizontalScroll-Container-main')}
|
||||
ref={this.innerWrapper}
|
||||
>
|
||||
{typeof children === 'function'
|
||||
? children(this.showSelected)
|
||||
: children}
|
||||
</div>
|
||||
{this.renderArrow('right')}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
76
packages/amis-ui/src/components/Html.tsx
Normal file
76
packages/amis-ui/src/components/Html.tsx
Normal file
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* @file Html
|
||||
* @description
|
||||
* @author fex
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import {ClassNamesFn, themeable} from 'amis-core';
|
||||
|
||||
export interface HtmlProps {
|
||||
className?: string;
|
||||
html?: string;
|
||||
wrapperComponent?: any;
|
||||
inline: boolean;
|
||||
classPrefix: string;
|
||||
classnames: ClassNamesFn;
|
||||
filterHtml?: (input: string) => string;
|
||||
}
|
||||
|
||||
export class Html extends React.Component<HtmlProps> {
|
||||
static defaultProps = {
|
||||
inline: true
|
||||
};
|
||||
|
||||
dom: any;
|
||||
|
||||
constructor(props: HtmlProps) {
|
||||
super(props);
|
||||
this.htmlRef = this.htmlRef.bind(this);
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps: HtmlProps) {
|
||||
if (this.props.html !== prevProps.html) {
|
||||
this._render();
|
||||
}
|
||||
}
|
||||
|
||||
htmlRef(dom: any) {
|
||||
this.dom = dom;
|
||||
|
||||
if (!dom) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._render();
|
||||
}
|
||||
|
||||
_render() {
|
||||
const {html, filterHtml} = this.props;
|
||||
|
||||
if (html) {
|
||||
this.dom.innerHTML = filterHtml ? filterHtml(html) : html;
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
className,
|
||||
wrapperComponent,
|
||||
inline,
|
||||
classPrefix: ns,
|
||||
classnames: cx
|
||||
} = this.props;
|
||||
|
||||
const Component = wrapperComponent || (inline ? 'span' : 'div');
|
||||
|
||||
return (
|
||||
<Component
|
||||
ref={this.htmlRef}
|
||||
className={cx(`Html`, className)}
|
||||
></Component>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(Html);
|
||||
3
packages/amis-ui/src/components/Icon.tsx
Normal file
3
packages/amis-ui/src/components/Icon.tsx
Normal file
@@ -0,0 +1,3 @@
|
||||
import Icon from './icons';
|
||||
|
||||
export default Icon;
|
||||
560
packages/amis-ui/src/components/ImageGallery.tsx
Normal file
560
packages/amis-ui/src/components/ImageGallery.tsx
Normal file
@@ -0,0 +1,560 @@
|
||||
import React from 'react';
|
||||
import debounce from 'lodash/debounce';
|
||||
import {themeable, ClassNamesFn, ThemeProps} from 'amis-core';
|
||||
import {autobind} from 'amis-core';
|
||||
import Modal from './Modal';
|
||||
import {Icon} from './icons';
|
||||
import {LocaleProps, localeable} from 'amis-core';
|
||||
|
||||
export enum ImageActionKey {
|
||||
/** 右旋转 */
|
||||
ROTATE_RIGHT = 'rotateRight',
|
||||
/** 左旋转 */
|
||||
ROTATE_LEFT = 'rotateLeft',
|
||||
/** 等比例放大 */
|
||||
ZOOM_IN = 'zoomIn',
|
||||
/** 等比例缩小 */
|
||||
ZOOM_OUT = 'zoomOut',
|
||||
/** 恢复原图缩放比例尺 */
|
||||
SCALE_ORIGIN = 'scaleOrigin'
|
||||
}
|
||||
|
||||
export interface ImageAction {
|
||||
key: ImageActionKey;
|
||||
label?: string;
|
||||
icon?: string | React.ReactNode;
|
||||
iconClassName?: string;
|
||||
disabled?: boolean;
|
||||
onClick?: (context: ImageGallery) => void;
|
||||
}
|
||||
|
||||
export interface ImageGalleryProps extends ThemeProps, LocaleProps {
|
||||
children: React.ReactNode | Array<React.ReactNode>;
|
||||
modalContainer?: () => HTMLElement;
|
||||
/** 操作栏 */
|
||||
actions?: ImageAction[];
|
||||
imageGallaryClassName?: string;
|
||||
}
|
||||
|
||||
export interface ImageGalleryState {
|
||||
isOpened: boolean;
|
||||
index: number;
|
||||
items: Array<{
|
||||
src: string;
|
||||
originalSrc: string;
|
||||
title?: string;
|
||||
caption?: string;
|
||||
}>;
|
||||
/** 图片缩放比例尺 */
|
||||
scale: number;
|
||||
/** 图片旋转角度 */
|
||||
rotate: number;
|
||||
/**
|
||||
* 水平位移
|
||||
*/
|
||||
tx: number;
|
||||
/**
|
||||
* 垂直位移
|
||||
*/
|
||||
ty: number;
|
||||
/** 是否开启操作栏 */
|
||||
showToolbar?: boolean;
|
||||
/** 是否显示底部图片集 */
|
||||
enlargeWithGallary?: boolean;
|
||||
/** 放大详情图类名 */
|
||||
imageGallaryClassName?: string;
|
||||
/** 工具栏配置 */
|
||||
actions?: ImageAction[];
|
||||
|
||||
scrollBarLeading?: boolean;
|
||||
scrollBarTrailing?: boolean;
|
||||
}
|
||||
|
||||
export class ImageGallery extends React.Component<
|
||||
ImageGalleryProps,
|
||||
ImageGalleryState
|
||||
> {
|
||||
static defaultProps: Pick<ImageGalleryProps, 'actions'> = {
|
||||
actions: [
|
||||
{
|
||||
key: ImageActionKey.ROTATE_LEFT,
|
||||
icon: 'rotate-left',
|
||||
label: 'rotate.left'
|
||||
},
|
||||
{
|
||||
key: ImageActionKey.ROTATE_RIGHT,
|
||||
icon: 'rotate-right',
|
||||
label: 'rotate.right'
|
||||
},
|
||||
{key: ImageActionKey.ZOOM_IN, icon: 'zoom-in', label: 'zoomIn'},
|
||||
{key: ImageActionKey.ZOOM_OUT, icon: 'zoom-out', label: 'zoomOut'},
|
||||
{
|
||||
key: ImageActionKey.SCALE_ORIGIN,
|
||||
icon: 'scale-origin',
|
||||
label: 'scale.origin'
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
state: ImageGalleryState = {
|
||||
isOpened: false,
|
||||
index: -1,
|
||||
items: [],
|
||||
tx: 0,
|
||||
ty: 0,
|
||||
scale: 1,
|
||||
rotate: 0,
|
||||
showToolbar: false,
|
||||
imageGallaryClassName: '',
|
||||
actions: ImageGallery.defaultProps.actions
|
||||
};
|
||||
|
||||
galleryMain?: HTMLDivElement;
|
||||
@autobind
|
||||
galleryMainRef(ref: HTMLDivElement) {
|
||||
if (ref) {
|
||||
ref.addEventListener('wheel', this.onWheelScroll, {
|
||||
passive: false
|
||||
});
|
||||
ref.addEventListener('mousedown', this.onMouseDown);
|
||||
} else {
|
||||
this.galleryMain?.removeEventListener('wheel', this.onWheelScroll);
|
||||
this.galleryMain?.removeEventListener('mousedown', this.onMouseDown);
|
||||
}
|
||||
|
||||
this.galleryMain = ref;
|
||||
}
|
||||
|
||||
@autobind
|
||||
onWheelScroll(event: WheelEvent) {
|
||||
const showToolbar = this.state?.showToolbar;
|
||||
|
||||
if (!showToolbar) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
/** 向上滚动放大,向下滚动缩小 */
|
||||
if (event.deltaY > 0) {
|
||||
this.handleToolbarAction({key: 'zoomOut'} as ImageAction);
|
||||
} else if (event.deltaY < 0) {
|
||||
this.handleToolbarAction({key: 'zoomIn'} as ImageAction);
|
||||
}
|
||||
}
|
||||
|
||||
startX = 0;
|
||||
startY = 0;
|
||||
startTx = 0;
|
||||
startTy = 0;
|
||||
|
||||
@autobind
|
||||
onMouseDown(event: MouseEvent) {
|
||||
const isLeftButton =
|
||||
(event.button === 1 && window.event !== null) || event.button === 0;
|
||||
if (!isLeftButton || event.defaultPrevented) return;
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
this.galleryMain?.classList.add('is-dragging');
|
||||
document.body.addEventListener('mousemove', this.onMouseMove);
|
||||
document.body.addEventListener('mouseup', this.onMouseUp);
|
||||
|
||||
this.startX = event.clientX;
|
||||
this.startY = event.clientY;
|
||||
this.startTx = this.state.tx;
|
||||
this.startTy = this.state.ty;
|
||||
}
|
||||
|
||||
@autobind
|
||||
onMouseMove(event: MouseEvent) {
|
||||
this.setState({
|
||||
tx: this.startTx + event.clientX - this.startX,
|
||||
ty: this.startTy + event.clientY - this.startY
|
||||
});
|
||||
}
|
||||
|
||||
@autobind
|
||||
onMouseUp() {
|
||||
this.galleryMain?.classList.remove('is-dragging');
|
||||
document.body.removeEventListener('mousemove', this.onMouseMove);
|
||||
document.body.removeEventListener('mouseup', this.onMouseUp);
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleImageEnlarge(info: {
|
||||
src: string;
|
||||
originalSrc: string;
|
||||
list?: Array<{
|
||||
src: string;
|
||||
originalSrc: string;
|
||||
title?: string;
|
||||
caption?: string;
|
||||
}>;
|
||||
title?: string;
|
||||
caption?: string;
|
||||
index?: number;
|
||||
showToolbar?: boolean;
|
||||
imageGallaryClassName?: string;
|
||||
toolbarActions?: ImageAction[];
|
||||
enlargeWithGallary?: boolean;
|
||||
}) {
|
||||
const {actions} = this.props;
|
||||
const validActionKeys = Object.values(ImageActionKey);
|
||||
|
||||
this.setState({
|
||||
isOpened: true,
|
||||
tx: 0,
|
||||
ty: 0,
|
||||
rotate: 0,
|
||||
scale: 1,
|
||||
items: info.list ? info.list : [info],
|
||||
index: info.index || 0,
|
||||
/* children组件可以控制工具栏的展示 */
|
||||
showToolbar: !!info.showToolbar,
|
||||
enlargeWithGallary: info.enlargeWithGallary,
|
||||
imageGallaryClassName: info.imageGallaryClassName,
|
||||
/** 外部传入合法key值的actions才会生效 */
|
||||
actions: Array.isArray(info.toolbarActions)
|
||||
? info.toolbarActions.filter(action =>
|
||||
validActionKeys.includes(action?.key)
|
||||
)
|
||||
: actions,
|
||||
|
||||
scrollBarLeading: true,
|
||||
scrollBarTrailing: false
|
||||
});
|
||||
}
|
||||
|
||||
resetImageAction() {
|
||||
this.setState({scale: 1, rotate: 0});
|
||||
}
|
||||
|
||||
@autobind
|
||||
close() {
|
||||
this.setState({
|
||||
isOpened: false
|
||||
});
|
||||
this.resetImageAction();
|
||||
}
|
||||
|
||||
@autobind
|
||||
prev() {
|
||||
const index = this.state.index;
|
||||
this.setState({index: index - 1});
|
||||
this.resetImageAction();
|
||||
}
|
||||
|
||||
@autobind
|
||||
next() {
|
||||
const index = this.state.index;
|
||||
this.setState({index: index + 1});
|
||||
this.resetImageAction();
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleItemClick(e: React.MouseEvent<HTMLDivElement>) {
|
||||
const index = parseInt(e.currentTarget.getAttribute('data-index')!, 10);
|
||||
this.setState({index});
|
||||
this.resetImageAction();
|
||||
}
|
||||
|
||||
handleToolbarAction = debounce(
|
||||
(action: ImageAction) => {
|
||||
if (action.disabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (action.key) {
|
||||
case ImageActionKey.ROTATE_LEFT:
|
||||
this.setState(prevState => ({
|
||||
rotate: prevState.rotate - 90,
|
||||
tx: 0,
|
||||
ty: 0
|
||||
}));
|
||||
break;
|
||||
case ImageActionKey.ROTATE_RIGHT:
|
||||
this.setState(prevState => ({
|
||||
rotate: prevState.rotate + 90,
|
||||
tx: 0,
|
||||
ty: 0
|
||||
}));
|
||||
break;
|
||||
case ImageActionKey.ZOOM_IN:
|
||||
this.setState(prevState => ({
|
||||
scale: prevState.scale + 0.5,
|
||||
tx: 0,
|
||||
ty: 0
|
||||
}));
|
||||
break;
|
||||
case ImageActionKey.ZOOM_OUT:
|
||||
this.setState(prevState => {
|
||||
return prevState.scale - 0.5 > 0
|
||||
? {scale: prevState.scale - 0.5, tx: 0, ty: 0}
|
||||
: null;
|
||||
});
|
||||
break;
|
||||
case ImageActionKey.SCALE_ORIGIN:
|
||||
this.setState(() => ({scale: 1, tx: 0, ty: 0}));
|
||||
break;
|
||||
}
|
||||
|
||||
if (action.onClick && typeof action.onClick === 'function') {
|
||||
action.onClick(this);
|
||||
}
|
||||
},
|
||||
250,
|
||||
{leading: true, trailing: false}
|
||||
);
|
||||
|
||||
@autobind
|
||||
handleModalEntered() {
|
||||
if (this.scrollBar.current) {
|
||||
const item = this.scrollBar.current.querySelector(
|
||||
`div[data-index="${this.state.index}"]`
|
||||
);
|
||||
item?.scrollIntoView({
|
||||
behavior: 'smooth'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
scrollBar = React.createRef<HTMLDivElement>();
|
||||
|
||||
@autobind
|
||||
handleBarScroll() {
|
||||
const scrollBar = this.scrollBar.current!;
|
||||
const inner = scrollBar.firstElementChild as HTMLElement;
|
||||
|
||||
this.setState({
|
||||
scrollBarLeading: scrollBar.scrollLeft === 0,
|
||||
scrollBarTrailing:
|
||||
scrollBar.offsetWidth + scrollBar.scrollLeft >= inner.offsetWidth
|
||||
});
|
||||
}
|
||||
|
||||
scroll(direction = 1) {
|
||||
const scrollBar = this.scrollBar.current!;
|
||||
const inner = scrollBar.firstElementChild as HTMLElement;
|
||||
const gap = inner.offsetWidth - scrollBar.offsetWidth;
|
||||
|
||||
scrollBar.scrollTo({
|
||||
left: scrollBar.scrollLeft + gap * 0.1 * direction,
|
||||
top: 0,
|
||||
behavior: 'smooth'
|
||||
});
|
||||
|
||||
let timer = setInterval(() => {
|
||||
scrollBar.scrollTo({
|
||||
left: scrollBar.scrollLeft + 5 * direction,
|
||||
top: 0,
|
||||
behavior: 'smooth'
|
||||
});
|
||||
}, 50);
|
||||
let onMouseUp = () => {
|
||||
document.body.removeEventListener('mouseup', onMouseUp);
|
||||
clearInterval(timer);
|
||||
};
|
||||
document.body.addEventListener('mouseup', onMouseUp);
|
||||
}
|
||||
|
||||
@autobind
|
||||
scrollRight() {
|
||||
this.scroll(1);
|
||||
}
|
||||
|
||||
@autobind
|
||||
scrollLeft() {
|
||||
this.scroll(-1);
|
||||
}
|
||||
|
||||
renderToolbar(actions: ImageAction[]) {
|
||||
const {classnames: cx, translate: __, className} = this.props;
|
||||
const scale = this.state.scale;
|
||||
|
||||
return (
|
||||
<div className={cx('ImageGallery-toolbar', className)}>
|
||||
{actions.map(action => (
|
||||
<div
|
||||
className={cx('ImageGallery-toolbar-action', {
|
||||
'is-disabled':
|
||||
action.disabled ||
|
||||
(action.key === ImageActionKey.ZOOM_OUT && scale - 0.5 <= 0)
|
||||
})}
|
||||
key={action.key}
|
||||
onClick={() => this.handleToolbarAction(action)}
|
||||
>
|
||||
<a
|
||||
className={cx('ImageGallery-toolbar-action-icon')}
|
||||
data-tooltip={__(action.label)}
|
||||
data-position="top"
|
||||
>
|
||||
{React.isValidElement(action.icon) ? (
|
||||
React.cloneElement(action.icon as React.ReactElement, {
|
||||
className: cx('icon', action.iconClassName)
|
||||
})
|
||||
) : (
|
||||
<Icon
|
||||
icon={action.icon}
|
||||
className={cx('icon', action.iconClassName)}
|
||||
/>
|
||||
)}
|
||||
</a>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {children, classnames: cx, modalContainer} = this.props;
|
||||
const {
|
||||
index,
|
||||
items,
|
||||
rotate,
|
||||
scale,
|
||||
tx,
|
||||
ty,
|
||||
showToolbar,
|
||||
enlargeWithGallary,
|
||||
actions,
|
||||
imageGallaryClassName,
|
||||
scrollBarLeading,
|
||||
scrollBarTrailing
|
||||
} = this.state;
|
||||
const __ = this.props.translate;
|
||||
|
||||
return (
|
||||
<>
|
||||
{React.cloneElement(children as any, {
|
||||
onImageEnlarge: this.handleImageEnlarge
|
||||
})}
|
||||
|
||||
<Modal
|
||||
closeOnEsc
|
||||
closeOnOutside
|
||||
size="full"
|
||||
onHide={this.close}
|
||||
show={this.state.isOpened}
|
||||
contentClassName={cx('ImageGallery', imageGallaryClassName)}
|
||||
container={modalContainer}
|
||||
onEntered={this.handleModalEntered}
|
||||
>
|
||||
<a
|
||||
data-tooltip={__('Dialog.close')}
|
||||
data-position="left"
|
||||
className={cx('ImageGallery-close')}
|
||||
onClick={this.close}
|
||||
>
|
||||
<Icon icon="close" className="icon" />
|
||||
</a>
|
||||
{~index && items[index] ? (
|
||||
<>
|
||||
<div className={cx('ImageGallery-title')}>
|
||||
{items[index].title}
|
||||
</div>
|
||||
{items[index].caption ? (
|
||||
<div className={cx('ImageGallery-caption')}>
|
||||
{items[index].caption}
|
||||
</div>
|
||||
) : null}
|
||||
<div
|
||||
className={cx('ImageGallery-main')}
|
||||
ref={this.galleryMainRef}
|
||||
>
|
||||
<img
|
||||
draggable={false}
|
||||
src={items[index].originalSrc}
|
||||
style={{
|
||||
transform: `translate(${tx}px, ${ty}px) scale(${scale}) rotate(${rotate}deg)`
|
||||
}}
|
||||
/>
|
||||
|
||||
{showToolbar && Array.isArray(actions) && actions.length > 0
|
||||
? this.renderToolbar(actions)
|
||||
: null}
|
||||
|
||||
{items.length > 1 && enlargeWithGallary !== false ? (
|
||||
<>
|
||||
<a
|
||||
className={cx(
|
||||
'ImageGallery-prevBtn',
|
||||
index <= 0 ? 'is-disabled' : ''
|
||||
)}
|
||||
onClick={this.prev}
|
||||
>
|
||||
<Icon
|
||||
icon="prev"
|
||||
className="icon"
|
||||
iconContent="ImageGallery-prevBtn"
|
||||
/>
|
||||
</a>
|
||||
<a
|
||||
className={cx(
|
||||
'ImageGallery-nextBtn',
|
||||
index >= items.length - 1 ? 'is-disabled' : ''
|
||||
)}
|
||||
onClick={this.next}
|
||||
>
|
||||
<Icon
|
||||
icon="next"
|
||||
className="icon"
|
||||
iconContent="ImageGallery-nextBtn"
|
||||
/>
|
||||
</a>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{items.length > 1 && enlargeWithGallary !== false ? (
|
||||
<div className={cx('ImageGallery-footer')}>
|
||||
<a
|
||||
className={cx(
|
||||
'ImageGallery-prevList',
|
||||
scrollBarLeading ? 'is-disabled' : ''
|
||||
)}
|
||||
onMouseDown={this.scrollLeft}
|
||||
>
|
||||
<Icon icon="prev" className="icon" />
|
||||
</a>
|
||||
<div
|
||||
className={cx('ImageGallery-itemsWrap')}
|
||||
ref={this.scrollBar}
|
||||
onScroll={this.handleBarScroll}
|
||||
>
|
||||
<div className={cx('ImageGallery-items')}>
|
||||
{items.map((item, i) => (
|
||||
<div
|
||||
key={i}
|
||||
data-index={i}
|
||||
onClick={this.handleItemClick}
|
||||
className={cx(
|
||||
'ImageGallery-item',
|
||||
i === index ? 'is-active' : ''
|
||||
)}
|
||||
>
|
||||
<img src={item.src} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<a
|
||||
className={cx(
|
||||
'ImageGallery-nextList',
|
||||
scrollBarTrailing ? 'is-disabled' : ''
|
||||
)}
|
||||
onMouseDown={this.scrollRight}
|
||||
>
|
||||
<Icon icon="next" className="icon" />
|
||||
</a>
|
||||
</div>
|
||||
) : null}
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(localeable(ImageGallery));
|
||||
88
packages/amis-ui/src/components/Input.tsx
Normal file
88
packages/amis-ui/src/components/Input.tsx
Normal file
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* @file 这个 Input 与系统默认的 input 不同的地方在于,
|
||||
* 中文输入过程中不会触发 onChange 事件。对于 autoComplete
|
||||
* 功能很有必要。
|
||||
*/
|
||||
import React from 'react';
|
||||
import {TestIdBuilder, autobind} from 'amis-core';
|
||||
|
||||
export interface InputProps
|
||||
extends React.InputHTMLAttributes<HTMLInputElement> {
|
||||
forwardedRef: React.Ref<HTMLInputElement>;
|
||||
testIdBuilder?: TestIdBuilder;
|
||||
}
|
||||
|
||||
export interface InputState {
|
||||
value: any;
|
||||
}
|
||||
|
||||
class InputInner extends React.Component<InputProps, InputState> {
|
||||
isOnComposition: boolean = false;
|
||||
state = {value: this.props.value};
|
||||
|
||||
componentDidUpdate(prevProps: InputProps) {
|
||||
const props = this.props;
|
||||
if (prevProps.value !== props.value) {
|
||||
this.setState({
|
||||
value: props.value
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleComposition(e: React.CompositionEvent<HTMLInputElement>) {
|
||||
this.isOnComposition = e.type !== 'compositionend';
|
||||
|
||||
if (!this.isOnComposition) {
|
||||
this.handleChange(e as any);
|
||||
}
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleChange(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const {onChange} = this.props;
|
||||
const value = e.currentTarget.value;
|
||||
|
||||
this.isOnComposition || (onChange && onChange(e));
|
||||
this.setState({
|
||||
value
|
||||
});
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleKeyDown(e: React.KeyboardEvent<any>) {
|
||||
const {onKeyDown} = this.props;
|
||||
|
||||
if (this.isOnComposition) {
|
||||
return;
|
||||
}
|
||||
|
||||
onKeyDown?.(e);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {forwardedRef, testIdBuilder, ...rest} = this.props;
|
||||
|
||||
return (
|
||||
<input
|
||||
type="text"
|
||||
{...rest}
|
||||
value={this.state.value}
|
||||
ref={forwardedRef}
|
||||
onChange={this.handleChange}
|
||||
onKeyDown={this.handleKeyDown}
|
||||
onCompositionStart={this.handleComposition}
|
||||
onCompositionUpdate={this.handleComposition}
|
||||
onCompositionEnd={this.handleComposition}
|
||||
{...testIdBuilder?.getTestId()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default React.forwardRef<HTMLInputElement>((props, ref) => {
|
||||
return <InputInner {...props} forwardedRef={ref} />;
|
||||
}) as React.ComponentType<
|
||||
Omit<InputProps, 'forwardedRef'> &
|
||||
React.InputHTMLAttributes<HTMLInputElement> & {ref?: any}
|
||||
>;
|
||||
152
packages/amis-ui/src/components/InputBox.tsx
Normal file
152
packages/amis-ui/src/components/InputBox.tsx
Normal file
@@ -0,0 +1,152 @@
|
||||
import React from 'react';
|
||||
import {TestIdBuilder, ThemeProps, themeable} from 'amis-core';
|
||||
import Input from './Input';
|
||||
import {autobind, ucFirst} from 'amis-core';
|
||||
import {Icon} from './icons';
|
||||
|
||||
export interface InputBoxProps
|
||||
extends ThemeProps,
|
||||
Omit<
|
||||
React.InputHTMLAttributes<HTMLInputElement>,
|
||||
'style' | 'prefix' | 'onChange' | 'translate' | 'size'
|
||||
> {
|
||||
value?: string;
|
||||
readOnly?: boolean;
|
||||
onChange?: (value: string) => void;
|
||||
onClear?: (e: React.MouseEvent<any>) => void;
|
||||
clearable?: boolean;
|
||||
disabled?: boolean;
|
||||
hasError?: boolean;
|
||||
placeholder?: string;
|
||||
prefix?: JSX.Element;
|
||||
children?: React.ReactNode | Array<React.ReactNode>;
|
||||
borderMode?: 'full' | 'half' | 'none';
|
||||
testIdBuilder?: TestIdBuilder;
|
||||
inputRender?: (props: any, ref?: any) => JSX.Element;
|
||||
dataName?: string;
|
||||
}
|
||||
|
||||
export interface InputBoxState {
|
||||
isFocused: boolean;
|
||||
}
|
||||
|
||||
export class InputBox extends React.Component<InputBoxProps, InputBoxState> {
|
||||
static defaultProps = {
|
||||
clearable: true,
|
||||
placeholder: ''
|
||||
};
|
||||
|
||||
state = {
|
||||
isFocused: false
|
||||
};
|
||||
|
||||
@autobind
|
||||
clearValue(e: any) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
const onClear = this.props.onClear;
|
||||
const onChange = this.props.onChange;
|
||||
onClear?.(e);
|
||||
onChange?.('');
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleChange(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const onChange = this.props.onChange;
|
||||
onChange && onChange(e.currentTarget ? e.currentTarget.value : (e as any));
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleFocus(e: any) {
|
||||
const onFocus = this.props.onFocus;
|
||||
onFocus && onFocus(e);
|
||||
this.setState({
|
||||
isFocused: true
|
||||
});
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleBlur(e: any) {
|
||||
const onBlur = this.props.onBlur;
|
||||
onBlur && onBlur(e);
|
||||
this.setState({
|
||||
isFocused: false
|
||||
});
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
className,
|
||||
classnames: cx,
|
||||
classPrefix,
|
||||
clearable,
|
||||
disabled,
|
||||
hasError,
|
||||
value,
|
||||
placeholder,
|
||||
prefix: result,
|
||||
children,
|
||||
borderMode,
|
||||
onClick,
|
||||
mobileUI,
|
||||
testIdBuilder,
|
||||
inputRender,
|
||||
dataName,
|
||||
...rest
|
||||
} = this.props;
|
||||
const isFocused = this.state.isFocused;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx('InputBox', className, {
|
||||
'is-mobile': mobileUI,
|
||||
'is-focused': isFocused,
|
||||
'is-disabled': disabled,
|
||||
'is-error': hasError,
|
||||
'is-clickable': onClick,
|
||||
[`InputBox--border${ucFirst(borderMode)}`]: borderMode
|
||||
})}
|
||||
onClick={onClick}
|
||||
data-amis-name={dataName}
|
||||
>
|
||||
{result}
|
||||
|
||||
{typeof inputRender === 'function' ? (
|
||||
inputRender({
|
||||
...rest,
|
||||
value: value ?? '',
|
||||
onChange: this.handleChange as any,
|
||||
placeholder,
|
||||
onFocus: this.handleFocus,
|
||||
onBlur: this.handleBlur,
|
||||
disabled,
|
||||
...testIdBuilder?.getTestId()
|
||||
})
|
||||
) : (
|
||||
<Input
|
||||
{...rest}
|
||||
value={value ?? ''}
|
||||
onChange={this.handleChange}
|
||||
placeholder={placeholder}
|
||||
onFocus={this.handleFocus}
|
||||
onBlur={this.handleBlur}
|
||||
size={12}
|
||||
disabled={disabled}
|
||||
{...testIdBuilder?.getTestId()}
|
||||
/>
|
||||
)}
|
||||
|
||||
{clearable && !disabled && value ? (
|
||||
<a onClick={this.clearValue} className={cx('InputBox-clear')}>
|
||||
<Icon icon="input-clear" className="icon" />
|
||||
</a>
|
||||
) : null}
|
||||
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(InputBox);
|
||||
128
packages/amis-ui/src/components/InputBoxWithSuggestion.tsx
Normal file
128
packages/amis-ui/src/components/InputBoxWithSuggestion.tsx
Normal file
@@ -0,0 +1,128 @@
|
||||
import React from 'react';
|
||||
import {findDOMNode} from 'react-dom';
|
||||
import {localeable, LocaleProps} from 'amis-core';
|
||||
import {themeable, ThemeProps} from 'amis-core';
|
||||
// @ts-ignore
|
||||
import {matchSorter} from 'match-sorter';
|
||||
import PopOverContainer from './PopOverContainer';
|
||||
import SearchBox from './SearchBox';
|
||||
import ListSelection from './GroupedSelection';
|
||||
import InputBox from './InputBox';
|
||||
import {Icon} from './icons';
|
||||
|
||||
export interface InputBoxWithSuggestionProps extends ThemeProps, LocaleProps {
|
||||
options: Array<any>;
|
||||
value: any;
|
||||
onChange: (value: any) => void;
|
||||
disabled?: boolean;
|
||||
searchable?: boolean;
|
||||
popOverContainer?: any;
|
||||
hasError?: boolean;
|
||||
placeholder?: string;
|
||||
clearable?: boolean;
|
||||
}
|
||||
|
||||
const option2value = (item: any) => item.value;
|
||||
|
||||
export class InputBoxWithSuggestion extends React.Component<InputBoxWithSuggestionProps> {
|
||||
constructor(props: InputBoxWithSuggestionProps) {
|
||||
super(props);
|
||||
this.state = {
|
||||
searchText: ''
|
||||
};
|
||||
this.onSearch = this.onSearch.bind(this);
|
||||
this.filterOptions = this.filterOptions.bind(this);
|
||||
}
|
||||
|
||||
onSearch(text: string) {
|
||||
let txt = text.toLowerCase();
|
||||
|
||||
this.setState({searchText: txt});
|
||||
}
|
||||
|
||||
filterOptions(options: any[]) {
|
||||
return this.props.value
|
||||
? matchSorter(options, this.props.value, {
|
||||
keys: ['label', 'value'],
|
||||
threshold: matchSorter.rankings.CONTAINS
|
||||
}).filter((item: any) => item.value !== this.props.value)
|
||||
: options;
|
||||
}
|
||||
|
||||
// 选了值,还原options
|
||||
onPopClose(e: React.MouseEvent, onClose: () => void) {
|
||||
this.setState({searchText: ''});
|
||||
onClose();
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
placeholder,
|
||||
onChange,
|
||||
value,
|
||||
classnames: cx,
|
||||
disabled,
|
||||
translate: __,
|
||||
searchable,
|
||||
popOverContainer,
|
||||
clearable,
|
||||
hasError,
|
||||
mobileUI,
|
||||
className
|
||||
} = this.props;
|
||||
const options = this.filterOptions(
|
||||
Array.isArray(this.props.options) ? this.props.options : []
|
||||
);
|
||||
|
||||
return (
|
||||
<PopOverContainer
|
||||
show={!!options.length}
|
||||
popOverContainer={popOverContainer || (() => findDOMNode(this))}
|
||||
popOverRender={({onClose}) => (
|
||||
<>
|
||||
{searchable ? (
|
||||
<SearchBox mini={false} onSearch={this.onSearch} />
|
||||
) : null}
|
||||
<ListSelection
|
||||
multiple={false}
|
||||
onClick={e => this.onPopClose(e, onClose)}
|
||||
options={options}
|
||||
value={[value]}
|
||||
option2value={option2value}
|
||||
onChange={(value: any) => {
|
||||
onChange?.(value);
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
>
|
||||
{({onClick, ref, isOpened}) => (
|
||||
<InputBox
|
||||
className={cx(
|
||||
'InputBox--sug',
|
||||
className,
|
||||
isOpened ? 'is-active' : ''
|
||||
)}
|
||||
ref={ref}
|
||||
placeholder={placeholder}
|
||||
disabled={disabled}
|
||||
value={options.find(o => o.value === value)?.label ?? value}
|
||||
onChange={onChange}
|
||||
clearable={clearable}
|
||||
onClick={onClick}
|
||||
hasError={hasError}
|
||||
mobileUI={mobileUI}
|
||||
>
|
||||
{options.length ? (
|
||||
<span className={cx('InputBox-caret')}>
|
||||
<Icon icon="right-arrow-bold" className="icon" />
|
||||
</span>
|
||||
) : null}
|
||||
</InputBox>
|
||||
)}
|
||||
</PopOverContainer>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(localeable(InputBoxWithSuggestion));
|
||||
3
packages/amis-ui/src/components/InputJSONSchema.tsx
Normal file
3
packages/amis-ui/src/components/InputJSONSchema.tsx
Normal file
@@ -0,0 +1,3 @@
|
||||
import InputJSONSchema from './json-schema';
|
||||
|
||||
export default InputJSONSchema;
|
||||
386
packages/amis-ui/src/components/InputTable.tsx
Normal file
386
packages/amis-ui/src/components/InputTable.tsx
Normal file
@@ -0,0 +1,386 @@
|
||||
import {
|
||||
ClassNamesFn,
|
||||
localeable,
|
||||
LocaleProps,
|
||||
themeable,
|
||||
ThemeProps,
|
||||
TranslateFn
|
||||
} from 'amis-core';
|
||||
import React from 'react';
|
||||
import {
|
||||
Control,
|
||||
useFieldArray,
|
||||
UseFieldArrayProps,
|
||||
useFormContext,
|
||||
UseFormReturn,
|
||||
useFormState
|
||||
} from 'react-hook-form';
|
||||
import useSubForm from '../hooks/use-sub-form';
|
||||
import Button from './Button';
|
||||
import FormField, {FormFieldProps} from './FormField';
|
||||
import {Icon} from './icons';
|
||||
|
||||
import type {ButtonProps} from './Button';
|
||||
|
||||
export interface tdRenderFunc {
|
||||
(
|
||||
methods: UseFormReturn & {
|
||||
popOverContainer?: any;
|
||||
},
|
||||
colIndex: number,
|
||||
rowIndex: number
|
||||
): JSX.Element | null;
|
||||
}
|
||||
|
||||
export interface InputTableColumnProps {
|
||||
title?: string;
|
||||
className?: string;
|
||||
thRender?: () => JSX.Element;
|
||||
tdRender: tdRenderFunc;
|
||||
}
|
||||
|
||||
interface InputTableScrollProps {
|
||||
/** 垂直滚动区域的最大高度 */
|
||||
y: number | string;
|
||||
}
|
||||
|
||||
export interface InputTabbleProps<T = any>
|
||||
extends ThemeProps,
|
||||
LocaleProps,
|
||||
Omit<FormFieldProps, 'children' | 'errors' | 'hasError' | 'className'>,
|
||||
UseFieldArrayProps {
|
||||
control: Control<any>;
|
||||
fieldClassName?: string;
|
||||
columns: Array<InputTableColumnProps>;
|
||||
|
||||
/**
|
||||
* 要不要包裹 label 之类的
|
||||
*/
|
||||
wrap?: boolean;
|
||||
scaffold?: any;
|
||||
|
||||
addable?: boolean;
|
||||
addButtonClassName?: string;
|
||||
addButtonText?: string;
|
||||
addButtonProps?: Partial<Omit<ButtonProps, 'onClick'>>;
|
||||
|
||||
maxLength?: number;
|
||||
minLength?: number;
|
||||
removable?: boolean;
|
||||
/** 表格CSS类名 */
|
||||
tableClassName?: string;
|
||||
/** 表格头CSS类名 */
|
||||
tableHeadClassName?: string;
|
||||
/** 表格内容区CSS类名 */
|
||||
tableBodyClassName?: string;
|
||||
/** 空状态文字 */
|
||||
placeholder?: React.ReactNode;
|
||||
/** 滚动设置 */
|
||||
scroll?: InputTableScrollProps;
|
||||
/** 底部工具栏 */
|
||||
footer?: () => React.ReactNode;
|
||||
onItemAdd?: (values: Record<string, any>) => void;
|
||||
}
|
||||
|
||||
export function InputTable({
|
||||
control,
|
||||
name,
|
||||
wrap,
|
||||
mode,
|
||||
label,
|
||||
labelAlign,
|
||||
labelClassName,
|
||||
description,
|
||||
fieldClassName,
|
||||
className,
|
||||
translate: __,
|
||||
classnames: cx,
|
||||
removable,
|
||||
columns,
|
||||
addable,
|
||||
addButtonText,
|
||||
addButtonClassName,
|
||||
addButtonProps,
|
||||
scaffold,
|
||||
minLength,
|
||||
maxLength,
|
||||
isRequired,
|
||||
rules,
|
||||
tableClassName,
|
||||
tableHeadClassName,
|
||||
tableBodyClassName,
|
||||
placeholder,
|
||||
scroll,
|
||||
footer,
|
||||
onItemAdd
|
||||
}: InputTabbleProps) {
|
||||
const enableScroll = scroll?.y != null;
|
||||
const tBodyRef = React.useRef<HTMLTableElement>(null);
|
||||
const tableRef = React.useRef<HTMLTableElement>(null);
|
||||
const subForms = React.useRef<Record<any, UseFormReturn>>({});
|
||||
const subFormRef = React.useCallback(
|
||||
(subform: UseFormReturn | null, id: string) => {
|
||||
if (subform) {
|
||||
subForms.current[id] = subform;
|
||||
} else {
|
||||
delete subForms.current[id];
|
||||
}
|
||||
},
|
||||
[subForms]
|
||||
);
|
||||
const popOverContainer = React.useCallback(() => {
|
||||
return tBodyRef.current;
|
||||
}, [tBodyRef]);
|
||||
let finalRules: any = {...rules};
|
||||
|
||||
if (isRequired) {
|
||||
finalRules.required = true;
|
||||
}
|
||||
|
||||
if (minLength) {
|
||||
finalRules.minLength = minLength;
|
||||
}
|
||||
|
||||
if (maxLength) {
|
||||
finalRules.maxLength = maxLength;
|
||||
}
|
||||
|
||||
finalRules.validate = React.useCallback(
|
||||
async (items: Array<any>) => {
|
||||
const map = subForms.current;
|
||||
|
||||
if (typeof rules?.validate === 'function') {
|
||||
const result = await rules.validate(items);
|
||||
if (result) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
for (let key of Object.keys(map)) {
|
||||
const valid = await (function (methods) {
|
||||
return new Promise<boolean>(resolve => {
|
||||
methods.handleSubmit(
|
||||
() => resolve(true),
|
||||
() => resolve(false)
|
||||
)();
|
||||
});
|
||||
})(map[key]);
|
||||
|
||||
if (!valid) {
|
||||
return __('validateFailed');
|
||||
}
|
||||
}
|
||||
},
|
||||
[subForms]
|
||||
);
|
||||
|
||||
const {fields, append, update, remove} = useFieldArray({
|
||||
control,
|
||||
name: name,
|
||||
rules: finalRules
|
||||
});
|
||||
|
||||
if (!Array.isArray(columns)) {
|
||||
columns = [];
|
||||
}
|
||||
|
||||
const {errors} = useFormState({
|
||||
control
|
||||
});
|
||||
|
||||
const {trigger, setValue} = useFormContext();
|
||||
|
||||
// useFieldArray 的 update 会更新行 id,导致重新渲染
|
||||
// 正在编辑中的元素失去焦点,所以自己写一个
|
||||
const lightUpdate = React.useCallback(
|
||||
(index: number, value: any) => {
|
||||
// const arr = control._getFieldArray(name);
|
||||
// arr[index] = {...value};
|
||||
// control._updateFieldArray(name, arr);
|
||||
// trigger(name);
|
||||
// control._subjects.watch.next({});
|
||||
setValue(`${name}.${index}`, value);
|
||||
},
|
||||
[control]
|
||||
);
|
||||
|
||||
function renderBody() {
|
||||
const handleItemAdd = () => {
|
||||
const values = {...scaffold};
|
||||
append(values);
|
||||
|
||||
/** 开启滚动后新增元素定位到底部 */
|
||||
if (enableScroll && tableRef) {
|
||||
requestAnimationFrame(() => {
|
||||
tableRef?.current?.scrollIntoView?.({
|
||||
behavior: 'smooth',
|
||||
block: 'end',
|
||||
inline: 'nearest'
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
onItemAdd?.(values);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={cx(`Table`, `InputTable-UI`, className)}>
|
||||
<div
|
||||
className={cx(`Table-contentWrap`, {'is-fixed': enableScroll})}
|
||||
style={{maxHeight: enableScroll ? scroll.y : 'unset'}}
|
||||
ref={tBodyRef}
|
||||
>
|
||||
<div className={cx('Table-content')}>
|
||||
<table className={cx(`Table-table`, tableClassName)} ref={tableRef}>
|
||||
<thead className={cx(tableHeadClassName)}>
|
||||
<tr>
|
||||
{columns.map((item, index) => (
|
||||
<th key={index} className={item.className}>
|
||||
{item.thRender ? item.thRender() : item.title}
|
||||
</th>
|
||||
))}
|
||||
<th key="operation">{__('Table.operation')}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className={cx(tableBodyClassName)}>
|
||||
{fields.length ? (
|
||||
fields.map((field, index) => (
|
||||
<tr key={field.id}>
|
||||
<InputTableRow
|
||||
key="columns"
|
||||
control={control}
|
||||
update={lightUpdate}
|
||||
index={index}
|
||||
value={field}
|
||||
columns={columns}
|
||||
translate={__}
|
||||
classnames={cx}
|
||||
formRef={subFormRef}
|
||||
popOverContainer={popOverContainer}
|
||||
/>
|
||||
<td key="operation">
|
||||
<Button
|
||||
level="link"
|
||||
key="delete"
|
||||
disabled={
|
||||
removable === false ||
|
||||
!!(minLength && fields.length <= minLength)
|
||||
}
|
||||
className={cx('Table-delBtn')}
|
||||
onClick={() => remove(index)}
|
||||
>
|
||||
{__('delete')}
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
) : (
|
||||
<tr>
|
||||
<td colSpan={columns.length + 1}>
|
||||
<Icon
|
||||
icon="desk-empty"
|
||||
className={cx('Table-placeholder-empty-icon', 'icon')}
|
||||
/>
|
||||
{placeholder ?? __('placeholder.noData')}
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
{addable !== false && (!maxLength || fields.length < maxLength) ? (
|
||||
<div className={cx(`InputTable-toolbar`)}>
|
||||
<Button
|
||||
className={cx(addButtonClassName)}
|
||||
size="sm"
|
||||
{...addButtonProps}
|
||||
onClick={() => handleItemAdd()}
|
||||
>
|
||||
<Icon icon="plus" className="icon" />
|
||||
<span>{__(addButtonText || 'add')}</span>
|
||||
</Button>
|
||||
{footer?.()}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return wrap === false ? (
|
||||
renderBody()
|
||||
) : (
|
||||
<FormField
|
||||
className={fieldClassName}
|
||||
label={label}
|
||||
labelAlign={labelAlign}
|
||||
labelClassName={labelClassName}
|
||||
description={description}
|
||||
mode={mode}
|
||||
hasError={!!errors[name]?.message}
|
||||
errors={errors[name]?.message as any}
|
||||
>
|
||||
{renderBody()}
|
||||
</FormField>
|
||||
);
|
||||
}
|
||||
|
||||
export interface InputTableRowProps {
|
||||
value: any;
|
||||
control: Control<any>;
|
||||
columns: Array<{
|
||||
tdRender: tdRenderFunc;
|
||||
className?: string;
|
||||
}>;
|
||||
update: (index: number, data: Record<string, any>) => void;
|
||||
index: number;
|
||||
translate: TranslateFn;
|
||||
classnames: ClassNamesFn;
|
||||
formRef: (form: UseFormReturn | null, id: string) => void;
|
||||
popOverContainer?: any;
|
||||
}
|
||||
|
||||
export const InputTableRow = React.memo(function InputTableRow({
|
||||
value,
|
||||
columns,
|
||||
index,
|
||||
translate,
|
||||
update,
|
||||
formRef,
|
||||
classnames: cx,
|
||||
popOverContainer
|
||||
}: InputTableRowProps) {
|
||||
const indexRef = React.useRef(index);
|
||||
React.useEffect(() => {
|
||||
indexRef.current = index;
|
||||
}, [index]);
|
||||
|
||||
const methods = useSubForm(value, translate, (data: any) =>
|
||||
update(indexRef.current!, data)
|
||||
);
|
||||
React.useEffect(() => {
|
||||
formRef?.(methods, value.id);
|
||||
return () => {
|
||||
formRef?.(null, value.id);
|
||||
};
|
||||
}, [methods, value.id]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{columns.map((item, colIndex) => (
|
||||
<td key={colIndex} className={item.className}>
|
||||
{item.tdRender(
|
||||
{
|
||||
...methods,
|
||||
popOverContainer
|
||||
},
|
||||
colIndex,
|
||||
index
|
||||
)}
|
||||
</td>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
export default themeable(localeable(InputTable));
|
||||
3
packages/amis-ui/src/components/JSONSchemaEditor.tsx
Normal file
3
packages/amis-ui/src/components/JSONSchemaEditor.tsx
Normal file
@@ -0,0 +1,3 @@
|
||||
import JSONSchemaEditor from './schema-editor';
|
||||
|
||||
export default JSONSchemaEditor;
|
||||
119
packages/amis-ui/src/components/Layout.tsx
Normal file
119
packages/amis-ui/src/components/Layout.tsx
Normal file
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* @file Layout
|
||||
* @description 页面布局,支持左边栏、顶部、内容区域布局。
|
||||
* @author fex
|
||||
*
|
||||
* @param 参数说明:
|
||||
* * children 会渲染在内容区。
|
||||
* * header 头部区域
|
||||
* * aside 边栏
|
||||
* * asideClassName 边栏附加样式class
|
||||
* * footer 页脚
|
||||
* * folder 是否收起边栏
|
||||
* * asideFixed 边栏是否为固定模式,如果是会用 position:fixed 来定位.
|
||||
* * className 附件的样式名
|
||||
* * contentClassName 内容区域附加样式名称
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import {ClassNamesFn, themeable} from 'amis-core';
|
||||
|
||||
interface LayoutProps {
|
||||
header?: boolean | React.ReactNode;
|
||||
headerClassName?: string;
|
||||
aside?: boolean | React.ReactNode;
|
||||
asideClassName?: string;
|
||||
boxed?: boolean;
|
||||
folded?: boolean;
|
||||
asideFixed?: boolean;
|
||||
headerFixed?: boolean;
|
||||
className?: string;
|
||||
contentClassName?: string;
|
||||
footer?: boolean | React.ReactNode;
|
||||
offScreen?: boolean;
|
||||
classPrefix: string;
|
||||
classnames: ClassNamesFn;
|
||||
size?: 'sm' | 'base' | 'md' | 'lg';
|
||||
children?: React.ReactNode;
|
||||
bodyClassName?: string;
|
||||
mainClassName?: string;
|
||||
}
|
||||
|
||||
export function Layout({
|
||||
header,
|
||||
headerClassName,
|
||||
aside,
|
||||
asideClassName = '',
|
||||
children,
|
||||
className,
|
||||
contentClassName,
|
||||
folded,
|
||||
asideFixed = true,
|
||||
headerFixed = true,
|
||||
footer = false,
|
||||
offScreen = false,
|
||||
size,
|
||||
boxed,
|
||||
classnames: cx,
|
||||
bodyClassName,
|
||||
mainClassName
|
||||
}: LayoutProps) {
|
||||
let body = (
|
||||
<div className={cx(`Layout-body`, contentClassName)}>{children}</div>
|
||||
);
|
||||
|
||||
if (aside) {
|
||||
body = (
|
||||
<div className={cx('Layout-content')} role="main">
|
||||
{body}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
React.useEffect(() => {
|
||||
bodyClassName && document.body.classList.add(bodyClassName);
|
||||
|
||||
return () => {
|
||||
bodyClassName && document.body.classList.remove(bodyClassName);
|
||||
};
|
||||
}, [bodyClassName]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx(`Layout`, className, {
|
||||
'Layout--boxed': boxed,
|
||||
'Layout--withAside': !!aside,
|
||||
'Layout--headerFixed': header ? headerFixed : false,
|
||||
'Layout--asideFixed': aside ? asideFixed : false,
|
||||
'Layout--folded': folded,
|
||||
'Layout--offScreen': offScreen,
|
||||
[`Layout--${size}`]: size,
|
||||
'Layout--noFooter': !footer,
|
||||
'Layout--noHeader': !header
|
||||
})}
|
||||
>
|
||||
{header ? (
|
||||
<div className={cx('Layout-header', headerClassName)}>{header}</div>
|
||||
) : null}
|
||||
<div className={cx('Layout-main', mainClassName)}>
|
||||
{aside ? (
|
||||
<div className={cx(`Layout-aside`, asideClassName)}>
|
||||
<div className={cx('Layout-asideWrap')}>
|
||||
<div id="asideInner" className={cx('Layout-asideInner')}>
|
||||
{aside}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
{body}
|
||||
</div>
|
||||
{footer ? (
|
||||
<footer className={cx('Layout-footer')} role="footer">
|
||||
{footer}
|
||||
</footer>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default themeable(Layout);
|
||||
89
packages/amis-ui/src/components/Link.tsx
Normal file
89
packages/amis-ui/src/components/Link.tsx
Normal file
@@ -0,0 +1,89 @@
|
||||
import React from 'react';
|
||||
import {themeable, ThemeProps} from 'amis-core';
|
||||
import {autobind} from 'amis-core';
|
||||
import {Icon} from './icons';
|
||||
|
||||
export interface LinkProps
|
||||
extends ThemeProps,
|
||||
React.DOMAttributes<HTMLAnchorElement> {
|
||||
/**
|
||||
* 禁用
|
||||
*/
|
||||
disabled?: boolean;
|
||||
|
||||
/**
|
||||
* 图标
|
||||
*/
|
||||
icon?: string;
|
||||
|
||||
/**
|
||||
* 右侧图标
|
||||
*/
|
||||
rightIcon?: string;
|
||||
|
||||
href?: string;
|
||||
htmlTarget?: string;
|
||||
title?: string;
|
||||
children?: React.ReactNode | Array<React.ReactNode>;
|
||||
}
|
||||
|
||||
export class Link extends React.Component<LinkProps, object> {
|
||||
constructor(props: LinkProps) {
|
||||
super(props);
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleClick(e: React.MouseEvent<any>) {
|
||||
const {disabled, onClick} = this.props;
|
||||
if (disabled) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
return;
|
||||
}
|
||||
onClick?.(e);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
className,
|
||||
style,
|
||||
href,
|
||||
classnames: cx,
|
||||
disabled,
|
||||
htmlTarget,
|
||||
title,
|
||||
icon,
|
||||
rightIcon,
|
||||
children,
|
||||
classPrefix,
|
||||
theme,
|
||||
...rest
|
||||
} = this.props;
|
||||
|
||||
return (
|
||||
<a
|
||||
{...rest}
|
||||
href={href}
|
||||
target={htmlTarget}
|
||||
className={cx(
|
||||
`Link`,
|
||||
{
|
||||
'is-disabled': disabled
|
||||
},
|
||||
className
|
||||
)}
|
||||
style={style}
|
||||
title={title}
|
||||
onClick={this.handleClick}
|
||||
>
|
||||
{icon ? <Icon cx={cx} icon={icon} className="Link-icon" /> : null}
|
||||
{children}
|
||||
{rightIcon ? (
|
||||
<Icon cx={cx} icon={rightIcon} className="Link-icon" />
|
||||
) : null}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(Link);
|
||||
75
packages/amis-ui/src/components/ListGroup.tsx
Normal file
75
packages/amis-ui/src/components/ListGroup.tsx
Normal file
@@ -0,0 +1,75 @@
|
||||
import {ThemeProps, themeable} from 'amis-core';
|
||||
import React from 'react';
|
||||
|
||||
export interface ListGroupProps
|
||||
extends ThemeProps,
|
||||
Omit<React.InputHTMLAttributes<HTMLDivElement>, 'placeholder'> {
|
||||
expand?: boolean;
|
||||
items?: Array<any>;
|
||||
itemClassName?: string;
|
||||
style?: {
|
||||
[propName: string]: any;
|
||||
};
|
||||
itemRender: (item: any, index: number) => JSX.Element;
|
||||
placeholder?: JSX.Element;
|
||||
getItemProps?: (props: {item: any; index: number}) => any;
|
||||
}
|
||||
|
||||
export class ListGroup extends React.Component<ListGroupProps> {
|
||||
static defaultProps = {
|
||||
itemRender: (item: any) => <>{`${item}`}</>
|
||||
};
|
||||
|
||||
render() {
|
||||
const {
|
||||
classnames: cx,
|
||||
className,
|
||||
expand,
|
||||
placeholder,
|
||||
items,
|
||||
children,
|
||||
itemClassName,
|
||||
itemRender,
|
||||
getItemProps,
|
||||
classPrefix,
|
||||
...rest
|
||||
} = this.props;
|
||||
|
||||
return (
|
||||
<div
|
||||
{...rest}
|
||||
className={cx(
|
||||
'ListGroup',
|
||||
className,
|
||||
expand ? 'ListGroup--expanded' : ''
|
||||
)}
|
||||
>
|
||||
{Array.isArray(items) && items.length ? (
|
||||
items.map((item: any, index) => {
|
||||
const itemProps = getItemProps?.({item, index}) || {};
|
||||
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
{...itemProps}
|
||||
className={cx(
|
||||
'ListGroup-item',
|
||||
itemClassName,
|
||||
itemProps.className
|
||||
)}
|
||||
>
|
||||
{itemRender(item, index)}
|
||||
</div>
|
||||
);
|
||||
})
|
||||
) : placeholder ? (
|
||||
<div className={cx('Placeholder ListGroup-placeholder')}></div>
|
||||
) : null}
|
||||
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(ListGroup);
|
||||
126
packages/amis-ui/src/components/ListMenu.tsx
Normal file
126
packages/amis-ui/src/components/ListMenu.tsx
Normal file
@@ -0,0 +1,126 @@
|
||||
import {ThemeProps, themeable} from 'amis-core';
|
||||
import React from 'react';
|
||||
import {Options, Option} from 'amis-core';
|
||||
import {LocaleProps, localeable} from 'amis-core';
|
||||
import type {TestIdBuilder} from 'amis-core';
|
||||
|
||||
export interface ListMenuProps extends ThemeProps, LocaleProps {
|
||||
options: Options;
|
||||
disabled?: boolean;
|
||||
selectedOptions?: Options;
|
||||
highlightIndex?: number | null;
|
||||
onSelect?: (e: any, option: Option) => void;
|
||||
placeholder: string;
|
||||
itemRender: (option: Option) => JSX.Element;
|
||||
getItemProps: (props: {item: Option; index: number}) => any;
|
||||
prefix?: JSX.Element;
|
||||
children?: React.ReactNode | Array<React.ReactNode>;
|
||||
testIdBuilder?: TestIdBuilder;
|
||||
}
|
||||
|
||||
interface RenderResult {
|
||||
items: Array<JSX.Element>;
|
||||
index: number;
|
||||
}
|
||||
|
||||
export class ListMenu extends React.Component<ListMenuProps> {
|
||||
static defaultProps = {
|
||||
placeholder: 'placeholder.noOption',
|
||||
itemRender: (option: Option) => <>{option.label}</>,
|
||||
getItemProps: (props: {item: Option; index: number}) => null
|
||||
};
|
||||
|
||||
renderItem(result: RenderResult, option: Option, optionIndex: number) {
|
||||
const {
|
||||
classnames: cx,
|
||||
itemRender,
|
||||
disabled,
|
||||
getItemProps,
|
||||
highlightIndex,
|
||||
selectedOptions,
|
||||
mobileUI,
|
||||
onSelect,
|
||||
testIdBuilder
|
||||
} = this.props;
|
||||
|
||||
if (Array.isArray(option.children) && option.children.length) {
|
||||
const stackResult = {
|
||||
items: [],
|
||||
index: result.index
|
||||
};
|
||||
result.items.push(
|
||||
<div className={cx('ListMenu-group')} key={optionIndex}>
|
||||
<div className={cx('ListMenu-groupLabel')}>{itemRender(option)}</div>
|
||||
{
|
||||
option.children.reduce(
|
||||
(result: RenderResult, option, index) =>
|
||||
this.renderItem(result, option, index),
|
||||
stackResult
|
||||
).items
|
||||
}
|
||||
</div>
|
||||
);
|
||||
result.index = stackResult.index;
|
||||
return result;
|
||||
}
|
||||
|
||||
const index = result.index++;
|
||||
|
||||
result.items.push(
|
||||
<div
|
||||
className={cx(
|
||||
'ListMenu-item',
|
||||
option.className,
|
||||
disabled || option.disabled ? 'is-disabled' : '',
|
||||
index === highlightIndex ? 'is-highlight' : '',
|
||||
~(selectedOptions || []).indexOf(option) ? 'is-active' : ''
|
||||
)}
|
||||
key={index}
|
||||
onClick={onSelect ? (e: any) => onSelect(e, option) : undefined}
|
||||
{...testIdBuilder?.getChild(option.value || index).getTestId()}
|
||||
{...getItemProps({
|
||||
item: option,
|
||||
index: index
|
||||
})}
|
||||
>
|
||||
<div className={cx('ListMenu-itemLabel')}>{itemRender(option)}</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
classnames: cx,
|
||||
options,
|
||||
placeholder,
|
||||
prefix,
|
||||
children,
|
||||
mobileUI,
|
||||
selectedOptions
|
||||
} = this.props;
|
||||
const __ = this.props.translate;
|
||||
|
||||
return (
|
||||
<div className={cx('ListMenu', {'is-mobile': mobileUI})}>
|
||||
{prefix}
|
||||
{Array.isArray(options) && options.length ? (
|
||||
options.reduce(
|
||||
(result: RenderResult, option: Option, index) =>
|
||||
this.renderItem(result, option, index),
|
||||
{
|
||||
items: [],
|
||||
index: 0
|
||||
}
|
||||
).items
|
||||
) : (
|
||||
<span className={cx('ListMenu-placeholder')}>{__(placeholder)}</span>
|
||||
)}
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(localeable(ListMenu));
|
||||
306
packages/amis-ui/src/components/LocationPicker.tsx
Normal file
306
packages/amis-ui/src/components/LocationPicker.tsx
Normal file
@@ -0,0 +1,306 @@
|
||||
import React from 'react';
|
||||
import {themeable, ClassNamesFn, ThemeProps} from 'amis-core';
|
||||
import {Overlay} from 'amis-core';
|
||||
import {PopOver} from 'amis-core';
|
||||
import {Icon} from './icons';
|
||||
import {autobind} from 'amis-core';
|
||||
import Alert2 from './Alert2';
|
||||
import BaiduMapPicker from './BaiduMapPicker';
|
||||
import GaodeMapPicker from './GaodeMapPicker';
|
||||
import {LocaleProps, localeable} from 'amis-core';
|
||||
import PopUp from './PopUp';
|
||||
|
||||
export interface LocationProps extends ThemeProps, LocaleProps {
|
||||
vendor: 'baidu' | 'gaode' | 'tenxun';
|
||||
coordinatesType: 'bd09' | 'gcj02';
|
||||
placeholder: string;
|
||||
getLocationPlaceholder: string;
|
||||
clearable: boolean;
|
||||
ak: string;
|
||||
value?: {
|
||||
address: string;
|
||||
lat: number;
|
||||
lng: number;
|
||||
city?: string;
|
||||
};
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
popoverClassName?: string;
|
||||
onChange: (value: any) => void;
|
||||
popOverContainer?: any;
|
||||
autoSelectCurrentLoc?: boolean;
|
||||
onlySelectCurrentLoc?: boolean;
|
||||
hideViewControl?: boolean; // 隐藏地图控件,默认为false,即显示控件
|
||||
}
|
||||
|
||||
export interface LocationState {
|
||||
isFocused: boolean;
|
||||
isOpened: boolean;
|
||||
}
|
||||
|
||||
export class LocationPicker extends React.Component<
|
||||
LocationProps,
|
||||
LocationState
|
||||
> {
|
||||
static defaultProps = {
|
||||
placeholder: 'LocationPicker.placeholder',
|
||||
getLocationPlaceholder: 'LocationPicker.getLocation',
|
||||
clearable: false
|
||||
};
|
||||
domRef: React.RefObject<HTMLDivElement> = React.createRef();
|
||||
tempValue: any;
|
||||
state = {
|
||||
isFocused: false,
|
||||
isOpened: false
|
||||
};
|
||||
|
||||
@autobind
|
||||
handleKeyPress(e: React.KeyboardEvent) {
|
||||
if (e.key === ' ') {
|
||||
this.handleClick();
|
||||
e.preventDefault();
|
||||
}
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleFocus() {
|
||||
this.setState({
|
||||
isFocused: true
|
||||
});
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleBlur() {
|
||||
this.setState({
|
||||
isFocused: true
|
||||
});
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleClick() {
|
||||
this.state.isOpened ? this.close() : this.open();
|
||||
}
|
||||
|
||||
@autobind
|
||||
getTarget() {
|
||||
return this.domRef.current;
|
||||
}
|
||||
|
||||
@autobind
|
||||
getParent() {
|
||||
return this.domRef.current?.parentElement;
|
||||
}
|
||||
|
||||
@autobind
|
||||
open(fn?: () => void) {
|
||||
this.props.disabled ||
|
||||
this.setState(
|
||||
{
|
||||
isOpened: true
|
||||
},
|
||||
fn
|
||||
);
|
||||
this.tempValue = this.props.value;
|
||||
}
|
||||
|
||||
@autobind
|
||||
close() {
|
||||
this.setState({
|
||||
isOpened: false
|
||||
});
|
||||
}
|
||||
|
||||
@autobind
|
||||
clearValue(e: React.MouseEvent<any>) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const onChange = this.props.onChange;
|
||||
onChange('');
|
||||
}
|
||||
|
||||
@autobind
|
||||
handlePopOverClick(e: React.MouseEvent<any>) {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleChange(value: any) {
|
||||
if (value) {
|
||||
value = {
|
||||
...value,
|
||||
vendor: this.props.vendor
|
||||
};
|
||||
}
|
||||
this.props.onChange(value);
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleTempChange(value: any) {
|
||||
if (value) {
|
||||
value = {
|
||||
...value,
|
||||
vendor: this.props.vendor
|
||||
};
|
||||
}
|
||||
this.tempValue = value;
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleConfirm() {
|
||||
this.props.onChange(this.tempValue);
|
||||
this.close();
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
classnames: cx,
|
||||
value,
|
||||
className,
|
||||
popoverClassName,
|
||||
disabled,
|
||||
placeholder,
|
||||
getLocationPlaceholder,
|
||||
clearable,
|
||||
popOverContainer,
|
||||
vendor,
|
||||
coordinatesType,
|
||||
ak,
|
||||
mobileUI,
|
||||
autoSelectCurrentLoc,
|
||||
onlySelectCurrentLoc,
|
||||
hideViewControl = false
|
||||
} = this.props;
|
||||
const __ = this.props.translate;
|
||||
const {isFocused, isOpened} = this.state;
|
||||
|
||||
const picker = (() => {
|
||||
switch (vendor) {
|
||||
case 'baidu':
|
||||
return (
|
||||
<BaiduMapPicker
|
||||
ak={ak}
|
||||
value={value}
|
||||
placeholder={__('MapPicker.searchPlaceholder')}
|
||||
coordinatesType={coordinatesType}
|
||||
autoSelectCurrentLoc={autoSelectCurrentLoc}
|
||||
onlySelectCurrentLoc={onlySelectCurrentLoc}
|
||||
onChange={this.handleChange}
|
||||
hideViewControl={hideViewControl}
|
||||
/>
|
||||
);
|
||||
case 'gaode':
|
||||
return (
|
||||
<GaodeMapPicker
|
||||
ak={ak}
|
||||
value={value}
|
||||
coordinatesType={coordinatesType}
|
||||
onChange={this.handleChange}
|
||||
/>
|
||||
);
|
||||
default:
|
||||
return <Alert2>{__(`{{vendor}} 地图控件不支持`, {vendor})}</Alert2>;
|
||||
}
|
||||
})();
|
||||
|
||||
return (
|
||||
<div
|
||||
tabIndex={0}
|
||||
onKeyPress={this.handleKeyPress}
|
||||
onFocus={this.handleFocus}
|
||||
onBlur={this.handleBlur}
|
||||
className={cx(
|
||||
`LocationPicker`,
|
||||
{
|
||||
'is-mobile': mobileUI,
|
||||
'is-disabled': disabled,
|
||||
'is-focused': isFocused,
|
||||
'is-active': isOpened
|
||||
},
|
||||
className
|
||||
)}
|
||||
ref={this.domRef}
|
||||
onClick={this.handleClick}
|
||||
>
|
||||
{value ? (
|
||||
<span className={cx('LocationPicker-value')}>{value.address}</span>
|
||||
) : (
|
||||
<span className={cx('LocationPicker-placeholder')}>
|
||||
{__(onlySelectCurrentLoc ? getLocationPlaceholder : placeholder)}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{clearable && !disabled && value ? (
|
||||
<a className={cx('LocationPicker-clear')} onClick={this.clearValue}>
|
||||
<Icon icon="input-clear" className="icon" />
|
||||
</a>
|
||||
) : null}
|
||||
|
||||
<a className={cx('LocationPicker-toggler')}>
|
||||
<Icon icon="location" className="icon" />
|
||||
</a>
|
||||
|
||||
{mobileUI ? (
|
||||
<PopUp
|
||||
className={cx(`LocationPicker-popup`)}
|
||||
container={popOverContainer || this.getParent}
|
||||
isShow={isOpened}
|
||||
onHide={this.close}
|
||||
showConfirm
|
||||
onConfirm={this.handleConfirm}
|
||||
>
|
||||
<div className={cx('LocationPicker-popup-inner')}>
|
||||
{vendor === 'baidu' ? (
|
||||
<BaiduMapPicker
|
||||
ak={ak}
|
||||
value={value}
|
||||
placeholder={__('MapPicker.searchPlaceholder')}
|
||||
coordinatesType={coordinatesType}
|
||||
autoSelectCurrentLoc={autoSelectCurrentLoc}
|
||||
onlySelectCurrentLoc={onlySelectCurrentLoc}
|
||||
onChange={this.handleTempChange}
|
||||
hideViewControl={hideViewControl}
|
||||
/>
|
||||
) : (
|
||||
<Alert2>{__('{{vendor}} 地图控件不支持', {vendor})}</Alert2>
|
||||
)}
|
||||
</div>
|
||||
</PopUp>
|
||||
) : (
|
||||
<Overlay
|
||||
target={this.getTarget}
|
||||
container={popOverContainer || this.getParent}
|
||||
rootClose={false}
|
||||
show={isOpened}
|
||||
>
|
||||
<PopOver
|
||||
className={cx('LocationPicker-popover', popoverClassName)}
|
||||
onHide={this.close}
|
||||
overlay
|
||||
onClick={this.handlePopOverClick}
|
||||
style={{width: this.getTarget()?.offsetWidth}}
|
||||
>
|
||||
{vendor === 'baidu' ? (
|
||||
<BaiduMapPicker
|
||||
ak={ak}
|
||||
value={value}
|
||||
placeholder={__('MapPicker.searchPlaceholder')}
|
||||
coordinatesType={coordinatesType}
|
||||
autoSelectCurrentLoc={autoSelectCurrentLoc}
|
||||
onlySelectCurrentLoc={onlySelectCurrentLoc}
|
||||
onChange={this.handleChange}
|
||||
hideViewControl={hideViewControl}
|
||||
/>
|
||||
) : (
|
||||
<Alert2>{__('{{vendor}} 地图控件不支持', {vendor})}</Alert2>
|
||||
)}
|
||||
</PopOver>
|
||||
</Overlay>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const ThemedCity = themeable(localeable(LocationPicker));
|
||||
export default ThemedCity;
|
||||
80
packages/amis-ui/src/components/Markdown.tsx
Normal file
80
packages/amis-ui/src/components/Markdown.tsx
Normal file
@@ -0,0 +1,80 @@
|
||||
import React from 'react';
|
||||
|
||||
/**
|
||||
* @file markdown 解析
|
||||
*/
|
||||
|
||||
import markdownIt from 'markdown-it';
|
||||
// @ts-ignore
|
||||
import {html5Media} from 'markdown-it-html5-media';
|
||||
|
||||
const doMarkdown = markdownIt();
|
||||
doMarkdown.use(html5Media);
|
||||
|
||||
export function markdown(content: string, options?: markdownIt.Options) {
|
||||
if (options) {
|
||||
doMarkdown.set(options);
|
||||
}
|
||||
return doMarkdown.render(content);
|
||||
}
|
||||
|
||||
interface MarkdownProps {
|
||||
content: string;
|
||||
options: object;
|
||||
}
|
||||
|
||||
export default class Markdown extends React.Component<MarkdownProps> {
|
||||
dom: any;
|
||||
|
||||
static defaultProps = {
|
||||
content: '',
|
||||
options: {
|
||||
linkify: true
|
||||
}
|
||||
};
|
||||
|
||||
constructor(props: MarkdownProps) {
|
||||
super(props);
|
||||
this.htmlRef = this.htmlRef.bind(this);
|
||||
}
|
||||
|
||||
htmlRef(dom: any) {
|
||||
this.dom = dom;
|
||||
if (!dom) {
|
||||
return;
|
||||
}
|
||||
this._render();
|
||||
}
|
||||
|
||||
componentDidUpdate(nextProps: MarkdownProps) {
|
||||
if (this.props.content !== nextProps.content) {
|
||||
this._render();
|
||||
}
|
||||
}
|
||||
|
||||
async _render() {
|
||||
const {content, options} = this.props;
|
||||
this.dom.innerHTML = markdown(content, options);
|
||||
|
||||
// @ts-ignore 需要用户手动加载 katex
|
||||
if (typeof renderMathInElement === 'function') {
|
||||
// @ts-ignore
|
||||
renderMathInElement(this.dom, {
|
||||
delimiters: [
|
||||
{left: '$$', right: '$$', display: true},
|
||||
{left: '$', right: '$', display: false}
|
||||
]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<div
|
||||
data-testid="markdown-body"
|
||||
className="markdown-body"
|
||||
ref={this.htmlRef}
|
||||
></div>
|
||||
);
|
||||
}
|
||||
}
|
||||
3
packages/amis-ui/src/components/Menu.tsx
Normal file
3
packages/amis-ui/src/components/Menu.tsx
Normal file
@@ -0,0 +1,3 @@
|
||||
import Menu from './menu/index';
|
||||
|
||||
export default Menu;
|
||||
163
packages/amis-ui/src/components/MixedInput.tsx
Normal file
163
packages/amis-ui/src/components/MixedInput.tsx
Normal file
@@ -0,0 +1,163 @@
|
||||
import React from 'react';
|
||||
import {ThemeProps, themeable} from 'amis-core';
|
||||
import FieldValue from './condition-builder/Value';
|
||||
import {FieldSimple} from './condition-builder/types';
|
||||
import Select from './Select';
|
||||
|
||||
interface MixedInputProps extends ThemeProps {
|
||||
// 预留给渲染器的,如果后面要添加到渲染器里面
|
||||
renderInput?: (schema: any, props: any) => React.ReactNode;
|
||||
|
||||
value?: any;
|
||||
onChange?: (value: any) => void;
|
||||
|
||||
// 可以根据需要添加属性
|
||||
methods: Array<{
|
||||
label: string;
|
||||
value?: any;
|
||||
test?: (value: any, defaultMethod?: any) => boolean;
|
||||
convert?: (value: any, raw: any) => any;
|
||||
pipeIn?: (value: any) => any;
|
||||
pipeOut?: (value: any) => any;
|
||||
type?:
|
||||
| 'text'
|
||||
| 'number'
|
||||
| 'date'
|
||||
| 'time'
|
||||
| 'datetime'
|
||||
| 'select'
|
||||
| 'custom'
|
||||
| 'boolean'
|
||||
| string;
|
||||
inputSettings?: any;
|
||||
}>;
|
||||
|
||||
disabled?: boolean;
|
||||
hasError?: boolean;
|
||||
|
||||
popOverContainer?: any;
|
||||
}
|
||||
|
||||
const MixedInput: React.FC<MixedInputProps> = ({
|
||||
value,
|
||||
onChange,
|
||||
methods,
|
||||
hasError,
|
||||
disabled,
|
||||
classnames: cx,
|
||||
className,
|
||||
style,
|
||||
popOverContainer
|
||||
}) => {
|
||||
const [focused, setFocused] = React.useState(false);
|
||||
const handleFocus = React.useCallback(() => {
|
||||
setFocused(true);
|
||||
}, []);
|
||||
const handleBlur = React.useCallback(() => {
|
||||
setFocused(false);
|
||||
}, []);
|
||||
|
||||
const [defaultMethod, setDefaultMethod] = React.useState<any>(null);
|
||||
const method = React.useMemo(() => {
|
||||
if (!Array.isArray(methods) || !methods.length) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
methods.find(m => m.test && m.test(value, defaultMethod)) ||
|
||||
defaultMethod ||
|
||||
methods[0]
|
||||
);
|
||||
}, [value, methods, defaultMethod]);
|
||||
const options = React.useMemo(() => {
|
||||
return methods.map(m => ({
|
||||
label: m.label,
|
||||
value: m.value ?? m.label
|
||||
}));
|
||||
}, [methods]);
|
||||
const methodChange = React.useCallback(
|
||||
(methodType: any) => {
|
||||
const newMethod = methods.find(m => (m.value ?? m.label) === methodType);
|
||||
if (!newMethod) {
|
||||
return;
|
||||
}
|
||||
if (newMethod.convert) {
|
||||
// 如果有转换方法,先转换一下
|
||||
value = newMethod.convert(
|
||||
method?.pipeIn ? method.pipeIn(value) : value,
|
||||
value
|
||||
);
|
||||
} else {
|
||||
value = method?.pipeIn ? method.pipeIn(value) : value; // 如果有转换方法,先转换一下
|
||||
}
|
||||
|
||||
setDefaultMethod(newMethod);
|
||||
onChange?.(newMethod.pipeOut ? newMethod.pipeOut(value) : value);
|
||||
},
|
||||
[methods, method, value]
|
||||
);
|
||||
const inputValue = React.useMemo(() => {
|
||||
if (!method) {
|
||||
return value;
|
||||
}
|
||||
return method.pipeIn ? method.pipeIn(value) : value;
|
||||
}, [value, method]);
|
||||
const inputOnChange = React.useCallback(
|
||||
(newValue: any) => {
|
||||
if (method && method.pipeOut) {
|
||||
newValue = method.pipeOut(newValue);
|
||||
}
|
||||
onChange?.(newValue);
|
||||
},
|
||||
[method]
|
||||
);
|
||||
const field = React.useMemo((): FieldSimple => {
|
||||
if (!method) {
|
||||
return {
|
||||
type: 'text',
|
||||
label: 'whatever',
|
||||
name: 'whatever'
|
||||
};
|
||||
}
|
||||
return {
|
||||
...method.inputSettings,
|
||||
name: 'whatever',
|
||||
type: (method.type || 'text') as 'text',
|
||||
label: method.label
|
||||
};
|
||||
}, [method]);
|
||||
|
||||
return (
|
||||
<div
|
||||
style={style}
|
||||
className={cx(`InputGroup MixedInput`, className, {
|
||||
'is-focused': focused,
|
||||
'is-error': hasError,
|
||||
'is-disabled': disabled
|
||||
})}
|
||||
>
|
||||
<FieldValue
|
||||
className="MixedInput-input"
|
||||
disabled={disabled}
|
||||
field={field}
|
||||
value={inputValue}
|
||||
onChange={inputOnChange}
|
||||
onFocus={handleFocus}
|
||||
onBlur={handleBlur}
|
||||
/>
|
||||
<div className={cx('MixedInput-select')}>
|
||||
<Select
|
||||
className={cx('MixedInput-select')}
|
||||
value={method ? method.value ?? method.label : ''}
|
||||
options={options}
|
||||
disabled={disabled}
|
||||
simpleValue
|
||||
onChange={methodChange}
|
||||
clearable={false}
|
||||
popOverContainer={popOverContainer}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default themeable(MixedInput);
|
||||
427
packages/amis-ui/src/components/MobileDevTool.tsx
Normal file
427
packages/amis-ui/src/components/MobileDevTool.tsx
Normal file
@@ -0,0 +1,427 @@
|
||||
import React, {useEffect, useRef} from 'react';
|
||||
import {Icon} from './icons';
|
||||
import {Select} from 'amis-ui';
|
||||
import debounce from 'lodash/debounce';
|
||||
import {Portal} from 'react-overlays';
|
||||
|
||||
export const dimensions = [
|
||||
{
|
||||
name: 'custom',
|
||||
width: 375,
|
||||
height: 667
|
||||
},
|
||||
{
|
||||
name: 'iPhone SE',
|
||||
width: 375,
|
||||
height: 667
|
||||
},
|
||||
{
|
||||
name: 'iPhone XR',
|
||||
width: 414,
|
||||
height: 896
|
||||
},
|
||||
{
|
||||
name: 'iPhone 12 Pro',
|
||||
width: 390,
|
||||
height: 844
|
||||
},
|
||||
{
|
||||
name: 'iPhone 14 Pro Max',
|
||||
width: 430,
|
||||
height: 932
|
||||
},
|
||||
{
|
||||
name: 'Pixel 7',
|
||||
width: 412,
|
||||
height: 915
|
||||
},
|
||||
{
|
||||
name: 'Samsung Galaxy S8+',
|
||||
width: 360,
|
||||
height: 740
|
||||
},
|
||||
{
|
||||
name: 'Samsung Galaxy S20 Ultra',
|
||||
width: 412,
|
||||
height: 915
|
||||
},
|
||||
{
|
||||
name: 'iPad Mini',
|
||||
width: 768,
|
||||
height: 1024
|
||||
},
|
||||
{
|
||||
name: 'iPad Air',
|
||||
width: 820,
|
||||
height: 1180
|
||||
},
|
||||
{
|
||||
name: 'iPad Pro',
|
||||
width: 1024,
|
||||
height: 1366
|
||||
},
|
||||
{
|
||||
name: 'Surface Pro 7',
|
||||
width: 912,
|
||||
height: 1368
|
||||
},
|
||||
{
|
||||
name: 'Surface Duo',
|
||||
width: 540,
|
||||
height: 720
|
||||
},
|
||||
{
|
||||
name: 'Galaxy Z Fold 5',
|
||||
width: 344,
|
||||
height: 882
|
||||
},
|
||||
{
|
||||
name: 'Asus Zenfone Fold',
|
||||
width: 853,
|
||||
height: 1280
|
||||
},
|
||||
{
|
||||
name: 'Samsung Galaxy A51/71',
|
||||
width: 412,
|
||||
height: 914
|
||||
},
|
||||
{
|
||||
name: 'Nest Hub',
|
||||
width: 1024,
|
||||
height: 600
|
||||
},
|
||||
{
|
||||
name: 'Next Hub Max',
|
||||
width: 1280,
|
||||
height: 800
|
||||
}
|
||||
];
|
||||
|
||||
const scaleList = [50, 75, 100, 125, 150, 200];
|
||||
|
||||
export default function MobileDevTool(props: {
|
||||
container: HTMLElement | null;
|
||||
previewBody: HTMLElement | null;
|
||||
border?: number;
|
||||
onChangeScale?: (scale: number) => void;
|
||||
}) {
|
||||
const [dimension, setDimension] = React.useState(
|
||||
() =>
|
||||
JSON.parse(
|
||||
localStorage.getItem('amis-mobile-dev-tool-dimension') || 'null'
|
||||
) || dimensions[1]
|
||||
);
|
||||
const defaultScale = useRef<number>();
|
||||
const [scale, setScale] = React.useState(100);
|
||||
const [autoScale, setAutoScale] = React.useState(100);
|
||||
|
||||
const {container, previewBody, onChangeScale} = props;
|
||||
|
||||
const resizeObserver = new ResizeObserver(debounce(updateAutoScale, 300));
|
||||
|
||||
useEffect(() => {
|
||||
defaultScale.current = parseInt(
|
||||
localStorage.getItem('amis-mobile-dev-tool-scale') || '0',
|
||||
10
|
||||
);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (container && previewBody) {
|
||||
updatePreviewSize({
|
||||
width: dimension.width,
|
||||
height: dimension.height
|
||||
});
|
||||
let scale = defaultScale.current || 100;
|
||||
if (!defaultScale.current) {
|
||||
scale = Math.min(updateAutoScale(), 100);
|
||||
defaultScale.current = scale;
|
||||
}
|
||||
setScale(scale);
|
||||
onChangeScale?.(scale);
|
||||
|
||||
updatePreviewScale(scale);
|
||||
resizeObserver.observe(container);
|
||||
}
|
||||
return () => {
|
||||
if (container) {
|
||||
resizeObserver.unobserve(container);
|
||||
}
|
||||
if (previewBody) {
|
||||
previewBody.style.width = '';
|
||||
previewBody.style.height = '';
|
||||
previewBody.style.transform = '';
|
||||
}
|
||||
};
|
||||
}, [container, previewBody]);
|
||||
|
||||
function updateDimension(dimension: {
|
||||
width: number;
|
||||
height: number;
|
||||
name: string;
|
||||
}) {
|
||||
setDimension(dimension);
|
||||
localStorage.setItem(
|
||||
'amis-mobile-dev-tool-dimension',
|
||||
JSON.stringify(dimension)
|
||||
);
|
||||
}
|
||||
|
||||
function updateScale(scale: number) {
|
||||
setScale(scale);
|
||||
onChangeScale?.(scale);
|
||||
localStorage.setItem('amis-mobile-dev-tool-scale', scale + '');
|
||||
}
|
||||
|
||||
function updateAutoScale() {
|
||||
if (!container) {
|
||||
return 100;
|
||||
}
|
||||
const containerRect = container.getBoundingClientRect();
|
||||
const {width, height} = containerRect;
|
||||
const previewBodyWidth = previewBody?.clientWidth || 375;
|
||||
const previewBodyHeight = previewBody?.clientHeight || 667;
|
||||
let scale = Math.min(
|
||||
(width - 50) / previewBodyWidth,
|
||||
(height * 0.9) / previewBodyHeight
|
||||
);
|
||||
scale = Math.floor(scale * 100);
|
||||
setAutoScale(scale);
|
||||
return scale;
|
||||
}
|
||||
|
||||
function handleRotateScreen() {
|
||||
updateDimension({
|
||||
name: dimension.name,
|
||||
width: dimension.height,
|
||||
height: dimension.width
|
||||
});
|
||||
updatePreviewSize({
|
||||
width: dimension.height,
|
||||
height: dimension.width
|
||||
});
|
||||
updateAutoScale();
|
||||
}
|
||||
|
||||
function handleAutoScale() {
|
||||
updateScale(autoScale);
|
||||
updatePreviewScale(autoScale);
|
||||
}
|
||||
|
||||
function handleDimensionChange(item: any) {
|
||||
if (item) {
|
||||
const value = dimensions.find(n => n.name === item.value)!;
|
||||
updateDimension(value);
|
||||
updatePreviewSize(value);
|
||||
updateScale(100);
|
||||
updatePreviewScale(100);
|
||||
updateAutoScale();
|
||||
}
|
||||
}
|
||||
|
||||
function handleCustomInputDimensionChange(
|
||||
value: string,
|
||||
type: 'width' | 'height'
|
||||
) {
|
||||
const number = parseInt(value || '0', 10);
|
||||
const newDimension = {
|
||||
name: 'custom',
|
||||
width: type === 'width' ? number : dimension.width,
|
||||
height: type === 'height' ? number : dimension.height
|
||||
};
|
||||
updateDimension(newDimension);
|
||||
updatePreviewSize(newDimension);
|
||||
updateAutoScale();
|
||||
}
|
||||
|
||||
function updatePreviewSize(dimension: {width: number; height: number}) {
|
||||
if (previewBody) {
|
||||
const {border = 20} = props;
|
||||
// 预览区域宽高加上20px的padding
|
||||
previewBody.style.width = dimension.width + border + 'px';
|
||||
previewBody.style.height = dimension.height + border + 'px';
|
||||
}
|
||||
}
|
||||
|
||||
function updatePreviewScale(scale: number) {
|
||||
if (previewBody) {
|
||||
previewBody.style.transform =
|
||||
'translateX(-50%) scale(' + scale / 100 + ')';
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="ae-MobileDevTool">
|
||||
<div className="ae-MobileDevTool-dimensions">
|
||||
<label>尺寸:</label>
|
||||
<Select
|
||||
className="ae-MobileDevTool-select"
|
||||
value={dimension.name}
|
||||
onChange={handleDimensionChange}
|
||||
options={dimensions.map(n => ({
|
||||
label: n.name === 'custom' ? '自定义' : n.name,
|
||||
value: n.name
|
||||
}))}
|
||||
clearable={false}
|
||||
/>
|
||||
</div>
|
||||
<div className="ae-MobileDevTool-dimension">
|
||||
{dimension.name === 'custom' ? (
|
||||
<input
|
||||
className="ae-MobileDevTool-dimension-input"
|
||||
value={dimension.width}
|
||||
onChange={event => {
|
||||
const value = event.currentTarget.value;
|
||||
|
||||
handleCustomInputDimensionChange(value, 'width');
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<span>{dimension.width}</span>
|
||||
)}
|
||||
<span>×</span>
|
||||
{dimension.name === 'custom' ? (
|
||||
<input
|
||||
className="ae-MobileDevTool-dimension-input"
|
||||
value={dimension.height}
|
||||
onChange={event => {
|
||||
const value = event.currentTarget.value;
|
||||
|
||||
handleCustomInputDimensionChange(value, 'height');
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<span>{dimension.height}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="ae-MobileDevTool-right">
|
||||
<div className="ae-MobileDevTool-right-scale">
|
||||
<Select
|
||||
className="ae-MobileDevTool-select"
|
||||
clearable={false}
|
||||
value={scale}
|
||||
options={[
|
||||
...scaleList.map(n => ({
|
||||
label: `${n}%`,
|
||||
value: n
|
||||
}))
|
||||
]}
|
||||
onChange={(item: any) => {
|
||||
updateScale(item.value);
|
||||
updatePreviewScale(item.value);
|
||||
}}
|
||||
/>
|
||||
{!scaleList.includes(scale) && (
|
||||
<div className="ae-MobileDevTool-right-scale-auto-value">
|
||||
{scale}%
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
className="ae-MobileDevTool-right-scale-auto"
|
||||
onClick={handleAutoScale}
|
||||
>
|
||||
自适应
|
||||
</div>
|
||||
</div>
|
||||
<div onClick={handleRotateScreen}>
|
||||
<Icon
|
||||
icon="rotate-screen"
|
||||
className="ae-MobileDevTool-right-rotate-screen"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{dimension.name === 'custom' && (
|
||||
<CustomSizeHandle
|
||||
previewBody={previewBody}
|
||||
onChange={(w, h) => {
|
||||
updateDimension({
|
||||
name: 'custom',
|
||||
width: w - 20,
|
||||
height: h - 20
|
||||
});
|
||||
}}
|
||||
onEnd={updateAutoScale}
|
||||
scale={scale}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CustomSizeHandle(props: {
|
||||
previewBody: HTMLElement | null;
|
||||
scale: number;
|
||||
onChange: (w: number, h: number) => void;
|
||||
onEnd: () => void;
|
||||
}) {
|
||||
const {previewBody, scale = 1, onChange, onEnd} = props;
|
||||
|
||||
function handleRightDown(e: any) {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
document.body.classList.add('width-move');
|
||||
document.addEventListener('mousemove', handleRightDragMove);
|
||||
document.addEventListener('mouseup', handleRightDragEnd);
|
||||
}
|
||||
|
||||
function handleRightDragMove(e: any) {
|
||||
e.stopPropagation();
|
||||
if (previewBody) {
|
||||
let w = previewBody.clientWidth;
|
||||
w += e.movementX;
|
||||
w = Math.max(70, w);
|
||||
previewBody.style.width = w + 'px';
|
||||
onChange?.(w, previewBody.clientHeight);
|
||||
}
|
||||
}
|
||||
|
||||
function handleRightDragEnd() {
|
||||
document.body.classList.remove('width-move');
|
||||
document.removeEventListener('mousemove', handleRightDragMove);
|
||||
document.removeEventListener('mouseup', handleRightDragEnd);
|
||||
onEnd();
|
||||
}
|
||||
|
||||
function handleBottomDown(e: any) {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
document.body.classList.add('height-move');
|
||||
document.addEventListener('mousemove', handleBottomDragMove);
|
||||
document.addEventListener('mouseup', handleBottomDragEnd);
|
||||
}
|
||||
|
||||
function handleBottomDragMove(e: any) {
|
||||
e.stopPropagation();
|
||||
if (previewBody) {
|
||||
let h = previewBody.clientHeight;
|
||||
h += e.movementY;
|
||||
h = Math.max(70, h);
|
||||
previewBody.style.height = h + 'px';
|
||||
onChange(previewBody.clientWidth, h);
|
||||
}
|
||||
}
|
||||
|
||||
function handleBottomDragEnd() {
|
||||
document.body.classList.remove('height-move');
|
||||
document.removeEventListener('mousemove', handleBottomDragMove);
|
||||
document.removeEventListener('mouseup', handleBottomDragEnd);
|
||||
onEnd();
|
||||
}
|
||||
|
||||
return (
|
||||
<Portal container={() => previewBody}>
|
||||
<>
|
||||
<div
|
||||
className="ae-MobileDevTool-rightHandle"
|
||||
onMouseDown={handleRightDown}
|
||||
style={{transform: `scale(${1 / (scale / 100)})`}}
|
||||
></div>
|
||||
<div
|
||||
className="ae-MobileDevTool-bottomHandle"
|
||||
onMouseDown={handleBottomDown}
|
||||
style={{transform: `scale(${1 / (scale / 100)})`}}
|
||||
></div>
|
||||
</>
|
||||
</Portal>
|
||||
);
|
||||
}
|
||||
481
packages/amis-ui/src/components/Modal.tsx
Normal file
481
packages/amis-ui/src/components/Modal.tsx
Normal file
@@ -0,0 +1,481 @@
|
||||
/**
|
||||
* @file Modal
|
||||
* @description
|
||||
* @author fex
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import Transition, {
|
||||
ENTERED,
|
||||
ENTERING,
|
||||
EXITING,
|
||||
EXITED
|
||||
} from 'react-transition-group/Transition';
|
||||
import Portal from 'react-overlays/Portal';
|
||||
import {current, addModal, removeModal} from './ModalManager';
|
||||
import {ClassNamesFn, themeable, ThemeProps} from 'amis-core';
|
||||
import {Icon} from './icons';
|
||||
import {LocaleProps, localeable} from 'amis-core';
|
||||
import {autobind, getScrollbarWidth} from 'amis-core';
|
||||
import {
|
||||
DraggableCore,
|
||||
type DraggableBounds,
|
||||
type DraggableData,
|
||||
type DraggableEvent
|
||||
} from 'react-draggable';
|
||||
import isNumber from 'lodash/isNumber';
|
||||
|
||||
export const getContainerWithFullscreen =
|
||||
(container?: () => HTMLElement | HTMLElement | null) => () => {
|
||||
const envContainer =
|
||||
typeof container === 'function' ? container() : container;
|
||||
|
||||
// 获取当前全屏元素
|
||||
const fullscreenElement = document.fullscreenElement;
|
||||
|
||||
if (
|
||||
fullscreenElement &&
|
||||
(!envContainer || !fullscreenElement.contains(envContainer))
|
||||
) {
|
||||
return fullscreenElement as HTMLElement;
|
||||
}
|
||||
return envContainer || null;
|
||||
};
|
||||
|
||||
export interface ModalProps extends ThemeProps, LocaleProps {
|
||||
className?: string;
|
||||
contentClassName?: string;
|
||||
size?: any;
|
||||
width?: any;
|
||||
height?: any;
|
||||
overlay?: boolean;
|
||||
onHide: (e: any) => void;
|
||||
closeOnEsc?: boolean;
|
||||
closeOnOutside?: boolean;
|
||||
container?: any;
|
||||
show?: boolean;
|
||||
disabled?: boolean;
|
||||
onExited?: () => void;
|
||||
onEntered?: () => void;
|
||||
children?: React.ReactNode | Array<React.ReactNode>;
|
||||
modalClassName?: string;
|
||||
modalMaskClassName?: string;
|
||||
draggable?: boolean;
|
||||
}
|
||||
|
||||
export interface ModalState {
|
||||
bounds?: DraggableBounds;
|
||||
dragPos?: {x: number; y: number};
|
||||
}
|
||||
|
||||
const fadeStyles: {
|
||||
[propName: string]: string;
|
||||
} = {
|
||||
[ENTERING]: 'in',
|
||||
[ENTERED]: 'in',
|
||||
[EXITING]: 'out'
|
||||
};
|
||||
|
||||
const contentFadeStyles: {
|
||||
[propName: string]: string;
|
||||
} = {
|
||||
[ENTERING]: 'in',
|
||||
[ENTERED]: '',
|
||||
[EXITING]: 'out'
|
||||
};
|
||||
|
||||
export class Modal extends React.Component<ModalProps, ModalState> {
|
||||
static defaultProps = {
|
||||
container: document.body,
|
||||
size: '',
|
||||
overlay: true,
|
||||
draggable: false
|
||||
};
|
||||
|
||||
isRootClosed = false;
|
||||
modalDom: HTMLElement;
|
||||
|
||||
static Header = themeable(
|
||||
localeable(
|
||||
({
|
||||
classnames: cx,
|
||||
className,
|
||||
showCloseButton,
|
||||
onClose,
|
||||
children,
|
||||
classPrefix,
|
||||
translate: __,
|
||||
forwardedRef,
|
||||
...rest
|
||||
}: ThemeProps &
|
||||
LocaleProps & {
|
||||
className?: string;
|
||||
showCloseButton?: boolean;
|
||||
onClose?: () => void;
|
||||
children?: React.ReactNode;
|
||||
forwardedRef?: any;
|
||||
} & React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div {...rest} className={cx('Modal-header', className)}>
|
||||
{showCloseButton !== false ? (
|
||||
<a
|
||||
data-tooltip={__('Dialog.close')}
|
||||
data-position="left"
|
||||
onClick={onClose}
|
||||
className={cx('Modal-close')}
|
||||
>
|
||||
<Icon icon="close" className="icon" />
|
||||
</a>
|
||||
) : null}
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
static Title = themeable(
|
||||
({
|
||||
classnames: cx,
|
||||
className,
|
||||
children,
|
||||
classPrefix,
|
||||
forwardedRef,
|
||||
...rest
|
||||
}: ThemeProps & {
|
||||
className?: string;
|
||||
children?: React.ReactNode;
|
||||
forwardedRef?: any;
|
||||
} & React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div {...rest} className={cx('Modal-title', className)}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
);
|
||||
|
||||
static Body = themeable(
|
||||
({
|
||||
classnames: cx,
|
||||
className,
|
||||
children,
|
||||
classPrefix,
|
||||
forwardedRef,
|
||||
...rest
|
||||
}: ThemeProps & {
|
||||
className?: string;
|
||||
children?: React.ReactNode;
|
||||
forwardedRef?: any;
|
||||
} & React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div {...rest} className={cx('Modal-body', className)}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
);
|
||||
|
||||
static Footer = themeable(
|
||||
({
|
||||
classnames: cx,
|
||||
className,
|
||||
children,
|
||||
classPrefix,
|
||||
forwardedRef,
|
||||
...rest
|
||||
}: ThemeProps & {
|
||||
className?: string;
|
||||
children?: React.ReactNode;
|
||||
forwardedRef?: any;
|
||||
} & React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div {...rest} className={cx('Modal-footer', className)}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
);
|
||||
|
||||
state: Readonly<ModalState> = {dragPos: undefined};
|
||||
|
||||
componentDidMount() {
|
||||
if (this.props.show) {
|
||||
this.handleEnter();
|
||||
this.handleEntered();
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
if (this.props.show) {
|
||||
this.handleExited();
|
||||
}
|
||||
}
|
||||
|
||||
handleEnter = () => {
|
||||
document.body.classList.add(`is-modalOpened`);
|
||||
if (
|
||||
window.innerWidth - document.documentElement.clientWidth > 0 ||
|
||||
document.body.scrollHeight > document.body.clientHeight
|
||||
) {
|
||||
const scrollbarWidth = getScrollbarWidth();
|
||||
document.body.style.width = `calc(100% - ${scrollbarWidth}px)`;
|
||||
}
|
||||
};
|
||||
|
||||
handleEntered = () => {
|
||||
const onEntered = this.props.onEntered;
|
||||
|
||||
document.body.addEventListener(
|
||||
'mousedown',
|
||||
this.handleRootMouseDownCapture,
|
||||
true
|
||||
);
|
||||
document.body.addEventListener(
|
||||
'mouseup',
|
||||
this.handleRootMouseUpCapture,
|
||||
true
|
||||
);
|
||||
document.body.addEventListener('mouseup', this.handleRootMouseUp);
|
||||
|
||||
onEntered && onEntered();
|
||||
};
|
||||
handleExited = () => {
|
||||
const onExited = this.props.onExited;
|
||||
|
||||
document.body.removeEventListener('mouseup', this.handleRootMouseUp);
|
||||
document.body.removeEventListener(
|
||||
'mousedown',
|
||||
this.handleRootMouseDownCapture,
|
||||
true
|
||||
);
|
||||
document.body.removeEventListener(
|
||||
'mouseup',
|
||||
this.handleRootMouseUpCapture,
|
||||
true
|
||||
);
|
||||
|
||||
onExited && onExited();
|
||||
setTimeout(() => {
|
||||
if (!document.querySelector('.amis-dialog-widget')) {
|
||||
document.body.classList.remove(`is-modalOpened`);
|
||||
document.body.style.width = '';
|
||||
}
|
||||
}, 200);
|
||||
};
|
||||
|
||||
modalRef = (ref: any) => {
|
||||
this.modalDom = ref;
|
||||
const {classPrefix: ns} = this.props;
|
||||
if (ref) {
|
||||
addModal(this);
|
||||
(ref as HTMLElement).classList.add(`${ns}Modal--${current()}th`);
|
||||
} else {
|
||||
removeModal(this);
|
||||
}
|
||||
};
|
||||
|
||||
@autobind
|
||||
handleRootMouseDownCapture(e: MouseEvent) {
|
||||
const target = e.target as HTMLElement;
|
||||
const {closeOnOutside, classPrefix: ns, mobileUI} = this.props;
|
||||
const isLeftButton =
|
||||
(e.button === 1 && window.event !== null) || e.button === 0;
|
||||
|
||||
this.isRootClosed = !!(
|
||||
isLeftButton &&
|
||||
closeOnOutside &&
|
||||
target &&
|
||||
this.modalDom &&
|
||||
((!mobileUI &&
|
||||
!this.modalDom.contains(target) &&
|
||||
!target.closest('[role=dialog]')) ||
|
||||
(target.matches(`.${ns}Modal`) && target === this.modalDom))
|
||||
); // 干脆过滤掉来自弹框里面的点击
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleRootMouseUpCapture(e: MouseEvent) {
|
||||
// mousedown 的时候不在弹窗里面,则不需要判断了
|
||||
if (!this.isRootClosed) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 再判断 mouseup 的时候是不是在弹窗里面
|
||||
this.handleRootMouseDownCapture(e);
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleRootMouseUp(e: MouseEvent) {
|
||||
const {onHide} = this.props;
|
||||
this.isRootClosed && !e.defaultPrevented && onHide(e);
|
||||
}
|
||||
|
||||
// #region 处理dialog拖动
|
||||
|
||||
handleDragStart = (_event: DraggableEvent, uiData: DraggableData) => {
|
||||
const node = uiData.node;
|
||||
const {offsetParent} = node;
|
||||
if (!node || !offsetParent) {
|
||||
return;
|
||||
}
|
||||
const {clientWidth, clientHeight} = window.document.documentElement;
|
||||
const nodeStyle = getComputedStyle(node);
|
||||
const marginTop = parseInt(nodeStyle.marginTop, 10);
|
||||
const nodeWidth = parseInt(nodeStyle.width, 10);
|
||||
const nodeHeight = parseInt(nodeStyle.height, 10);
|
||||
const bounds = {
|
||||
left: 0,
|
||||
right: clientWidth - nodeWidth,
|
||||
top: -marginTop,
|
||||
bottom: clientHeight - nodeHeight - marginTop
|
||||
};
|
||||
const parentRect = offsetParent.getBoundingClientRect();
|
||||
const clientRect = node.getBoundingClientRect();
|
||||
const cLeft = clientRect.left;
|
||||
const pLeft = parentRect.left;
|
||||
const cTop = clientRect.top;
|
||||
const pTop = parentRect.top;
|
||||
const left = cLeft - pLeft + offsetParent.scrollLeft;
|
||||
const top = cTop - pTop + offsetParent.scrollTop - marginTop;
|
||||
this.setState({dragPos: {x: left, y: top}, bounds});
|
||||
// 阻止冒泡 存在弹窗里面套弹窗
|
||||
_event.stopPropagation();
|
||||
};
|
||||
|
||||
handleDrag = (e: DraggableEvent, {deltaX, deltaY}: DraggableData) => {
|
||||
e.stopPropagation();
|
||||
if (!this.state.dragPos) {
|
||||
return;
|
||||
}
|
||||
const {
|
||||
dragPos: {x, y},
|
||||
bounds
|
||||
} = this.state;
|
||||
|
||||
let calcY = y + deltaY;
|
||||
let calcX = x + deltaX;
|
||||
|
||||
// 防止拖动到屏幕外 处理边界
|
||||
if (isNumber(bounds?.right)) {
|
||||
calcX = Math.min(calcX, bounds!.right);
|
||||
}
|
||||
if (isNumber(bounds?.bottom)) {
|
||||
calcY = Math.min(calcY, bounds!.bottom);
|
||||
}
|
||||
if (isNumber(bounds?.left)) {
|
||||
calcX = Math.max(calcX, bounds!.left);
|
||||
}
|
||||
if (isNumber(bounds?.top)) {
|
||||
calcY = Math.max(calcY, bounds!.top);
|
||||
}
|
||||
this.setState({dragPos: {x: calcX, y: calcY}});
|
||||
};
|
||||
|
||||
handleDragStop = (e: DraggableEvent) => {
|
||||
e.stopPropagation();
|
||||
};
|
||||
|
||||
getDragStyle = (): React.CSSProperties => {
|
||||
const {draggable} = this.props;
|
||||
const {dragPos} = this.state;
|
||||
if (!dragPos || !draggable) {
|
||||
return {};
|
||||
}
|
||||
const {x, y} = dragPos;
|
||||
return {
|
||||
top: `${y}px`,
|
||||
left: `${x}px`,
|
||||
position: 'absolute'
|
||||
};
|
||||
};
|
||||
|
||||
// #endregion
|
||||
|
||||
render() {
|
||||
const {
|
||||
className,
|
||||
contentClassName,
|
||||
children,
|
||||
container,
|
||||
show,
|
||||
size,
|
||||
style,
|
||||
overlay,
|
||||
width,
|
||||
height,
|
||||
modalClassName,
|
||||
modalMaskClassName,
|
||||
classnames: cx,
|
||||
mobileUI,
|
||||
draggable,
|
||||
classPrefix
|
||||
} = this.props;
|
||||
|
||||
let _style = {
|
||||
width: style?.width ? style?.width : width,
|
||||
height: style?.height ? style?.height : height
|
||||
};
|
||||
return (
|
||||
<Transition
|
||||
mountOnEnter
|
||||
unmountOnExit
|
||||
appear
|
||||
in={show}
|
||||
timeout={500}
|
||||
onEnter={this.handleEnter}
|
||||
onExited={this.handleExited}
|
||||
onEntered={this.handleEntered}
|
||||
>
|
||||
{(status: string) => (
|
||||
<Portal container={getContainerWithFullscreen(container)}>
|
||||
<div
|
||||
ref={this.modalRef}
|
||||
role="dialog"
|
||||
className={cx(
|
||||
`amis-dialog-widget Modal`,
|
||||
{
|
||||
[`Modal--${size}`]: size
|
||||
},
|
||||
className
|
||||
)}
|
||||
>
|
||||
{overlay ? (
|
||||
<div
|
||||
className={cx(
|
||||
`Modal-overlay`,
|
||||
fadeStyles[status],
|
||||
modalMaskClassName
|
||||
)}
|
||||
/>
|
||||
) : null}
|
||||
<DraggableCore
|
||||
disabled={!draggable || mobileUI}
|
||||
onStart={this.handleDragStart}
|
||||
onDrag={this.handleDrag}
|
||||
onStop={this.handleDragStop}
|
||||
cancel="Icon, svg, a, svg *"
|
||||
handle={`.${classPrefix}Modal-header`}
|
||||
>
|
||||
<div
|
||||
className={cx(
|
||||
`Modal-content`,
|
||||
draggable && !mobileUI ? 'Modal-draggable' : '',
|
||||
size === 'custom' ? 'Modal-content-custom' : '',
|
||||
contentClassName,
|
||||
modalClassName,
|
||||
contentFadeStyles[status]
|
||||
)}
|
||||
style={{..._style, ...this.getDragStyle()}}
|
||||
>
|
||||
{status === EXITED ? null : children}
|
||||
</div>
|
||||
</DraggableCore>
|
||||
</div>
|
||||
</Portal>
|
||||
)}
|
||||
</Transition>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const FinalModal = themeable(localeable(Modal));
|
||||
|
||||
export default FinalModal as typeof FinalModal & {
|
||||
Header: typeof Modal.Header;
|
||||
Title: typeof Modal.Title;
|
||||
Body: typeof Modal.Body;
|
||||
Footer: typeof Modal.Footer;
|
||||
};
|
||||
49
packages/amis-ui/src/components/ModalManager.ts
Normal file
49
packages/amis-ui/src/components/ModalManager.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* @file ModalManager
|
||||
* @description
|
||||
* @author fex
|
||||
*/
|
||||
|
||||
import keycode from 'keycode';
|
||||
|
||||
interface ModalComponent
|
||||
extends React.Component<{
|
||||
onHide: (e: any) => void;
|
||||
disabled?: boolean;
|
||||
closeOnEsc?: boolean;
|
||||
}> {}
|
||||
|
||||
let modals: Array<ModalComponent> = [];
|
||||
|
||||
export function current() {
|
||||
return modals.length;
|
||||
}
|
||||
|
||||
export function currentModal(): ModalComponent | void {
|
||||
return modals[modals.length - 1];
|
||||
}
|
||||
|
||||
export function addModal(modal: ModalComponent) {
|
||||
modals.push(modal);
|
||||
}
|
||||
|
||||
export function removeModal(modal: ModalComponent) {
|
||||
modals = modals.filter(el => el !== modal);
|
||||
}
|
||||
|
||||
window.addEventListener('keydown', handleWindowKeyDown);
|
||||
|
||||
function handleWindowKeyDown(e: Event) {
|
||||
const code = keycode(e);
|
||||
if (code !== 'esc') {
|
||||
return;
|
||||
}
|
||||
let modal = currentModal();
|
||||
if (!modal) {
|
||||
return;
|
||||
}
|
||||
const {disabled, closeOnEsc} = modal.props;
|
||||
if (closeOnEsc && !disabled && !e.defaultPrevented) {
|
||||
modal.props.onHide(e);
|
||||
}
|
||||
}
|
||||
731
packages/amis-ui/src/components/MonthRangePicker.tsx
Normal file
731
packages/amis-ui/src/components/MonthRangePicker.tsx
Normal file
@@ -0,0 +1,731 @@
|
||||
/**
|
||||
* @file MonthRangePicker
|
||||
* @description 月份范围选择器
|
||||
* @author fex
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import moment from 'moment';
|
||||
import {findDOMNode} from 'react-dom';
|
||||
import cx from 'classnames';
|
||||
import {Icon} from './icons';
|
||||
import {Overlay} from 'amis-core';
|
||||
import Calendar from './calendar/Calendar';
|
||||
import {PopOver} from 'amis-core';
|
||||
import PopUp from './PopUp';
|
||||
import {themeable, ThemeProps} from 'amis-core';
|
||||
|
||||
import {noop} from 'amis-core';
|
||||
import {LocaleProps, localeable} from 'amis-core';
|
||||
import {DateRangePicker} from './DateRangePicker';
|
||||
import capitalize from 'lodash/capitalize';
|
||||
import {ShortCuts, ShortCutDateRange} from './DatePicker';
|
||||
import {availableShortcuts} from './DateRangePicker';
|
||||
import CalendarMobile from './CalendarMobile';
|
||||
import type {PlainObject} from 'amis-core';
|
||||
|
||||
export interface MonthRangePickerProps extends ThemeProps, LocaleProps {
|
||||
className?: string;
|
||||
popoverClassName?: string;
|
||||
placeholder?: string;
|
||||
theme?: any;
|
||||
format: string;
|
||||
utc?: boolean;
|
||||
inputFormat?: string;
|
||||
timeFormat?: string;
|
||||
/**
|
||||
* @deprecated 3.1.0后废弃,用shortcuts替代
|
||||
*/
|
||||
ranges?: string | Array<ShortCuts>;
|
||||
shortcuts?: string | Array<ShortCuts>;
|
||||
clearable?: boolean;
|
||||
minDate?: moment.Moment;
|
||||
maxDate?: moment.Moment;
|
||||
minDuration?: moment.Duration;
|
||||
maxDuration?: moment.Duration;
|
||||
joinValues: boolean;
|
||||
delimiter: string;
|
||||
value?: any;
|
||||
onChange: (value: any) => void;
|
||||
data?: any;
|
||||
disabled?: boolean;
|
||||
closeOnSelect?: boolean;
|
||||
overlayPlacement: string;
|
||||
resetValue?: any;
|
||||
popOverContainer?: any;
|
||||
embed?: boolean;
|
||||
onFocus?: Function;
|
||||
onBlur?: Function;
|
||||
label?: string | false;
|
||||
}
|
||||
|
||||
export interface MonthRangePickerState {
|
||||
isOpened: boolean;
|
||||
isFocused: boolean;
|
||||
startDate?: moment.Moment;
|
||||
endDate?: moment.Moment;
|
||||
}
|
||||
|
||||
export class MonthRangePicker extends React.Component<
|
||||
MonthRangePickerProps,
|
||||
MonthRangePickerState
|
||||
> {
|
||||
static defaultProps = {
|
||||
placeholder: 'MonthRange.placeholder',
|
||||
format: 'YYYY-MM',
|
||||
inputFormat: 'YYYY-MM',
|
||||
joinValues: true,
|
||||
clearable: true,
|
||||
delimiter: ',',
|
||||
resetValue: '',
|
||||
closeOnSelect: true,
|
||||
overlayPlacement: 'auto'
|
||||
};
|
||||
|
||||
innerDom: any;
|
||||
popover: any;
|
||||
input?: HTMLInputElement;
|
||||
|
||||
dom: React.RefObject<HTMLDivElement>;
|
||||
nextMonth = moment().add(1, 'year').startOf('month');
|
||||
|
||||
constructor(props: MonthRangePickerProps) {
|
||||
super(props);
|
||||
|
||||
this.open = this.open.bind(this);
|
||||
this.close = this.close.bind(this);
|
||||
this.handleStartChange = this.handleStartChange.bind(this);
|
||||
this.handleEndChange = this.handleEndChange.bind(this);
|
||||
this.handleFocus = this.handleFocus.bind(this);
|
||||
this.handleBlur = this.handleBlur.bind(this);
|
||||
this.checkStartIsValidDate = this.checkStartIsValidDate.bind(this);
|
||||
this.checkEndIsValidDate = this.checkEndIsValidDate.bind(this);
|
||||
this.confirm = this.confirm.bind(this);
|
||||
this.clearValue = this.clearValue.bind(this);
|
||||
this.dom = React.createRef();
|
||||
this.handleClick = this.handleClick.bind(this);
|
||||
this.handleKeyPress = this.handleKeyPress.bind(this);
|
||||
this.handlePopOverClick = this.handlePopOverClick.bind(this);
|
||||
this.renderMonth = this.renderMonth.bind(this);
|
||||
this.handleMobileChange = this.handleMobileChange.bind(this);
|
||||
const {format, joinValues, delimiter, value} = this.props;
|
||||
|
||||
this.state = {
|
||||
isOpened: false,
|
||||
isFocused: false,
|
||||
...DateRangePicker.unFormatValue(
|
||||
value,
|
||||
format,
|
||||
joinValues,
|
||||
delimiter,
|
||||
this.props.data
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps: MonthRangePickerProps) {
|
||||
const props = this.props;
|
||||
const {value, format, joinValues, delimiter, data} = props;
|
||||
|
||||
if (prevProps.value !== value) {
|
||||
this.setState({
|
||||
...DateRangePicker.unFormatValue(
|
||||
value,
|
||||
format,
|
||||
joinValues,
|
||||
delimiter,
|
||||
data
|
||||
)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
focus() {
|
||||
if (!this.dom.current || this.props.disabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.dom.current.focus();
|
||||
}
|
||||
|
||||
blur() {
|
||||
if (!this.dom.current || this.props.disabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.dom.current.blur();
|
||||
}
|
||||
|
||||
handleFocus(e: React.SyntheticEvent<HTMLDivElement>) {
|
||||
this.setState({
|
||||
isFocused: true
|
||||
});
|
||||
const {onFocus} = this.props;
|
||||
onFocus && onFocus(e);
|
||||
}
|
||||
|
||||
handleBlur(e: React.SyntheticEvent<HTMLDivElement>) {
|
||||
this.setState({
|
||||
isFocused: false
|
||||
});
|
||||
const {onBlur} = this.props;
|
||||
onBlur && onBlur(e);
|
||||
}
|
||||
|
||||
open() {
|
||||
if (this.props.disabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.setState({
|
||||
isOpened: true
|
||||
});
|
||||
}
|
||||
|
||||
close() {
|
||||
this.setState(
|
||||
{
|
||||
isOpened: false
|
||||
},
|
||||
this.blur
|
||||
);
|
||||
}
|
||||
|
||||
handleClick() {
|
||||
this.state.isOpened ? this.close() : this.open();
|
||||
}
|
||||
|
||||
handlePopOverClick(e: React.MouseEvent<any>) {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
}
|
||||
|
||||
handleKeyPress(e: React.KeyboardEvent) {
|
||||
if (e.key === ' ') {
|
||||
this.handleClick();
|
||||
e.preventDefault();
|
||||
}
|
||||
}
|
||||
|
||||
confirm() {
|
||||
if (!this.state.startDate || !this.state.endDate) {
|
||||
return;
|
||||
} else if (this.state.startDate.isAfter(this.state.endDate)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.props.onChange(
|
||||
DateRangePicker.formatValue(
|
||||
{
|
||||
startDate: this.state.startDate,
|
||||
endDate: this.state.endDate
|
||||
},
|
||||
this.props.format,
|
||||
this.props.joinValues,
|
||||
this.props.delimiter,
|
||||
this.props.utc
|
||||
)
|
||||
);
|
||||
this.close();
|
||||
}
|
||||
|
||||
filterDate(
|
||||
date: moment.Moment,
|
||||
originValue?: moment.Moment,
|
||||
timeFormat?: string,
|
||||
type: 'start' | 'end' = 'start'
|
||||
): moment.Moment {
|
||||
let value = date.clone();
|
||||
|
||||
value = value[type === 'start' ? 'startOf' : 'endOf']('month');
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
handleStartChange(newValue: moment.Moment) {
|
||||
const {embed, minDuration, maxDuration} = this.props;
|
||||
const {startDate, endDate} = this.state;
|
||||
|
||||
if (
|
||||
startDate &&
|
||||
!endDate &&
|
||||
newValue.isSameOrAfter(startDate) &&
|
||||
(!minDuration || newValue.isAfter(startDate.clone().add(minDuration))) &&
|
||||
(!maxDuration || newValue.isBefore(startDate.clone().add(maxDuration)))
|
||||
) {
|
||||
return this.setState(
|
||||
{
|
||||
endDate: this.filterDate(newValue, endDate, '', 'end')
|
||||
},
|
||||
() => {
|
||||
embed && this.confirm();
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
this.setState(
|
||||
{
|
||||
startDate: this.filterDate(newValue, startDate, '', 'start')
|
||||
},
|
||||
() => {
|
||||
embed && this.confirm();
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
handleEndChange(newValue: moment.Moment) {
|
||||
const {embed, minDuration, maxDuration} = this.props;
|
||||
const {startDate, endDate} = this.state;
|
||||
|
||||
if (
|
||||
endDate &&
|
||||
!startDate &&
|
||||
newValue.isSameOrBefore(endDate) &&
|
||||
(!minDuration ||
|
||||
newValue.isBefore(endDate.clone().subtract(minDuration))) &&
|
||||
(!maxDuration || newValue.isAfter(endDate.clone().subtract(maxDuration)))
|
||||
) {
|
||||
return this.setState(
|
||||
{
|
||||
startDate: this.filterDate(newValue, startDate, '', 'start')
|
||||
},
|
||||
() => {
|
||||
embed && this.confirm();
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
this.setState(
|
||||
{
|
||||
endDate: this.filterDate(newValue, endDate, '', 'end')
|
||||
},
|
||||
() => {
|
||||
embed && this.confirm();
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
handleMobileChange(data: any, callback?: () => void) {
|
||||
this.setState(
|
||||
{
|
||||
startDate: data.startDate,
|
||||
endDate: data.endDate
|
||||
},
|
||||
callback
|
||||
);
|
||||
}
|
||||
|
||||
selectShortcut(shortcut: PlainObject) {
|
||||
const {closeOnSelect, minDate, maxDate} = this.props;
|
||||
this.setState(
|
||||
{
|
||||
startDate: minDate
|
||||
? moment.max(shortcut.startDate(moment()), minDate)
|
||||
: shortcut.startDate(moment()),
|
||||
endDate: maxDate
|
||||
? moment.min(maxDate, shortcut.endDate(moment()))
|
||||
: shortcut.endDate(moment())
|
||||
},
|
||||
closeOnSelect ? this.confirm : noop
|
||||
);
|
||||
}
|
||||
|
||||
renderShortcuts(shortcuts: string | Array<ShortCuts> | undefined) {
|
||||
if (!shortcuts) {
|
||||
return null;
|
||||
}
|
||||
const {classPrefix: ns} = this.props;
|
||||
let shortcutArr: Array<string | ShortCuts>;
|
||||
if (typeof shortcuts === 'string') {
|
||||
shortcutArr = shortcuts.split(',');
|
||||
} else {
|
||||
shortcutArr = shortcuts;
|
||||
}
|
||||
const __ = this.props.translate;
|
||||
|
||||
return (
|
||||
<ul className={`${ns}DateRangePicker-rangers`}>
|
||||
{shortcutArr.map((item, index) => {
|
||||
if (!item) {
|
||||
return null;
|
||||
}
|
||||
let shortcut: PlainObject = {};
|
||||
if (typeof item === 'string') {
|
||||
shortcut = availableShortcuts[item];
|
||||
shortcut.key = item;
|
||||
} else if (
|
||||
(item as ShortCutDateRange).startDate &&
|
||||
(item as ShortCutDateRange).endDate
|
||||
) {
|
||||
shortcut = {
|
||||
...item,
|
||||
startDate: () => (item as ShortCutDateRange).startDate,
|
||||
endDate: () => (item as ShortCutDateRange).endDate
|
||||
};
|
||||
}
|
||||
return (
|
||||
<li
|
||||
className={`${ns}DateRangePicker-ranger`}
|
||||
onClick={() => this.selectShortcut(shortcut)}
|
||||
key={index}
|
||||
>
|
||||
<a>{__(shortcut.label)}</a>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
clearValue(e: React.MouseEvent<any>) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const {onChange} = this.props;
|
||||
|
||||
onChange('');
|
||||
}
|
||||
|
||||
checkStartIsValidDate(currentDate: moment.Moment) {
|
||||
let {endDate, startDate} = this.state;
|
||||
|
||||
let {minDate, maxDate, minDuration, maxDuration} = this.props;
|
||||
|
||||
maxDate =
|
||||
maxDate && endDate
|
||||
? maxDate.isBefore(endDate)
|
||||
? maxDate
|
||||
: endDate
|
||||
: maxDate || endDate;
|
||||
|
||||
if (minDate && currentDate.isBefore(minDate, 'day')) {
|
||||
return false;
|
||||
} else if (maxDate && currentDate.isAfter(maxDate, 'day')) {
|
||||
return false;
|
||||
} else if (
|
||||
// 如果配置了 minDuration 那么 EndDate - minDuration 之后的天数也不能选
|
||||
endDate &&
|
||||
minDuration &&
|
||||
currentDate.isAfter(endDate.clone().subtract(minDuration))
|
||||
) {
|
||||
return false;
|
||||
} else if (
|
||||
endDate &&
|
||||
maxDuration &&
|
||||
currentDate.isBefore(endDate.clone().subtract(maxDuration))
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
checkEndIsValidDate(currentDate: moment.Moment) {
|
||||
let {startDate} = this.state;
|
||||
|
||||
let {minDate, maxDate, minDuration, maxDuration} = this.props;
|
||||
|
||||
minDate =
|
||||
minDate && startDate
|
||||
? minDate.isAfter(startDate)
|
||||
? minDate
|
||||
: startDate
|
||||
: minDate || startDate;
|
||||
|
||||
if (minDate && currentDate.isBefore(minDate, 'day')) {
|
||||
return false;
|
||||
} else if (maxDate && currentDate.isAfter(maxDate, 'day')) {
|
||||
return false;
|
||||
} else if (
|
||||
startDate &&
|
||||
minDuration &&
|
||||
currentDate.isBefore(startDate.clone().add(minDuration))
|
||||
) {
|
||||
return false;
|
||||
} else if (
|
||||
startDate &&
|
||||
maxDuration &&
|
||||
currentDate.isAfter(startDate.clone().add(maxDuration))
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
renderMonth(props: any, month: number, year: number) {
|
||||
var currentDate = moment().year(year).month(month);
|
||||
var monthStr = currentDate
|
||||
.localeData()
|
||||
.monthsShort(currentDate.month(month));
|
||||
var strLength = 3;
|
||||
var monthStrFixedLength = monthStr.substring(0, strLength);
|
||||
const {startDate, endDate} = this.state;
|
||||
|
||||
if (
|
||||
startDate &&
|
||||
endDate &&
|
||||
currentDate.isBetween(startDate, endDate, 'month', '[]')
|
||||
) {
|
||||
props.className += ' rdtBetween';
|
||||
}
|
||||
|
||||
return (
|
||||
<td {...props}>
|
||||
<span>{capitalize(monthStrFixedLength)}</span>
|
||||
</td>
|
||||
);
|
||||
}
|
||||
|
||||
renderCalendar() {
|
||||
const {
|
||||
classPrefix: ns,
|
||||
classnames: cx,
|
||||
locale,
|
||||
embed,
|
||||
ranges,
|
||||
shortcuts,
|
||||
inputFormat,
|
||||
timeFormat
|
||||
} = this.props;
|
||||
const __ = this.props.translate;
|
||||
const viewMode: 'months' = 'months';
|
||||
const dateFormat = 'YYYY-MM';
|
||||
const {startDate, endDate} = this.state;
|
||||
|
||||
return (
|
||||
<div className={`${ns}DateRangePicker-wrap`}>
|
||||
{this.renderShortcuts(ranges || shortcuts)}
|
||||
<Calendar
|
||||
className={`${ns}DateRangePicker-start`}
|
||||
value={startDate}
|
||||
onChange={this.handleStartChange}
|
||||
requiredConfirm={false}
|
||||
dateFormat={dateFormat}
|
||||
inputFormat={inputFormat}
|
||||
timeFormat={timeFormat}
|
||||
isValidDate={this.checkStartIsValidDate}
|
||||
viewMode={viewMode}
|
||||
input={false}
|
||||
onClose={this.close}
|
||||
renderMonth={this.renderMonth}
|
||||
locale={locale}
|
||||
/>
|
||||
|
||||
<Calendar
|
||||
className={`${ns}DateRangePicker-end`}
|
||||
value={
|
||||
// 因为如果最后一天,切换月份的时候会切不了,有的月份有 31 号,有的没有。
|
||||
endDate?.clone().startOf('month')
|
||||
}
|
||||
onChange={this.handleEndChange}
|
||||
requiredConfirm={false}
|
||||
dateFormat={dateFormat}
|
||||
inputFormat={inputFormat}
|
||||
timeFormat={timeFormat}
|
||||
viewDate={this.nextMonth}
|
||||
isEndDate
|
||||
isValidDate={this.checkEndIsValidDate}
|
||||
viewMode={viewMode}
|
||||
input={false}
|
||||
onClose={this.close}
|
||||
renderMonth={this.renderMonth}
|
||||
locale={locale}
|
||||
/>
|
||||
|
||||
{embed ? null : (
|
||||
<div key="button" className={cx('DateRangePicker-actions')}>
|
||||
<a
|
||||
className={cx(
|
||||
'Button',
|
||||
'Button--default',
|
||||
'Button--size-default'
|
||||
)}
|
||||
onClick={this.close}
|
||||
>
|
||||
{__('cancel')}
|
||||
</a>
|
||||
<a
|
||||
className={cx(
|
||||
'Button',
|
||||
'Button--primary',
|
||||
'Button--size-default',
|
||||
'm-l-sm',
|
||||
{
|
||||
'is-disabled': !this.state.startDate || !this.state.endDate
|
||||
}
|
||||
)}
|
||||
onClick={this.confirm}
|
||||
>
|
||||
{__('confirm')}
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
className,
|
||||
popoverClassName,
|
||||
classPrefix: ns,
|
||||
value,
|
||||
placeholder,
|
||||
popOverContainer,
|
||||
inputFormat,
|
||||
format,
|
||||
joinValues,
|
||||
delimiter,
|
||||
clearable,
|
||||
disabled,
|
||||
embed,
|
||||
overlayPlacement,
|
||||
mobileUI,
|
||||
timeFormat,
|
||||
minDate,
|
||||
maxDate,
|
||||
minDuration,
|
||||
maxDuration,
|
||||
ranges,
|
||||
shortcuts,
|
||||
label,
|
||||
translate: __,
|
||||
data
|
||||
} = this.props;
|
||||
const {isOpened, isFocused, startDate, endDate} = this.state;
|
||||
const selectedDate = DateRangePicker.unFormatValue(
|
||||
value,
|
||||
format,
|
||||
joinValues,
|
||||
delimiter,
|
||||
data
|
||||
);
|
||||
const startViewValue = selectedDate.startDate
|
||||
? selectedDate.startDate.format(inputFormat)
|
||||
: '';
|
||||
const endViewValue = selectedDate.endDate
|
||||
? selectedDate.endDate.format(inputFormat)
|
||||
: '';
|
||||
const arr = [];
|
||||
|
||||
startViewValue && arr.push(startViewValue);
|
||||
endViewValue && arr.push(endViewValue);
|
||||
|
||||
const calendarMobile = (
|
||||
<CalendarMobile
|
||||
timeFormat={timeFormat}
|
||||
inputFormat={inputFormat}
|
||||
startDate={startDate}
|
||||
endDate={endDate}
|
||||
minDate={minDate}
|
||||
maxDate={maxDate}
|
||||
minDuration={minDuration}
|
||||
maxDuration={maxDuration}
|
||||
embed={embed}
|
||||
viewMode="months"
|
||||
close={this.close}
|
||||
confirm={this.confirm}
|
||||
onChange={this.handleMobileChange}
|
||||
footerExtra={this.renderShortcuts(ranges || shortcuts)}
|
||||
showViewMode="years"
|
||||
/>
|
||||
);
|
||||
|
||||
if (embed) {
|
||||
return (
|
||||
<div
|
||||
className={cx(
|
||||
`${ns}DateRangeCalendar`,
|
||||
{
|
||||
'is-disabled': disabled
|
||||
},
|
||||
className
|
||||
)}
|
||||
>
|
||||
{mobileUI ? calendarMobile : this.renderCalendar()}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const CalendarMobileTitle = (
|
||||
<div className={`${ns}CalendarMobile-title`}>
|
||||
{label && typeof label === 'string' ? label : __('Calendar.datepicker')}
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
tabIndex={0}
|
||||
onKeyPress={this.handleKeyPress}
|
||||
onFocus={this.handleFocus}
|
||||
onBlur={this.handleBlur}
|
||||
className={cx(
|
||||
`${ns}DateRangePicker`,
|
||||
{
|
||||
'is-disabled': disabled,
|
||||
'is-focused': isFocused,
|
||||
'is-mobile': mobileUI
|
||||
},
|
||||
className
|
||||
)}
|
||||
ref={this.dom}
|
||||
onClick={this.handleClick}
|
||||
>
|
||||
{arr.length ? (
|
||||
<span className={`${ns}DateRangePicker-value`}>
|
||||
{arr.join(__('DateRange.valueConcat'))}
|
||||
</span>
|
||||
) : (
|
||||
<span className={`${ns}DateRangePicker-placeholder`}>
|
||||
{__(placeholder)}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{clearable && !disabled && value ? (
|
||||
<a className={`${ns}DateRangePicker-clear`} onClick={this.clearValue}>
|
||||
<Icon icon="close" className="icon" />
|
||||
</a>
|
||||
) : null}
|
||||
|
||||
<a className={`${ns}DateRangePicker-toggler`}>
|
||||
<Icon icon="clock" className="icon" />
|
||||
</a>
|
||||
|
||||
{isOpened ? (
|
||||
mobileUI ? (
|
||||
<PopUp
|
||||
isShow={isOpened}
|
||||
container={popOverContainer}
|
||||
className={cx(`${ns}CalendarMobile-pop`)}
|
||||
onHide={this.close}
|
||||
header={CalendarMobileTitle}
|
||||
>
|
||||
{calendarMobile}
|
||||
</PopUp>
|
||||
) : (
|
||||
<Overlay
|
||||
target={() => this.dom.current}
|
||||
onHide={this.close}
|
||||
container={popOverContainer || (() => findDOMNode(this))}
|
||||
rootClose={false}
|
||||
placement={overlayPlacement}
|
||||
show
|
||||
>
|
||||
<PopOver
|
||||
classPrefix={ns}
|
||||
className={cx(`${ns}DateRangePicker-popover`, popoverClassName)}
|
||||
onHide={this.close}
|
||||
onClick={this.handlePopOverClick}
|
||||
overlay
|
||||
>
|
||||
{this.renderCalendar()}
|
||||
</PopOver>
|
||||
</Overlay>
|
||||
)
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(localeable(MonthRangePicker));
|
||||
161
packages/amis-ui/src/components/MultilineText.tsx
Normal file
161
packages/amis-ui/src/components/MultilineText.tsx
Normal file
@@ -0,0 +1,161 @@
|
||||
import React from 'react';
|
||||
import {anyChanged, autobind, localeable, LocaleProps} from 'amis-core';
|
||||
import {themeable, ThemeProps} from 'amis-core';
|
||||
import Button from './Button';
|
||||
|
||||
export interface MultilineTextProps extends ThemeProps, LocaleProps {
|
||||
/**
|
||||
* 最大行数
|
||||
*/
|
||||
maxRows?: number;
|
||||
|
||||
/**
|
||||
* 展示文本
|
||||
*/
|
||||
text: string;
|
||||
|
||||
/**
|
||||
* 展开按钮文本
|
||||
*/
|
||||
expendButtonText?: string;
|
||||
|
||||
/**
|
||||
* 收起按钮文本
|
||||
*/
|
||||
collapseButtonText?: string;
|
||||
}
|
||||
|
||||
export interface MultilineTextState {
|
||||
isExpend: boolean;
|
||||
showBtn: boolean;
|
||||
}
|
||||
|
||||
export class MultilineText extends React.Component<
|
||||
MultilineTextProps,
|
||||
MultilineTextState
|
||||
> {
|
||||
static defaultProps = {
|
||||
maxRows: 5,
|
||||
expendButtonText: '展开',
|
||||
collapseButtonText: '收起'
|
||||
};
|
||||
|
||||
state = {
|
||||
isExpend: false,
|
||||
showBtn: false
|
||||
};
|
||||
|
||||
ref?: React.RefObject<HTMLDivElement>;
|
||||
|
||||
constructor(props: MultilineTextProps) {
|
||||
super(props);
|
||||
this.ref = React.createRef();
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
if (this.ref && this.ref.current) {
|
||||
if (this.ref.current.scrollHeight > this.ref.current.clientHeight) {
|
||||
this.setState({
|
||||
showBtn: true
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
shouldComponentUpdate(
|
||||
nextProps: Readonly<MultilineTextProps>,
|
||||
nextState: Readonly<MultilineTextState>,
|
||||
nextContext: any
|
||||
): boolean {
|
||||
if (
|
||||
anyChanged(
|
||||
[
|
||||
'text',
|
||||
'maxRows',
|
||||
'expendButtonText',
|
||||
'collapseButtonText',
|
||||
'className'
|
||||
],
|
||||
this.props,
|
||||
nextProps
|
||||
) ||
|
||||
anyChanged(['isExpend', 'showBtn'], this.state, nextState)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
componentDidUpdate(oldProps: any, oldState: any) {
|
||||
const {text, maxRows} = this.props;
|
||||
if (text !== oldProps.text || maxRows !== oldProps.maxRows) {
|
||||
if (this.ref && this.ref.current) {
|
||||
this.setState({
|
||||
showBtn: this.ref.current.scrollHeight > this.ref.current.clientHeight
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@autobind
|
||||
toggleExpend() {
|
||||
this.setState({
|
||||
isExpend: !this.state.isExpend
|
||||
});
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
className,
|
||||
style,
|
||||
text,
|
||||
classnames: cx,
|
||||
maxRows = 5,
|
||||
expendButtonText,
|
||||
collapseButtonText
|
||||
} = this.props;
|
||||
|
||||
if (!text) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const {showBtn, isExpend} = this.state;
|
||||
|
||||
return (
|
||||
<div className={cx('MultilineText', className)} style={style}>
|
||||
{/* 用于计算高度 */}
|
||||
<div
|
||||
ref={this.ref}
|
||||
className={cx('MultilineText-counter')}
|
||||
style={{
|
||||
height: `${maxRows * 20}px`
|
||||
}}
|
||||
>
|
||||
{text}
|
||||
</div>
|
||||
{/* 用于展示 */}
|
||||
<div
|
||||
className={cx('MultilineText-display')}
|
||||
style={{
|
||||
height: showBtn && !isExpend ? `${maxRows * 20}px` : 'auto'
|
||||
}}
|
||||
>
|
||||
{text}
|
||||
</div>
|
||||
{showBtn && (
|
||||
<div className={cx('MultilineText-button-wrapper')}>
|
||||
<Button
|
||||
className={cx('MultilineText-button')}
|
||||
level="link"
|
||||
onClick={this.toggleExpend}
|
||||
>
|
||||
{!isExpend ? expendButtonText : collapseButtonText}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(localeable(MultilineText));
|
||||
495
packages/amis-ui/src/components/NumberInput.tsx
Normal file
495
packages/amis-ui/src/components/NumberInput.tsx
Normal file
@@ -0,0 +1,495 @@
|
||||
import React from 'react';
|
||||
import isInteger from 'lodash/isInteger';
|
||||
// @ts-ignore
|
||||
import InputNumber from 'rc-input-number';
|
||||
import getMiniDecimal, {
|
||||
DecimalClass,
|
||||
toFixed,
|
||||
getNumberPrecision,
|
||||
num2str
|
||||
} from '@rc-component/mini-decimal';
|
||||
|
||||
import {Icon} from './icons';
|
||||
import {
|
||||
ThemeProps,
|
||||
themeable,
|
||||
isNumeric,
|
||||
autobind,
|
||||
ucFirst,
|
||||
TestIdBuilder
|
||||
} from 'amis-core';
|
||||
|
||||
export type ValueType = string | number;
|
||||
|
||||
export interface NumberProps extends ThemeProps {
|
||||
name?: string;
|
||||
placeholder?: string;
|
||||
max?: ValueType;
|
||||
min?: ValueType;
|
||||
step?: number;
|
||||
showSteps?: boolean;
|
||||
precision?: number;
|
||||
disabled?: boolean;
|
||||
/**
|
||||
* 只读
|
||||
*/
|
||||
readOnly?: boolean;
|
||||
value?: ValueType;
|
||||
onChange?: (value: number) => void;
|
||||
/**
|
||||
* 边框模式,全边框,还是半边框,或者没边框。
|
||||
*/
|
||||
borderMode?: 'full' | 'half' | 'none';
|
||||
/**
|
||||
* 指定输入框展示值的格式
|
||||
*/
|
||||
formatter?: Function;
|
||||
/**
|
||||
* 指定从 formatter 里转换回数字的方式,和 formatter 搭配使用
|
||||
*/
|
||||
parser?: Function;
|
||||
inputRef?: Function;
|
||||
/**
|
||||
* 获取焦点事件
|
||||
*/
|
||||
onFocus?: Function;
|
||||
/**
|
||||
* 失去焦点事件
|
||||
*/
|
||||
onBlur?: Function;
|
||||
/**
|
||||
* 指定输入框是基础输入框,增强输入框
|
||||
*/
|
||||
displayMode?: 'base' | 'enhance';
|
||||
keyboard?: Boolean;
|
||||
|
||||
/**
|
||||
* 是否是大数
|
||||
*/
|
||||
big?: boolean;
|
||||
|
||||
/**
|
||||
* 清空输入内容时的值
|
||||
*/
|
||||
resetValue?: any;
|
||||
|
||||
/**
|
||||
* 后缀
|
||||
*/
|
||||
suffix?: string;
|
||||
|
||||
/**
|
||||
* 用来开启百分号的展示形式,搭配suffix使用
|
||||
*/
|
||||
showAsPercent?: boolean;
|
||||
|
||||
/**
|
||||
* 是否在清空内容时从数据域中删除该表单项对应的值
|
||||
*/
|
||||
clearValueOnEmpty?: boolean;
|
||||
|
||||
/**
|
||||
* 数字输入框类名
|
||||
*/
|
||||
inputControlClassName?: string;
|
||||
|
||||
testIdBuilder?: TestIdBuilder;
|
||||
}
|
||||
|
||||
export interface NumberState {
|
||||
focused: boolean;
|
||||
}
|
||||
|
||||
export class NumberInput extends React.Component<NumberProps, NumberState> {
|
||||
static defaultProps: Pick<
|
||||
NumberProps,
|
||||
'step' | 'readOnly' | 'borderMode' | 'resetValue'
|
||||
> = {
|
||||
step: 1,
|
||||
readOnly: false,
|
||||
borderMode: 'full',
|
||||
resetValue: ''
|
||||
};
|
||||
|
||||
/**
|
||||
* 处理value值
|
||||
*
|
||||
* @param value value 值
|
||||
* @param min 最小值
|
||||
* @param max 最大值
|
||||
* @param precision 精度
|
||||
* @param resetValue 重置值
|
||||
* @param isBig 是否为大数模式
|
||||
*/
|
||||
static normalizeValue = (
|
||||
value: any,
|
||||
min: ValueType | undefined,
|
||||
max: ValueType | undefined,
|
||||
precision: number,
|
||||
resetValue: any,
|
||||
clearValueOnEmpty?: boolean,
|
||||
isBig?: boolean
|
||||
) => {
|
||||
/**
|
||||
* 输入不合法时重置为resetValue
|
||||
* 若resetValue为不合法数字,直接清空输入
|
||||
* 若resetValue为数字,则需要处理max,min,precision,保证抛出的值满足条件
|
||||
*/
|
||||
if (!isNumeric(value)) {
|
||||
if (!isNumeric(resetValue)) {
|
||||
return clearValueOnEmpty ? undefined : '';
|
||||
}
|
||||
|
||||
value = resetValue;
|
||||
}
|
||||
// 处理max & min
|
||||
if (typeof value === 'number') {
|
||||
if (typeof min === 'number') {
|
||||
value = Math.max(value, min);
|
||||
}
|
||||
|
||||
if (typeof max === 'number') {
|
||||
value = Math.min(value, max);
|
||||
}
|
||||
}
|
||||
// 处理string类型输入
|
||||
if (typeof value === 'string') {
|
||||
let val = getMiniDecimal(value);
|
||||
if (typeof min !== 'undefined') {
|
||||
let minValue = getMiniDecimal(min);
|
||||
if (val.lessEquals(minValue)) {
|
||||
value = min;
|
||||
}
|
||||
}
|
||||
if (typeof max !== 'undefined') {
|
||||
let maxValue = getMiniDecimal(max);
|
||||
if (maxValue.lessEquals(val)) {
|
||||
value = max;
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 非大数模式下,如果精度不满足要求,需要处理value值,只做精度处理,不做四舍五入
|
||||
*/
|
||||
if (!isBig && getNumberPrecision(value) !== precision) {
|
||||
const multiplier = Math.pow(10, precision);
|
||||
const truncatedValue =
|
||||
Math.trunc(getMiniDecimal(value).multi(multiplier).toNumber()) /
|
||||
multiplier;
|
||||
value = getMiniDecimal(truncatedValue).toNumber();
|
||||
}
|
||||
|
||||
return value;
|
||||
};
|
||||
|
||||
/**
|
||||
* 处理value值(仅使用 resetValue 和 clearValueOnEmpty)
|
||||
*
|
||||
* @param value value 值
|
||||
* @param resetValue 重置值
|
||||
* @param clearValueOnEmpty 是否在清空内容时从数据域中删除该表单项对应的值
|
||||
*/
|
||||
static normalizeValue2 = (
|
||||
value: any,
|
||||
resetValue: any,
|
||||
clearValueOnEmpty?: boolean
|
||||
) => {
|
||||
if (!isNumeric(value)) {
|
||||
if (!isNumeric(resetValue)) {
|
||||
return clearValueOnEmpty ? undefined : '';
|
||||
}
|
||||
|
||||
value = resetValue;
|
||||
}
|
||||
|
||||
return value;
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取精度,合法的精度为0和正整数,不合法的精度统一转化为0
|
||||
* 若设置了step,则会基于step的精度生成,最终使用更高的精度
|
||||
*
|
||||
* @param precision 精度
|
||||
* @param step 步长
|
||||
*/
|
||||
static normalizePrecision = (precision: any, step?: number): number => {
|
||||
if (
|
||||
typeof precision === 'number' &&
|
||||
isInteger(precision) &&
|
||||
precision >= 0
|
||||
) {
|
||||
return Math.max(precision, getNumberPrecision(step ?? 1));
|
||||
}
|
||||
|
||||
// 如果设置了step,就基于step和precision,选取更高精度
|
||||
if (step != null) {
|
||||
return Math.max(0, getNumberPrecision(step));
|
||||
}
|
||||
|
||||
return 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* 是否是 bigNumber,如果输入的内容是字符串就自动开启
|
||||
*/
|
||||
isBig: boolean = false;
|
||||
|
||||
constructor(props: NumberProps) {
|
||||
super(props);
|
||||
|
||||
// 严格判断大数模式,因为初始化value为empty string时,修改value值格式仍然为string
|
||||
this.isBig = !!props.big;
|
||||
this.state = {
|
||||
focused: false
|
||||
};
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps: NumberProps) {
|
||||
const isBig = !!this.props.big;
|
||||
|
||||
if (!!prevProps?.big !== isBig) {
|
||||
this.isBig = isBig;
|
||||
}
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleChange(value: any) {
|
||||
const {min, max, step, resetValue, clearValueOnEmpty, onChange} =
|
||||
this.props;
|
||||
let {suffix, precision, showAsPercent} = this.props;
|
||||
//在显示百分号情况下,需先将数值恢复到实际value值
|
||||
if (showAsPercent && suffix == '%') {
|
||||
value = value / 100;
|
||||
precision = (precision || 0) + 2;
|
||||
}
|
||||
const finalPrecision = NumberInput.normalizePrecision(precision, step);
|
||||
const result = NumberInput.normalizeValue(
|
||||
value,
|
||||
min,
|
||||
max,
|
||||
finalPrecision,
|
||||
resetValue,
|
||||
clearValueOnEmpty,
|
||||
this.isBig
|
||||
);
|
||||
onChange?.(result);
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleFocus(e: React.SyntheticEvent<HTMLElement>) {
|
||||
const {onFocus} = this.props;
|
||||
this.setState({focused: true});
|
||||
onFocus && onFocus(e);
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleBlur(e: React.SyntheticEvent<HTMLElement>) {
|
||||
const {onBlur} = this.props;
|
||||
this.setState({focused: false});
|
||||
onBlur && onBlur(e);
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleClick(e: React.SyntheticEvent<HTMLElement>) {
|
||||
e.stopPropagation();
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleEnhanceModeChange(
|
||||
action: 'add' | 'subtract',
|
||||
e: React.MouseEvent
|
||||
): void {
|
||||
e.stopPropagation();
|
||||
const {value, step = 1, disabled, readOnly, precision} = this.props;
|
||||
// value为undefined会导致溢出错误
|
||||
let val = value || 0;
|
||||
if (disabled || readOnly) {
|
||||
return;
|
||||
}
|
||||
if (isNaN(Number(step)) || !Number(step)) {
|
||||
return;
|
||||
}
|
||||
let stepDecimal = getMiniDecimal(step);
|
||||
if (action !== 'add') {
|
||||
stepDecimal = stepDecimal.negate();
|
||||
}
|
||||
const target = getMiniDecimal(val).add(stepDecimal.toString());
|
||||
const getPrecision = (numStr: string) => {
|
||||
if (precision != null && precision >= 0) {
|
||||
return precision;
|
||||
}
|
||||
return Math.max(
|
||||
getNumberPrecision(numStr),
|
||||
getNumberPrecision(Number(step) || 1)
|
||||
);
|
||||
};
|
||||
const triggerValueUpdate = (
|
||||
newValue: DecimalClass,
|
||||
userTyping: boolean
|
||||
): DecimalClass => {
|
||||
let updateValue = newValue;
|
||||
const numStr = updateValue.toString();
|
||||
const mergedPrecision = getPrecision(numStr);
|
||||
if (mergedPrecision >= 0) {
|
||||
updateValue = getMiniDecimal(toFixed(numStr, '.', mergedPrecision));
|
||||
}
|
||||
|
||||
return updateValue;
|
||||
};
|
||||
const updatedValue = triggerValueUpdate(target, false);
|
||||
if (this.isBig) {
|
||||
this.handleChange(updatedValue.toString());
|
||||
} else {
|
||||
val = Number(updatedValue.toString());
|
||||
this.handleChange(val);
|
||||
}
|
||||
}
|
||||
|
||||
@autobind
|
||||
renderBase() {
|
||||
const {
|
||||
className,
|
||||
classPrefix: ns,
|
||||
classnames: cx,
|
||||
step,
|
||||
precision,
|
||||
disabled,
|
||||
placeholder,
|
||||
showSteps,
|
||||
formatter,
|
||||
suffix,
|
||||
showAsPercent,
|
||||
parser,
|
||||
borderMode,
|
||||
readOnly,
|
||||
displayMode,
|
||||
inputRef,
|
||||
keyboard,
|
||||
inputControlClassName,
|
||||
mobileUI,
|
||||
name,
|
||||
testIdBuilder
|
||||
} = this.props;
|
||||
|
||||
let {value, max, min} = this.props;
|
||||
//需要展示百分号的情况下,数值乘100显示,注意精度丢失问题
|
||||
if (showAsPercent && suffix == '%' && value) {
|
||||
value = parseFloat((Number(value) * 100).toFixed(precision));
|
||||
max = max != null ? Math.round(Number(max) * 100) : max;
|
||||
min = min != null ? Math.round(Number(min) * 100) : min;
|
||||
}
|
||||
const precisionProps: any = {
|
||||
precision: NumberInput.normalizePrecision(precision, step)
|
||||
};
|
||||
|
||||
return (
|
||||
<InputNumber
|
||||
name={name}
|
||||
className={cx(
|
||||
className,
|
||||
showSteps === false || readOnly ? 'no-steps' : '',
|
||||
displayMode === 'enhance'
|
||||
? 'Number--enhance-input'
|
||||
: inputControlClassName,
|
||||
{
|
||||
[`Number--border${ucFirst(borderMode)}`]: borderMode
|
||||
},
|
||||
{
|
||||
'is-mobile': mobileUI
|
||||
}
|
||||
)}
|
||||
ref={inputRef}
|
||||
readOnly={readOnly}
|
||||
prefixCls={`${ns}Number`}
|
||||
value={value}
|
||||
step={step}
|
||||
max={max}
|
||||
min={min}
|
||||
formatter={formatter}
|
||||
parser={parser}
|
||||
onChange={this.handleChange}
|
||||
disabled={disabled}
|
||||
placeholder={placeholder}
|
||||
onFocus={this.handleFocus}
|
||||
onClick={this.handleClick}
|
||||
onBlur={this.handleBlur}
|
||||
stringMode={this.isBig ? true : false}
|
||||
keyboard={keyboard}
|
||||
{...precisionProps}
|
||||
{...testIdBuilder?.getTestId()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
render(): JSX.Element {
|
||||
const {
|
||||
classnames: cx,
|
||||
value,
|
||||
max,
|
||||
min,
|
||||
disabled,
|
||||
showSteps,
|
||||
borderMode,
|
||||
readOnly,
|
||||
displayMode,
|
||||
inputControlClassName,
|
||||
mobileUI
|
||||
} = this.props;
|
||||
|
||||
return (
|
||||
<>
|
||||
{displayMode === 'enhance' ? (
|
||||
<div
|
||||
className={cx(
|
||||
'Number--enhance',
|
||||
disabled ? 'Number--enhance-disabled' : '',
|
||||
showSteps === false ? 'Number--enhance-no-steps' : '',
|
||||
{
|
||||
[`Number--enhance-border${ucFirst(borderMode)}`]: borderMode
|
||||
},
|
||||
inputControlClassName,
|
||||
this.state?.focused && 'focused'
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={cx(
|
||||
'Number--enhance-left-icon',
|
||||
value && value === min ? 'Number--enhance-border-min' : '',
|
||||
disabled ? 'Number--enhance-border-disabled' : '',
|
||||
readOnly ? 'Number--enhance-border-readOnly' : ''
|
||||
)}
|
||||
onClick={e => this.handleEnhanceModeChange('subtract', e)}
|
||||
>
|
||||
<Icon
|
||||
icon="minus"
|
||||
className="icon"
|
||||
classNameProp={cx('InputNumber-enhance-minus icon')}
|
||||
iconContent="InputNumber-enhance-minus"
|
||||
/>
|
||||
</div>
|
||||
{this.renderBase()}
|
||||
<div
|
||||
className={cx(
|
||||
'Number--enhance-right-icon',
|
||||
value && value === max ? 'Number--enhance-border-max' : '',
|
||||
disabled ? 'Number--enhance-border-disabled' : '',
|
||||
readOnly ? 'Number--enhance-border-readOnly' : ''
|
||||
)}
|
||||
onClick={e => this.handleEnhanceModeChange('add', e)}
|
||||
>
|
||||
<Icon
|
||||
icon="plus"
|
||||
className="icon"
|
||||
classNameProp={cx('InputNumber-enhance-plus icon')}
|
||||
iconContent="InputNumber-enhance-plus"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
this.renderBase()
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(NumberInput);
|
||||
181
packages/amis-ui/src/components/OverflowTpl.tsx
Normal file
181
packages/amis-ui/src/components/OverflowTpl.tsx
Normal file
@@ -0,0 +1,181 @@
|
||||
/**
|
||||
* @file OverflowTpl
|
||||
* @desc 文字提示组件,会基于内部文字是否触发ellipsis,动态展示tooltip提示, 默认使用子节点文本作为tooltip内容
|
||||
*/
|
||||
|
||||
import React, {useState, useEffect, useRef, useCallback} from 'react';
|
||||
import {findDOMNode} from 'react-dom';
|
||||
import omit from 'lodash/omit';
|
||||
import {themeable, isObject} from 'amis-core';
|
||||
import TooltipWrapper from './TooltipWrapper';
|
||||
|
||||
import type {ThemeProps} from 'amis-core';
|
||||
import type {TooltipWrapperProps} from './TooltipWrapper';
|
||||
|
||||
export interface OverflowTplProps extends ThemeProps {
|
||||
className?: string;
|
||||
|
||||
/**
|
||||
* tooltip相关配置
|
||||
*/
|
||||
tooltip?: TooltipWrapperProps['tooltip'];
|
||||
|
||||
/**
|
||||
* 是否使用行内标签,默认为 true,使用 span 标签,否则使用 div 标签
|
||||
*/
|
||||
inline?: boolean;
|
||||
|
||||
/**
|
||||
* 目标元素的selector,通常不需要指定
|
||||
*/
|
||||
targetSelector?: string;
|
||||
|
||||
/**
|
||||
* 内部节点
|
||||
*/
|
||||
children?: React.ReactNode | React.ReactNode[];
|
||||
}
|
||||
|
||||
const OverflowTpl: React.FC<OverflowTplProps> = props => {
|
||||
const {
|
||||
classnames: cx,
|
||||
children,
|
||||
className,
|
||||
targetSelector,
|
||||
tooltip,
|
||||
inline = true
|
||||
} = props;
|
||||
const [ellipsisAvtived, setEllipsisAvtived] = useState(false);
|
||||
const [innerText, setInnerText] = useState('');
|
||||
const innerRef = useRef<Element | React.ReactInstance>(null);
|
||||
const defaultTooltip = tooltip
|
||||
? typeof tooltip === 'string'
|
||||
? {content: tooltip}
|
||||
: isObject(tooltip)
|
||||
? tooltip
|
||||
: undefined
|
||||
: typeof children === 'string'
|
||||
? {content: children}
|
||||
: undefined; /** 默认使用子节点文本 */
|
||||
const normalizedTooltip =
|
||||
innerText && (!defaultTooltip || defaultTooltip?.content == null)
|
||||
? {...defaultTooltip, content: innerText}
|
||||
: defaultTooltip;
|
||||
const updateEllipsisActivation = useCallback(
|
||||
(el?: Element) => {
|
||||
setEllipsisAvtived(
|
||||
el
|
||||
? el.scrollWidth > el.clientWidth || el.scrollHeight > el.scrollHeight
|
||||
: false
|
||||
);
|
||||
},
|
||||
[innerRef.current]
|
||||
);
|
||||
const onMutation = useCallback(
|
||||
(mutations: MutationRecord[]) => {
|
||||
const dom = (
|
||||
targetSelector
|
||||
? document.querySelector(targetSelector)
|
||||
: mutations?.[0].target
|
||||
) as Element | undefined;
|
||||
|
||||
updateEllipsisActivation(dom);
|
||||
if (
|
||||
dom?.textContent &&
|
||||
typeof dom.textContent === 'string' &&
|
||||
(!defaultTooltip || defaultTooltip?.content == null)
|
||||
) {
|
||||
setInnerText(dom.textContent);
|
||||
}
|
||||
},
|
||||
[targetSelector]
|
||||
);
|
||||
const onResize = useCallback(
|
||||
(entries: ResizeObserverEntry[]) => {
|
||||
const dom = (
|
||||
targetSelector
|
||||
? document.querySelector(targetSelector)
|
||||
: entries?.[0].target
|
||||
) as Element | undefined;
|
||||
|
||||
updateEllipsisActivation(dom);
|
||||
if (
|
||||
dom?.textContent &&
|
||||
typeof dom.textContent === 'string' &&
|
||||
(!defaultTooltip || !defaultTooltip?.content == null)
|
||||
) {
|
||||
setInnerText(dom.textContent);
|
||||
}
|
||||
},
|
||||
[targetSelector]
|
||||
);
|
||||
|
||||
/** 监听目标元素的DOM变化 */
|
||||
useEffect(() => {
|
||||
const element =
|
||||
innerRef.current instanceof React.Component
|
||||
? (findDOMNode(innerRef.current) as Element)
|
||||
: innerRef.current;
|
||||
|
||||
if (element) {
|
||||
const observer = new MutationObserver(onMutation);
|
||||
observer.observe(element, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
characterDataOldValue: true,
|
||||
characterData: true
|
||||
});
|
||||
return () => observer.disconnect();
|
||||
}
|
||||
|
||||
return;
|
||||
}, [innerRef.current]);
|
||||
|
||||
/** 监听目标元素的尺寸变化 */
|
||||
useEffect(() => {
|
||||
const element =
|
||||
innerRef.current instanceof React.Component
|
||||
? (findDOMNode(innerRef.current) as Element)
|
||||
: innerRef.current;
|
||||
|
||||
if (element) {
|
||||
const observer = new ResizeObserver(onResize);
|
||||
observer.observe(element);
|
||||
return () => observer.disconnect();
|
||||
}
|
||||
|
||||
return;
|
||||
}, [innerRef.current]);
|
||||
|
||||
const WrapComponent = inline !== false ? 'span' : 'div';
|
||||
const showTooltip = ellipsisAvtived && normalizedTooltip;
|
||||
const Body = React.isValidElement(children) ? (
|
||||
React.cloneElement(children as React.ReactElement, {ref: innerRef})
|
||||
) : (
|
||||
<WrapComponent
|
||||
ref={innerRef as React.RefObject<HTMLDivElement>}
|
||||
className={cx('OverflowTpl', className, {
|
||||
'OverflowTpl--with-tooltip': showTooltip
|
||||
})}
|
||||
>
|
||||
{children}
|
||||
</WrapComponent>
|
||||
);
|
||||
|
||||
return showTooltip ? (
|
||||
<TooltipWrapper
|
||||
{...omit(props, ['className', 'inline', 'targetSelector', 'children'])}
|
||||
tooltip={normalizedTooltip}
|
||||
>
|
||||
{Body}
|
||||
</TooltipWrapper>
|
||||
) : (
|
||||
Body
|
||||
);
|
||||
};
|
||||
|
||||
OverflowTpl.defaultProps = {
|
||||
inline: true
|
||||
};
|
||||
|
||||
export default themeable(OverflowTpl);
|
||||
755
packages/amis-ui/src/components/Pagination.tsx
Normal file
755
packages/amis-ui/src/components/Pagination.tsx
Normal file
@@ -0,0 +1,755 @@
|
||||
/*
|
||||
* @Description: Pagination分页组件
|
||||
* @Author: wangfeilong02@baidu.com
|
||||
* @Date: 2021-11-01 16:57:38
|
||||
*/
|
||||
import React from 'react';
|
||||
import isInteger from 'lodash/isInteger';
|
||||
import {
|
||||
localeable,
|
||||
LocaleProps,
|
||||
resolveEventData,
|
||||
TestIdBuilder
|
||||
} from 'amis-core';
|
||||
import {themeable, ThemeProps} from 'amis-core';
|
||||
import {autobind} from 'amis-core';
|
||||
import {Icon} from './icons';
|
||||
import Select from './Select';
|
||||
|
||||
export type MODE_TYPE = 'simple' | 'normal';
|
||||
|
||||
export const enum PaginationWidget {
|
||||
Pager = 'pager',
|
||||
PerPage = 'perpage',
|
||||
Total = 'total',
|
||||
Go = 'go'
|
||||
}
|
||||
|
||||
export const enum KeyCode {
|
||||
ENTER = 'Enter',
|
||||
UP = 'ArrowUp',
|
||||
DOWN = 'ArrowDown'
|
||||
}
|
||||
|
||||
export interface BasicPaginationProps {
|
||||
/**
|
||||
* 通过控制layout属性的顺序,调整分页结构 total,perPage,pager,go
|
||||
* @default ['pager']
|
||||
*/
|
||||
layout?: string | Array<string>;
|
||||
|
||||
/**
|
||||
* 最多显示多少个分页按钮。
|
||||
*
|
||||
* @default 5
|
||||
*/
|
||||
maxButtons: number;
|
||||
|
||||
/**
|
||||
* 模式,默认normal,如果只想简单显示可以配置成 `simple`。
|
||||
* @default 'normal'
|
||||
*/
|
||||
mode?: MODE_TYPE;
|
||||
|
||||
/**
|
||||
* 当前页数
|
||||
*/
|
||||
activePage: number;
|
||||
|
||||
/**
|
||||
* 总条数
|
||||
*/
|
||||
total?: number;
|
||||
|
||||
/**
|
||||
* 最后一页,总页数(如果传入了total,会重新计算lastPage)
|
||||
*/
|
||||
lastPage?: number;
|
||||
|
||||
/**
|
||||
* 每页显示条数
|
||||
* @default 10
|
||||
*/
|
||||
perPage?: number;
|
||||
|
||||
/**
|
||||
* 是否展示分页切换,也同时受layout控制
|
||||
* @default false
|
||||
*/
|
||||
showPerPage?: boolean;
|
||||
|
||||
/**
|
||||
* 指定每页可以显示多少条
|
||||
* @default [10, 20, 50, 100]
|
||||
*/
|
||||
perPageAvailable?: Array<number>;
|
||||
|
||||
/**
|
||||
* 是否显示快速跳转输入框
|
||||
* @default false
|
||||
*/
|
||||
showPageInput?: boolean;
|
||||
|
||||
/**
|
||||
* 是否禁用
|
||||
* @default false
|
||||
*/
|
||||
disabled?: boolean;
|
||||
|
||||
hasNext?: boolean;
|
||||
|
||||
/**
|
||||
* 弹层挂载节点
|
||||
* @default false
|
||||
*/
|
||||
popOverContainerSelector?: string;
|
||||
|
||||
/**
|
||||
* 多页跳转页数
|
||||
*
|
||||
* @default 5
|
||||
*/
|
||||
ellipsisPageGap?: number;
|
||||
|
||||
/**
|
||||
* 组件尺寸
|
||||
*
|
||||
* @default 'md'
|
||||
*/
|
||||
size?: string;
|
||||
|
||||
onPageChange?: (page: number, perPage?: number, dir?: string) => void;
|
||||
|
||||
/**
|
||||
* 按钮类型
|
||||
*
|
||||
* @default 'icon'
|
||||
*/
|
||||
buttonType?: string;
|
||||
}
|
||||
export interface PaginationProps
|
||||
extends BasicPaginationProps,
|
||||
ThemeProps,
|
||||
LocaleProps {
|
||||
popOverContainer?: any;
|
||||
testIdBuilder?: TestIdBuilder;
|
||||
}
|
||||
export interface PaginationState {
|
||||
pageNum: string;
|
||||
internalPageNum: string;
|
||||
perPage: number;
|
||||
}
|
||||
export class Pagination extends React.Component<
|
||||
PaginationProps,
|
||||
PaginationState
|
||||
> {
|
||||
static defaultProps = {
|
||||
layout: [PaginationWidget.Pager],
|
||||
maxButtons: 5,
|
||||
mode: 'normal' as MODE_TYPE,
|
||||
activePage: 1,
|
||||
perPage: 10,
|
||||
perPageAvailable: [10, 20, 50, 100],
|
||||
ellipsisPageGap: 5,
|
||||
size: 'md',
|
||||
buttonType: 'icon'
|
||||
};
|
||||
|
||||
state = {
|
||||
pageNum: '',
|
||||
internalPageNum: '1',
|
||||
perPage: Number(this.props.perPage)
|
||||
};
|
||||
|
||||
constructor(props: PaginationProps) {
|
||||
super(props);
|
||||
|
||||
this.handlePageNumChange = this.handlePageNumChange.bind(this);
|
||||
this.renderPageItem = this.renderPageItem.bind(this);
|
||||
this.renderEllipsis = this.renderEllipsis.bind(this);
|
||||
this.handlePageNums = this.handlePageNums.bind(this);
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps: PaginationProps) {
|
||||
if (prevProps.perPage !== this.props.perPage) {
|
||||
const perPage = Number(this.props.perPage);
|
||||
this.setState({perPage: isInteger(perPage) ? perPage : 10});
|
||||
}
|
||||
}
|
||||
|
||||
componentWillReceiveProps(nextProps: PaginationProps) {
|
||||
if (
|
||||
// 原本作用在simple上的样式和部分方法变成了normal的,这里需要重置内部状态
|
||||
this.props.mode !== 'simple' &&
|
||||
nextProps.activePage !== Number(this.state.internalPageNum)
|
||||
) {
|
||||
this.setState({internalPageNum: String(nextProps.activePage)});
|
||||
}
|
||||
}
|
||||
|
||||
async handlePageNumChange(page: number, perPage?: number, dir?: string) {
|
||||
const {disabled, onPageChange} = this.props;
|
||||
const _page = isNaN(Number(page)) || Number(page) < 1 ? 1 : page;
|
||||
|
||||
if (disabled) {
|
||||
return;
|
||||
}
|
||||
onPageChange?.(_page, perPage, dir);
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染每个页码li
|
||||
*
|
||||
* @param page 页码
|
||||
*/
|
||||
renderPageItem(page: number) {
|
||||
const {classnames: cx, activePage, testIdBuilder} = this.props;
|
||||
const {perPage} = this.state;
|
||||
|
||||
return (
|
||||
<li
|
||||
onClick={() => this.handlePageNumChange(page, perPage)}
|
||||
key={page}
|
||||
className={cx('Pagination-pager-item', {
|
||||
'is-active': page === activePage
|
||||
})}
|
||||
>
|
||||
<a
|
||||
role="button"
|
||||
{...testIdBuilder?.getChild(`page-${page}`).getTestId()}
|
||||
>
|
||||
{page}
|
||||
</a>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染...
|
||||
*
|
||||
* @param key 类型 'prev-ellipsis' | 'next-ellipsis'
|
||||
* @param page 页码
|
||||
*/
|
||||
renderEllipsis(key: string) {
|
||||
const {
|
||||
classnames: cx,
|
||||
activePage,
|
||||
ellipsisPageGap,
|
||||
testIdBuilder
|
||||
} = this.props;
|
||||
const {perPage} = this.state;
|
||||
const lastPage = this.getLastPage();
|
||||
const gap: number =
|
||||
isNaN(Number(ellipsisPageGap)) || Number(ellipsisPageGap) < 1
|
||||
? 5
|
||||
: Number(ellipsisPageGap);
|
||||
const isPrevEllipsis = key === 'prev-ellipsis';
|
||||
const jumpContent = isPrevEllipsis ? (
|
||||
<Icon icon="arrow-double-left" className="icon" />
|
||||
) : (
|
||||
<Icon icon="arrow-double-right" className="icon" />
|
||||
);
|
||||
const jumpPage = isPrevEllipsis
|
||||
? Math.max(1, activePage - gap)
|
||||
: Math.min(lastPage, activePage + gap);
|
||||
|
||||
return (
|
||||
<li
|
||||
key={key}
|
||||
className={cx('Pagination-ellipsis')}
|
||||
onClick={(e: any) => {
|
||||
return this.handlePageNumChange(
|
||||
jumpPage,
|
||||
perPage,
|
||||
isPrevEllipsis ? 'backward' : 'forward'
|
||||
);
|
||||
}}
|
||||
{...testIdBuilder?.getChild(key).getTestId()}
|
||||
>
|
||||
<a role="button">...</a>
|
||||
<span className="icon">{jumpContent}</span>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染器事件方法装饰器
|
||||
*
|
||||
* @param cur 当前页数
|
||||
* @param counts 总共页码按钮数
|
||||
* @param min 最小页码
|
||||
* @param max 最大页码
|
||||
*/
|
||||
handlePageNums(
|
||||
cur: number,
|
||||
counts: number,
|
||||
min: number,
|
||||
max: number
|
||||
): Array<any> {
|
||||
const pageButtons: Array<any> = [];
|
||||
if (counts === 0) {
|
||||
return pageButtons;
|
||||
}
|
||||
|
||||
let step = 0;
|
||||
let page = cur;
|
||||
while (true) {
|
||||
if (pageButtons.length >= counts) {
|
||||
return pageButtons;
|
||||
}
|
||||
if (cur - step < min && cur + step > max) {
|
||||
return pageButtons;
|
||||
}
|
||||
page = cur - step;
|
||||
if (pageButtons.length < counts && page >= min) {
|
||||
pageButtons.unshift(this.renderPageItem(page));
|
||||
}
|
||||
page = cur + step;
|
||||
if (step !== 0 && pageButtons.length < counts && page <= max) {
|
||||
pageButtons.push(this.renderPageItem(page));
|
||||
}
|
||||
step++;
|
||||
}
|
||||
}
|
||||
|
||||
getLastPage() {
|
||||
const {total, lastPage, activePage, hasNext} = this.props;
|
||||
const perPage = this.state.perPage;
|
||||
|
||||
// 输入total,重新计算lastPage
|
||||
if (total && perPage) {
|
||||
return Math.ceil(total / (perPage as number));
|
||||
}
|
||||
if (lastPage) {
|
||||
return Number(lastPage);
|
||||
}
|
||||
if (hasNext) {
|
||||
return Number(activePage + 1);
|
||||
}
|
||||
return Number(activePage);
|
||||
}
|
||||
|
||||
@autobind
|
||||
handlePageChange(e: React.ChangeEvent<any>) {
|
||||
const lastPage = this.getLastPage();
|
||||
let value = e.currentTarget.value;
|
||||
|
||||
if (/^\d+$/.test(value) && parseInt(value, 10) > lastPage) {
|
||||
value = String(lastPage);
|
||||
}
|
||||
|
||||
this.setState({pageNum: value});
|
||||
}
|
||||
|
||||
/**
|
||||
* 简洁模式input onChange/onKeyUp事件
|
||||
*
|
||||
* @param event
|
||||
*/
|
||||
@autobind
|
||||
handleSimpleKeyUp(
|
||||
e:
|
||||
| React.KeyboardEvent<HTMLInputElement>
|
||||
| React.ChangeEvent<HTMLInputElement>
|
||||
) {
|
||||
const lastPage = this.getLastPage();
|
||||
const key = (e as React.KeyboardEvent<HTMLInputElement>).key;
|
||||
let v: number = parseInt(e.currentTarget.value, 10);
|
||||
// handle keyboard up and down events value
|
||||
switch (key) {
|
||||
case KeyCode.DOWN:
|
||||
v = isNaN(v) || v < 2 ? 1 : v - 1;
|
||||
break;
|
||||
case KeyCode.UP:
|
||||
v = v + 1;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
// validate inputvalue
|
||||
if (/^\d+$/.test(String(v)) && v >= lastPage) {
|
||||
v = lastPage;
|
||||
}
|
||||
this.setState({internalPageNum: String(v)});
|
||||
// handle empty val
|
||||
if (!v) {
|
||||
this.setState({internalPageNum: ''});
|
||||
return;
|
||||
}
|
||||
if (([KeyCode.UP, KeyCode.DOWN, KeyCode.ENTER] as string[]).includes(key)) {
|
||||
this.handlePageNumChange(v, this.props.perPage);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 简洁模式input onBlur事件
|
||||
*/
|
||||
@autobind
|
||||
handleSimpleBlur() {
|
||||
this.setState({internalPageNum: String(this.props.activePage)});
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
layout,
|
||||
mode,
|
||||
activePage,
|
||||
total,
|
||||
showPerPage,
|
||||
perPageAvailable,
|
||||
classnames: cx,
|
||||
showPageInput,
|
||||
className,
|
||||
style,
|
||||
disabled,
|
||||
hasNext,
|
||||
popOverContainer,
|
||||
popOverContainerSelector,
|
||||
mobileUI,
|
||||
size,
|
||||
translate: __,
|
||||
buttonType,
|
||||
testIdBuilder
|
||||
} = this.props;
|
||||
let maxButtons = this.props.maxButtons;
|
||||
const {pageNum, perPage, internalPageNum} = this.state;
|
||||
const lastPage = this.getLastPage();
|
||||
|
||||
let basePager: React.ReactNode = null;
|
||||
// 移动端复用简洁模式的样式
|
||||
if ((mode !== 'simple' && mobileUI) || mode === 'simple') {
|
||||
basePager = mobileUI ? (
|
||||
// 移动端简洁模式不需要中间的数字
|
||||
mode === 'simple' ? null : (
|
||||
<li className={cx('Pagination-simplego')} key="simple-go">
|
||||
<input
|
||||
className={cx('Pagination-simplego-input')}
|
||||
key="simple-input"
|
||||
type="text"
|
||||
disabled={disabled}
|
||||
onChange={this.handleSimpleKeyUp}
|
||||
onKeyUp={this.handleSimpleKeyUp}
|
||||
onBlur={this.handleSimpleBlur}
|
||||
value={internalPageNum}
|
||||
{...testIdBuilder?.getChild('simple-input').getTestId()}
|
||||
/>
|
||||
/
|
||||
<span className={cx('Pagination-simplego-right')} key="go-right">
|
||||
{lastPage}
|
||||
</span>
|
||||
</li>
|
||||
)
|
||||
) : (
|
||||
<span className="Pagination-simple-number">{activePage}</span>
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx(
|
||||
'Pagination-wrap',
|
||||
`Pagination-wrap-size--${size}`,
|
||||
'Pagination-simple',
|
||||
{disabled: disabled},
|
||||
className
|
||||
)}
|
||||
style={style}
|
||||
{...testIdBuilder?.getTestId()}
|
||||
>
|
||||
<ul
|
||||
key="pager-items"
|
||||
className={cx(
|
||||
'Pagination',
|
||||
'Pagination--sm',
|
||||
'Pagination-pager-items',
|
||||
'Pagination-item'
|
||||
)}
|
||||
>
|
||||
<li
|
||||
className={cx('Pagination-prev', {
|
||||
'is-disabled': activePage < 2
|
||||
})}
|
||||
onClick={(e: any) => {
|
||||
if (activePage < 2) {
|
||||
return e.preventDefault();
|
||||
}
|
||||
|
||||
return this.handlePageNumChange(
|
||||
activePage - 1,
|
||||
undefined,
|
||||
'backward'
|
||||
);
|
||||
}}
|
||||
key="prev"
|
||||
>
|
||||
<span {...testIdBuilder?.getChild(`go-prev`).getTestId()}>
|
||||
{buttonType === 'icon' ? (
|
||||
<Icon icon="left-arrow" className="icon" />
|
||||
) : buttonType === 'text' ? (
|
||||
'上一页'
|
||||
) : null}
|
||||
</span>
|
||||
</li>
|
||||
{basePager}
|
||||
<li
|
||||
className={cx('Pagination-next', {
|
||||
'is-disabled': activePage >= lastPage && !hasNext // 到达最后一页并且没有配置hasNext属性时,禁止点击下一页按钮
|
||||
})}
|
||||
onClick={(e: any) => {
|
||||
if (activePage === lastPage && !hasNext) {
|
||||
return e.preventDefault();
|
||||
}
|
||||
return this.handlePageNumChange(
|
||||
activePage + 1,
|
||||
perPage,
|
||||
'forward'
|
||||
);
|
||||
}}
|
||||
key="next"
|
||||
>
|
||||
<span {...testIdBuilder?.getChild(`go-next`).getTestId()}>
|
||||
{buttonType === 'icon' ? (
|
||||
<Icon icon="right-arrow" className="icon" />
|
||||
) : buttonType === 'text' ? (
|
||||
'下一页'
|
||||
) : null}
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
let pageButtons: any = [];
|
||||
let layoutList: Array<string> = Array.isArray(layout)
|
||||
? layout
|
||||
: typeof layout === 'string'
|
||||
? layout.split(',')
|
||||
: [];
|
||||
|
||||
/** 分页组件至少要包含页码 */
|
||||
if (!layoutList.includes(PaginationWidget.Pager)) {
|
||||
layoutList.unshift(PaginationWidget.Pager);
|
||||
}
|
||||
/** 统一使用小写格式,外部属性case insensitive */
|
||||
layoutList = layoutList.map(widget => widget.trim().toLowerCase());
|
||||
|
||||
/** 兼容showPageInput属性,默认展示跳转页面 */
|
||||
if (showPageInput && !layoutList.includes(PaginationWidget.Go)) {
|
||||
layoutList.push(PaginationWidget.Go);
|
||||
}
|
||||
|
||||
if (showPerPage && !layoutList.includes(PaginationWidget.PerPage)) {
|
||||
layoutList.unshift(PaginationWidget.PerPage);
|
||||
}
|
||||
|
||||
// 页码全部显示 [1, 2, 3, 4]
|
||||
if (lastPage <= maxButtons) {
|
||||
pageButtons = this.handlePageNums(
|
||||
activePage,
|
||||
maxButtons,
|
||||
1,
|
||||
Math.min(maxButtons, lastPage)
|
||||
);
|
||||
}
|
||||
//当前为1234页时, [1, 2, 3, 4, 5, ... 12]
|
||||
else if (activePage <= maxButtons - 3) {
|
||||
pageButtons = this.handlePageNums(
|
||||
activePage,
|
||||
maxButtons - 2,
|
||||
1,
|
||||
Math.min(maxButtons - 2, lastPage)
|
||||
);
|
||||
pageButtons.push(this.renderEllipsis('next-ellipsis'));
|
||||
pageButtons.push(this.renderPageItem(lastPage));
|
||||
}
|
||||
// [1, ..., 5, 6, 7, 8, 9]
|
||||
else if (activePage > lastPage - (maxButtons - 3)) {
|
||||
const min = lastPage - (maxButtons - 3);
|
||||
pageButtons = this.handlePageNums(
|
||||
activePage,
|
||||
maxButtons - 2,
|
||||
min,
|
||||
lastPage
|
||||
);
|
||||
pageButtons.unshift(this.renderEllipsis('prev-ellipsis'));
|
||||
pageButtons.unshift(this.renderPageItem(1));
|
||||
}
|
||||
// [1, ... 4, 5, 6, ... 10]
|
||||
else {
|
||||
pageButtons = this.handlePageNums(
|
||||
activePage,
|
||||
maxButtons - 2,
|
||||
3,
|
||||
lastPage - 3
|
||||
);
|
||||
pageButtons.unshift(this.renderEllipsis('prev-ellipsis'));
|
||||
pageButtons.unshift(this.renderPageItem(1));
|
||||
pageButtons.push(this.renderEllipsis('next-ellipsis'));
|
||||
pageButtons.push(this.renderPageItem(lastPage));
|
||||
}
|
||||
pageButtons.unshift(
|
||||
<li
|
||||
className={cx('Pagination-prev', {
|
||||
'is-disabled': activePage < 2
|
||||
})}
|
||||
onClick={(e: any) => {
|
||||
if (activePage < 2) {
|
||||
return e.preventDefault();
|
||||
}
|
||||
return this.handlePageNumChange(activePage - 1, perPage);
|
||||
}}
|
||||
key="prev"
|
||||
>
|
||||
<span {...testIdBuilder?.getChild('go-prev').getTestId()}>
|
||||
{buttonType === 'icon' ? (
|
||||
<Icon icon="left-arrow" className="icon" />
|
||||
) : buttonType === 'text' ? (
|
||||
'上一页'
|
||||
) : null}
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
|
||||
pageButtons.push(
|
||||
<li
|
||||
className={cx('Pagination-next', {
|
||||
'is-disabled': activePage === lastPage
|
||||
})}
|
||||
onClick={(e: any) => {
|
||||
if (activePage === lastPage) {
|
||||
return e.preventDefault();
|
||||
}
|
||||
return this.handlePageNumChange(activePage + 1, perPage);
|
||||
}}
|
||||
key="next"
|
||||
>
|
||||
<span {...testIdBuilder?.getChild('go-next').getTestId()}>
|
||||
{buttonType === 'icon' ? (
|
||||
<Icon icon="right-arrow" className="icon" />
|
||||
) : buttonType === 'text' ? (
|
||||
'下一页'
|
||||
) : null}
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
|
||||
if (mobileUI) {
|
||||
pageButtons = [
|
||||
pageButtons[0],
|
||||
// this.renderPageItem(activePage),
|
||||
pageButtons[pageButtons.length - 1]
|
||||
];
|
||||
}
|
||||
|
||||
const go = mobileUI ? null : (
|
||||
<div className={cx('Pagination-inputGroup Pagination-item')} key="go">
|
||||
<span className={cx('Pagination-inputGroup-left')} key="go-left">
|
||||
{__('Pagination.goto')}
|
||||
</span>
|
||||
<input
|
||||
className={cx('Pagination-inputGroup-input')}
|
||||
key="go-input"
|
||||
type="text"
|
||||
disabled={disabled}
|
||||
onChange={this.handlePageChange}
|
||||
onFocus={(e: any) => e.currentTarget.select()}
|
||||
onKeyUp={(e: any) => {
|
||||
const v: number = parseInt(e.currentTarget.value, 10);
|
||||
if (!v || e.code != 'Enter') {
|
||||
return;
|
||||
}
|
||||
this.setState({pageNum: ''});
|
||||
this.handlePageNumChange(v, perPage);
|
||||
}}
|
||||
value={pageNum}
|
||||
{...testIdBuilder?.getChild('go-input').getTestId()}
|
||||
/>
|
||||
<span
|
||||
className={cx('Pagination-inputGroup-right')}
|
||||
key="go-right"
|
||||
onClick={(e: any) => {
|
||||
if (!pageNum) {
|
||||
return;
|
||||
}
|
||||
this.setState({pageNum: ''});
|
||||
this.handlePageNumChange(+pageNum, perPage);
|
||||
}}
|
||||
{...testIdBuilder?.getChild('go').getTestId()}
|
||||
>
|
||||
{__('Pagination.go')}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
const selection = (perPageAvailable as Array<number>)
|
||||
.filter(v => !!v)
|
||||
.map(v => ({label: __('Pagination.select', {count: v}), value: v}));
|
||||
const perPageEle = mobileUI ? null : (
|
||||
<Select
|
||||
key="perpage"
|
||||
className={cx('Pagination-perpage', 'Pagination-item')}
|
||||
clearable={false}
|
||||
disabled={disabled}
|
||||
value={perPage}
|
||||
options={selection || []}
|
||||
popOverContainer={popOverContainer}
|
||||
popOverContainerSelector={popOverContainerSelector}
|
||||
onChange={(p: any) => {
|
||||
this.setState({
|
||||
perPage: p.value,
|
||||
pageNum: ''
|
||||
});
|
||||
this.handlePageNumChange(1, p.value);
|
||||
}}
|
||||
{...testIdBuilder?.getChild('perpage').getTestId()}
|
||||
/>
|
||||
);
|
||||
|
||||
// total或者lastpage不存在,不渲染总数
|
||||
const totalPage =
|
||||
!(total || lastPage) || mobileUI ? null : (
|
||||
<div className={cx('Pagination-total Pagination-item')} key="total">
|
||||
{total || total === 0
|
||||
? __('Pagination.totalCount', {total})
|
||||
: __('Pagination.totalPage', {lastPage})}
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div
|
||||
className={cx(
|
||||
'Pagination-wrap',
|
||||
`Pagination-wrap-size--${size}`,
|
||||
{disabled: disabled},
|
||||
className
|
||||
)}
|
||||
{...testIdBuilder?.getTestId()}
|
||||
>
|
||||
{layoutList.map(layoutItem => {
|
||||
if (layoutItem === PaginationWidget.Pager) {
|
||||
return (
|
||||
<ul
|
||||
key="pager-items"
|
||||
className={cx(
|
||||
'Pagination',
|
||||
'Pagination--sm',
|
||||
'Pagination-item'
|
||||
)}
|
||||
>
|
||||
{pageButtons}
|
||||
</ul>
|
||||
);
|
||||
} else if (layoutItem === PaginationWidget.Go) {
|
||||
return go;
|
||||
} else if (layoutItem === PaginationWidget.PerPage) {
|
||||
return perPageEle;
|
||||
} else if (layoutItem === PaginationWidget.Total) {
|
||||
return totalPage;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(localeable(Pagination));
|
||||
144
packages/amis-ui/src/components/PdfViewer.tsx
Normal file
144
packages/amis-ui/src/components/PdfViewer.tsx
Normal file
@@ -0,0 +1,144 @@
|
||||
/**
|
||||
* @file PdfViewer.tsx PDF 预览
|
||||
*
|
||||
* @created: 2024/02/26
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import {themeable, ThemeProps, getGlobalOptions} from 'amis-core';
|
||||
import {Document, Page, pdfjs} from 'react-pdf';
|
||||
import {Icon} from './icons';
|
||||
import Input from './Input';
|
||||
import Spinner from './Spinner';
|
||||
|
||||
pdfjs.GlobalWorkerOptions.workerSrc = getGlobalOptions().pdfjsWorkerSrc;
|
||||
export interface PdfViewerProps extends ThemeProps {
|
||||
file?: ArrayBuffer;
|
||||
width?: number;
|
||||
height?: number;
|
||||
background?: string;
|
||||
loading: boolean;
|
||||
}
|
||||
|
||||
const PdfViewer: React.FC<PdfViewerProps> = props => {
|
||||
const {classnames: cx, className, loading, width = 300} = props;
|
||||
const [file, setFile] = React.useState(props.file);
|
||||
const [loaded, setLoaded] = React.useState(false);
|
||||
const [page, setPage] = React.useState(1);
|
||||
const [scale, setScale] = React.useState(1);
|
||||
const [total, setTotal] = React.useState(1);
|
||||
const inputRef = React.useRef<HTMLInputElement>();
|
||||
|
||||
React.useEffect(() => {
|
||||
if (props.file instanceof ArrayBuffer && props.file.byteLength > 0) {
|
||||
setFile(props.file);
|
||||
} else {
|
||||
setFile(undefined);
|
||||
}
|
||||
}, [props.file]);
|
||||
|
||||
function handleLoadSuccess({numPages}: {numPages: number}) {
|
||||
setLoaded(true);
|
||||
setTotal(numPages);
|
||||
}
|
||||
|
||||
function handleChangePage(idx: number) {
|
||||
const newPage = page + idx;
|
||||
if (newPage <= 0 || newPage > total) {
|
||||
return;
|
||||
}
|
||||
setPage(newPage);
|
||||
}
|
||||
|
||||
function handlePageBlur(event: React.ChangeEvent<HTMLInputElement>) {
|
||||
const newPage = +event.target.value;
|
||||
if (isNaN(newPage) || newPage <= 0 || newPage > total) {
|
||||
if (inputRef.current) {
|
||||
inputRef.current.value = page + '';
|
||||
}
|
||||
return;
|
||||
}
|
||||
setPage(newPage);
|
||||
}
|
||||
|
||||
function handleChangeScale(t: number) {
|
||||
setScale(scale * t);
|
||||
}
|
||||
|
||||
function renderLoading() {
|
||||
return (
|
||||
<div className={cx('PdfViewer-Loading')}>
|
||||
<Spinner />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function renderTool() {
|
||||
return (
|
||||
<div className={cx('PdfViewer-Tool')}>
|
||||
<Icon
|
||||
className="icon"
|
||||
icon="prev"
|
||||
onClick={() => handleChangePage(-1)}
|
||||
/>
|
||||
<Input
|
||||
className="page-input"
|
||||
value={page}
|
||||
onBlur={handlePageBlur}
|
||||
ref={inputRef}
|
||||
/>
|
||||
<span className="gap">/</span>
|
||||
<span>{total}</span>
|
||||
<Icon
|
||||
className="icon"
|
||||
icon="next"
|
||||
onClick={() => handleChangePage(1)}
|
||||
/>
|
||||
<Icon
|
||||
className="icon"
|
||||
icon="zoom-in"
|
||||
onClick={() => handleChangeScale(1.2)}
|
||||
/>
|
||||
<Icon
|
||||
className="icon"
|
||||
icon="zoom-out"
|
||||
onClick={() => handleChangeScale(0.8)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cx(className, 'PdfViewer')}>
|
||||
{!file || loading ? (
|
||||
renderLoading()
|
||||
) : (
|
||||
<>
|
||||
<div className={cx('PdfViewer-Content', {'is-loaded': loaded})}>
|
||||
<Document
|
||||
file={file}
|
||||
onLoadSuccess={handleLoadSuccess}
|
||||
onLoadError={err => console.log(err)}
|
||||
loading={renderLoading()}
|
||||
>
|
||||
<Page
|
||||
className={cx('PdfViewer-Content-Page')}
|
||||
pageNumber={page}
|
||||
width={width}
|
||||
height={props.height}
|
||||
loading={renderLoading()}
|
||||
noData={<div>No PDF data</div>}
|
||||
scale={scale}
|
||||
renderTextLayer={false}
|
||||
renderAnnotationLayer={false}
|
||||
/>
|
||||
</Document>
|
||||
</div>
|
||||
{loaded ? renderTool() : null}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default themeable(PdfViewer);
|
||||
164
packages/amis-ui/src/components/Picker.tsx
Normal file
164
packages/amis-ui/src/components/Picker.tsx
Normal file
@@ -0,0 +1,164 @@
|
||||
/**
|
||||
* @file Picker
|
||||
* @description 移动端列滚动选择器
|
||||
*/
|
||||
import React, {memo, ReactNode, useState, useEffect} from 'react';
|
||||
import {uncontrollable} from 'amis-core';
|
||||
|
||||
import {themeable, ThemeProps} from 'amis-core';
|
||||
import {localeable, LocaleProps} from 'amis-core';
|
||||
|
||||
import Button from './Button';
|
||||
import {PickerColumnItem, default as Column} from './PickerColumn';
|
||||
|
||||
export type PickerValue = string | number;
|
||||
|
||||
export interface PickerProps extends ThemeProps, LocaleProps {
|
||||
title?: String | ReactNode;
|
||||
labelField?: string;
|
||||
valueField?: string;
|
||||
className?: string;
|
||||
showToolbar?: boolean;
|
||||
defaultValue?: PickerValue[];
|
||||
value?: PickerValue[];
|
||||
swipeDuration?: number;
|
||||
visibleItemCount?: number;
|
||||
highlightTxt?: string;
|
||||
itemHeight?: number;
|
||||
columns: PickerColumnItem[] | PickerColumnItem;
|
||||
onChange?: (value?: PickerValue[], index?: number, confirm?: boolean) => void;
|
||||
onClose?: (value?: PickerValue[]) => void;
|
||||
onConfirm?: (value?: PickerValue[]) => void;
|
||||
}
|
||||
|
||||
function fixToArray(data: any) {
|
||||
if (!Array.isArray(data)) {
|
||||
return [data];
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
const Picker = memo<PickerProps>(props => {
|
||||
const {
|
||||
title,
|
||||
labelField,
|
||||
valueField,
|
||||
visibleItemCount = 5,
|
||||
value = [],
|
||||
swipeDuration = 1000,
|
||||
columns = [],
|
||||
itemHeight = 48,
|
||||
showToolbar = true,
|
||||
className = '',
|
||||
highlightTxt = '',
|
||||
classnames: cx,
|
||||
classPrefix: ns,
|
||||
translate: __
|
||||
} = props;
|
||||
|
||||
const _columns = fixToArray(columns);
|
||||
const [innerValue, setInnerValue] = useState<PickerValue[]>(
|
||||
fixToArray(props.value === undefined ? props.defaultValue || [] : value)
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (value === innerValue) return;
|
||||
setInnerValue(fixToArray(value));
|
||||
}, [value]);
|
||||
|
||||
const close = () => {
|
||||
if (props.onClose) {
|
||||
props.onClose(innerValue);
|
||||
}
|
||||
};
|
||||
|
||||
const confirm = () => {
|
||||
if (props.onConfirm) {
|
||||
props.onConfirm(innerValue);
|
||||
}
|
||||
};
|
||||
|
||||
const onChange = (
|
||||
itemValue: PickerValue,
|
||||
columnIndex: number,
|
||||
confirm?: boolean
|
||||
) => {
|
||||
const nextInnerValue = [...innerValue];
|
||||
nextInnerValue[columnIndex] = itemValue;
|
||||
setInnerValue(nextInnerValue);
|
||||
if (props.onChange) {
|
||||
props.onChange(nextInnerValue, columnIndex, confirm);
|
||||
}
|
||||
};
|
||||
|
||||
const renderColumnItem = (item: PickerColumnItem, index: number) => {
|
||||
return (
|
||||
<Column
|
||||
{...item}
|
||||
highlightTxt={highlightTxt}
|
||||
classnames={cx}
|
||||
classPrefix={ns}
|
||||
labelField={labelField || item.labelField}
|
||||
valueField={valueField || item.valueField}
|
||||
itemHeight={itemHeight}
|
||||
swipeDuration={swipeDuration}
|
||||
visibleItemCount={visibleItemCount}
|
||||
value={innerValue[index]}
|
||||
onChange={(val: string | number, i, confirm) => {
|
||||
onChange(val, index, confirm);
|
||||
}}
|
||||
key={`column${index}`}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const wrapHeight = itemHeight * +visibleItemCount;
|
||||
const frameStyle = {height: `${itemHeight}px`};
|
||||
const columnsStyle = {height: `${wrapHeight}px`};
|
||||
const maskStyle = {
|
||||
backgroundSize: `100% ${(wrapHeight - itemHeight) / 2}px`
|
||||
};
|
||||
const hasHeader = showToolbar || title;
|
||||
return (
|
||||
<div className={cx(className, 'PickerColumns', 'PickerColumns-popOver')}>
|
||||
{hasHeader && (
|
||||
<div className={cx('PickerColumns-header')}>
|
||||
{showToolbar && (
|
||||
<Button
|
||||
className="PickerColumns-cancel"
|
||||
level="link"
|
||||
onClick={close}
|
||||
>
|
||||
{__('cancel')}
|
||||
</Button>
|
||||
)}
|
||||
{title && <div className={cx('PickerColumns-title')}>{title}</div>}
|
||||
{showToolbar && (
|
||||
<Button
|
||||
className="PickerColumns-confirm"
|
||||
level="link"
|
||||
onClick={confirm}
|
||||
>
|
||||
{__('confirm')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className={cx('PickerColumns-columns')} style={columnsStyle}>
|
||||
{_columns.map((column: PickerColumnItem, index: number) =>
|
||||
renderColumnItem(column, index)
|
||||
)}
|
||||
<div className={cx('PickerColumns-mask')} style={maskStyle}></div>
|
||||
<div className={cx('PickerColumns-frame')} style={frameStyle}></div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
export default themeable(
|
||||
localeable(
|
||||
uncontrollable(Picker, {
|
||||
value: 'onChange'
|
||||
})
|
||||
)
|
||||
);
|
||||
404
packages/amis-ui/src/components/PickerColumn.tsx
Normal file
404
packages/amis-ui/src/components/PickerColumn.tsx
Normal file
@@ -0,0 +1,404 @@
|
||||
/**
|
||||
* @file Picker
|
||||
* @description 移动端列滚动选择器
|
||||
*/
|
||||
import React, {
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useImperativeHandle,
|
||||
useCallback,
|
||||
forwardRef
|
||||
} from 'react';
|
||||
import isObject from 'lodash/isObject';
|
||||
import cloneDeep from 'lodash/cloneDeep';
|
||||
import {uncontrollable, highlight, labelToString} from 'amis-core';
|
||||
|
||||
import {useSetState, useUpdateEffect} from '../hooks';
|
||||
import {range} from 'amis-core';
|
||||
import {themeable, ThemeProps} from 'amis-core';
|
||||
import useTouch from '../hooks/use-touch';
|
||||
|
||||
export interface PickerColumnItem {
|
||||
labelField?: string;
|
||||
valueField?: string;
|
||||
readonly?: boolean;
|
||||
value?: PickerOption;
|
||||
swipeDuration?: number;
|
||||
visibleItemCount?: number;
|
||||
itemHeight?: number;
|
||||
options?: PickerOption[];
|
||||
highlightTxt?: string;
|
||||
optionRender?: (...params: any) => React.ReactNode;
|
||||
onChange?: (
|
||||
value?: PickerOption | string,
|
||||
index?: number,
|
||||
confirm?: boolean
|
||||
) => void;
|
||||
}
|
||||
|
||||
export interface PickerColumnProps extends PickerColumnItem, ThemeProps {}
|
||||
|
||||
export type PickerOption = string | number | PickerObjectOption;
|
||||
|
||||
export type PickerObjectOption = {
|
||||
value?: string | number;
|
||||
text?: string | number;
|
||||
disabled?: boolean;
|
||||
} & Record<string, {}>;
|
||||
|
||||
const DEFAULT_DURATION = 200;
|
||||
const MOMENTUM_LIMIT_TIME = 300;
|
||||
const MOMENTUM_LIMIT_DISTANCE = 15;
|
||||
|
||||
function getElementTranslateY(element: HTMLElement | null) {
|
||||
if (!element) {
|
||||
return 0;
|
||||
}
|
||||
const style = window.getComputedStyle(element);
|
||||
const transform = style.transform || style.webkitTransform;
|
||||
// 格式如:matrix( scaleX(), skewY(), skewX(), scaleY(), translateX(), translateY() );
|
||||
const translateY = transform.slice(7, transform.length - 1).split(', ')[5];
|
||||
|
||||
return Number(translateY);
|
||||
}
|
||||
|
||||
function isOptionDisabled(option: PickerOption) {
|
||||
return isObject(option) && option.disabled;
|
||||
}
|
||||
|
||||
const PickerColumn = forwardRef<{}, PickerColumnProps>((props, ref) => {
|
||||
const {
|
||||
visibleItemCount = 5,
|
||||
itemHeight = 48,
|
||||
value,
|
||||
valueField = 'value',
|
||||
swipeDuration = 1000,
|
||||
labelField = 'text',
|
||||
highlightTxt = '',
|
||||
options = [],
|
||||
classnames: cx
|
||||
} = props;
|
||||
|
||||
const root = useRef(null);
|
||||
const menuItemRef = useRef(null);
|
||||
const wrapper = useRef(null);
|
||||
|
||||
const moving = useRef(false);
|
||||
const startOffset = useRef(0);
|
||||
const transitionEndTrigger = useRef(null);
|
||||
const touchStartTime = useRef(0);
|
||||
const momentumOffset = useRef(0);
|
||||
|
||||
const touch = useTouch();
|
||||
const count = options.length;
|
||||
|
||||
const getOptionText = (option: [] | PickerOption) => {
|
||||
if (isObject(option) && labelField in option) {
|
||||
//@ts-ignore
|
||||
return labelToString(option[labelField]);
|
||||
}
|
||||
return labelToString(option);
|
||||
};
|
||||
|
||||
const getOptionValue = (option: [] | PickerOption) => {
|
||||
if (isObject(option) && valueField in option) {
|
||||
//@ts-ignore
|
||||
return option[valueField];
|
||||
}
|
||||
return option;
|
||||
};
|
||||
|
||||
const defaultIndex = options.findIndex(
|
||||
item => getOptionValue(item) === value
|
||||
);
|
||||
|
||||
const baseOffset = useMemo(() => {
|
||||
// 默认转入第一个选项的位置
|
||||
return (itemHeight * (+visibleItemCount - 1)) / 2;
|
||||
}, [itemHeight, visibleItemCount]);
|
||||
|
||||
const adjustIndex = (index: number) => {
|
||||
index = range(index, 0, count);
|
||||
if (!options) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (let i = index; i < count; i += 1) {
|
||||
if (!isOptionDisabled(options[i])) return i;
|
||||
}
|
||||
for (let i = index - 1; i >= 0; i -= 1) {
|
||||
if (!isOptionDisabled(options[i])) return i;
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const [state, updateState] = useSetState({
|
||||
index: adjustIndex(defaultIndex) || 0,
|
||||
offset: 0,
|
||||
duration: 0,
|
||||
options: cloneDeep(options)
|
||||
});
|
||||
|
||||
/**
|
||||
*
|
||||
* @param index 索引
|
||||
* @param emitChange 是否派发变动消息
|
||||
* @param confirm 是否为确认类型,为真时触发value改变
|
||||
*/
|
||||
const setIndex = (index: number, emitChange?: boolean, confirm?: boolean) => {
|
||||
index = adjustIndex(index) || 0;
|
||||
|
||||
const offset = -index * itemHeight;
|
||||
const trigger = () => {
|
||||
updateState({index});
|
||||
|
||||
if (emitChange && props.onChange) {
|
||||
requestAnimationFrame(() => {
|
||||
props.onChange?.(getOptionValue(options[index]), index, confirm);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// trigger the change event after transitionend when moving
|
||||
if (moving.current && offset !== state.offset) {
|
||||
//@ts-ignore
|
||||
transitionEndTrigger.current = trigger;
|
||||
} else {
|
||||
trigger();
|
||||
}
|
||||
updateState({offset});
|
||||
};
|
||||
|
||||
const setOptions = (options: Array<PickerOption>) => {
|
||||
if (JSON.stringify(options) !== JSON.stringify(state.options)) {
|
||||
updateState({options});
|
||||
const index =
|
||||
options.findIndex(item => getOptionValue(item) === value) || 0;
|
||||
setIndex(index, true, true);
|
||||
}
|
||||
};
|
||||
|
||||
const onClickItem = (index: number) => {
|
||||
if (moving.current || props.readonly) {
|
||||
return;
|
||||
}
|
||||
transitionEndTrigger.current = null;
|
||||
updateState({duration: DEFAULT_DURATION});
|
||||
setIndex(index, true, true);
|
||||
};
|
||||
|
||||
const getIndexByOffset = (offset: number) =>
|
||||
range(Math.round(-offset / itemHeight), 0, count - 1);
|
||||
|
||||
const momentum = (distance: number, duration: number) => {
|
||||
const speed = Math.abs(distance / duration);
|
||||
|
||||
distance = state.offset + (speed / 0.003) * (distance < 0 ? -1 : 1);
|
||||
|
||||
const index = getIndexByOffset(distance);
|
||||
updateState({duration: +swipeDuration});
|
||||
setIndex(index, true);
|
||||
};
|
||||
|
||||
const stopMomentum = () => {
|
||||
moving.current = false;
|
||||
updateState({duration: 0});
|
||||
|
||||
if (transitionEndTrigger.current) {
|
||||
//@ts-ignore
|
||||
transitionEndTrigger.current();
|
||||
transitionEndTrigger.current = null;
|
||||
}
|
||||
};
|
||||
|
||||
const onTouchStart = (event: any) => {
|
||||
if (props.readonly) {
|
||||
return;
|
||||
}
|
||||
|
||||
touch.start(event);
|
||||
let {offset} = state;
|
||||
|
||||
if (moving.current) {
|
||||
const translateY = getElementTranslateY(wrapper.current);
|
||||
offset = Math.min(0, translateY - baseOffset);
|
||||
startOffset.current = offset;
|
||||
} else {
|
||||
startOffset.current = offset;
|
||||
}
|
||||
|
||||
updateState({duration: 0, offset});
|
||||
touchStartTime.current = Date.now();
|
||||
momentumOffset.current = startOffset.current;
|
||||
transitionEndTrigger.current = null;
|
||||
};
|
||||
|
||||
const onTouchMove = (event: TouchEvent | React.TouchEvent) => {
|
||||
if (props.readonly) {
|
||||
return;
|
||||
}
|
||||
|
||||
touch.move(event as TouchEvent);
|
||||
|
||||
if (touch.isVertical()) {
|
||||
moving.current = true;
|
||||
}
|
||||
|
||||
const offset = range(
|
||||
startOffset.current + touch.deltaY,
|
||||
-(count * itemHeight),
|
||||
itemHeight
|
||||
);
|
||||
|
||||
updateState({
|
||||
offset
|
||||
});
|
||||
|
||||
const now = Date.now();
|
||||
if (now - touchStartTime.current > MOMENTUM_LIMIT_TIME) {
|
||||
touchStartTime.current = now;
|
||||
momentumOffset.current = offset;
|
||||
}
|
||||
};
|
||||
|
||||
const onTouchEnd = () => {
|
||||
if (props.readonly) {
|
||||
return;
|
||||
}
|
||||
const distance = state.offset - momentumOffset.current;
|
||||
const duration = Date.now() - touchStartTime.current;
|
||||
|
||||
const allowMomentum =
|
||||
duration < MOMENTUM_LIMIT_TIME &&
|
||||
Math.abs(distance) > MOMENTUM_LIMIT_DISTANCE;
|
||||
|
||||
if (allowMomentum) {
|
||||
momentum(distance, duration);
|
||||
return;
|
||||
}
|
||||
|
||||
const index = getIndexByOffset(state.offset);
|
||||
updateState({duration: DEFAULT_DURATION});
|
||||
setIndex(index, true);
|
||||
|
||||
// compatible with desktop scenario
|
||||
// use setTimeout to skip the click event triggered after touchstart
|
||||
setTimeout(() => {
|
||||
moving.current = false;
|
||||
}, 0);
|
||||
};
|
||||
|
||||
const renderOptions = () => {
|
||||
const style = {
|
||||
height: `${itemHeight}px`,
|
||||
lineHeight: `${itemHeight}px`
|
||||
};
|
||||
return state.options.map((option, index: number) => {
|
||||
const text: string = getOptionText(option);
|
||||
const disabled = isOptionDisabled(option);
|
||||
|
||||
const data = {
|
||||
role: 'button',
|
||||
key: index,
|
||||
style,
|
||||
tabIndex: disabled ? -1 : 0,
|
||||
className: props.classnames(`PickerColumns-columnItem`, {
|
||||
'is-disabled': disabled,
|
||||
'is-selected': index === state.index
|
||||
}),
|
||||
onClick: () => {
|
||||
onClickItem(index);
|
||||
}
|
||||
};
|
||||
|
||||
const childData = {
|
||||
className: 'text-ellipsis',
|
||||
children: (highlightTxt
|
||||
? highlight(text, highlightTxt, cx('Select-option-hl'))
|
||||
: text) as React.ReactNode
|
||||
};
|
||||
|
||||
return (
|
||||
<li {...data} ref={menuItemRef}>
|
||||
{props.optionRender ? (
|
||||
props.optionRender(option, {index, checked: state.index === index})
|
||||
) : (
|
||||
<div {...childData} />
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
const setValue = (value: string) => {
|
||||
const {options} = state;
|
||||
for (let i = 0; i < options.length; i += 1) {
|
||||
if (options[i] === value) {
|
||||
return setIndex(i);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const getValue = useCallback<() => PickerOption>(
|
||||
() => state.options[state.index],
|
||||
[state.index, state.options]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setIndex(defaultIndex);
|
||||
}, [defaultIndex]);
|
||||
|
||||
useUpdateEffect(() => {
|
||||
setOptions(cloneDeep(options));
|
||||
}, [options]);
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
state,
|
||||
setIndex,
|
||||
getValue,
|
||||
setValue,
|
||||
setOptions,
|
||||
stopMomentum
|
||||
}));
|
||||
|
||||
const wrapperStyle = {
|
||||
transform: `translate3d(0, ${state.offset + baseOffset}px, 0)`,
|
||||
transitionDuration: `${state.duration}ms`,
|
||||
transitionProperty: state.duration ? 'all' : 'none'
|
||||
};
|
||||
return (
|
||||
<div
|
||||
ref={root}
|
||||
className={props.classnames('PickerColumns', props.className)}
|
||||
onTouchStart={onTouchStart}
|
||||
onTouchMove={onTouchMove}
|
||||
onTouchEnd={onTouchEnd}
|
||||
onTouchCancel={onTouchEnd}
|
||||
>
|
||||
<ul
|
||||
ref={wrapper}
|
||||
style={wrapperStyle}
|
||||
className={props.classnames('PickerColumns-columnWrapper')}
|
||||
onTransitionEnd={stopMomentum}
|
||||
>
|
||||
{renderOptions()}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
PickerColumn.defaultProps = {
|
||||
options: [],
|
||||
visibleItemCount: 5,
|
||||
swipeDuration: 1000,
|
||||
itemHeight: 48
|
||||
};
|
||||
|
||||
export default themeable(
|
||||
uncontrollable(PickerColumn, {
|
||||
value: 'onChange'
|
||||
})
|
||||
);
|
||||
192
packages/amis-ui/src/components/PickerContainer.tsx
Normal file
192
packages/amis-ui/src/components/PickerContainer.tsx
Normal file
@@ -0,0 +1,192 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
autobind,
|
||||
isObject,
|
||||
themeable,
|
||||
ThemeProps,
|
||||
localeable,
|
||||
LocaleProps
|
||||
} from 'amis-core';
|
||||
import Modal from './Modal';
|
||||
import Button from './Button';
|
||||
import ConfirmBox, {ConfirmBoxProps} from './ConfirmBox';
|
||||
import type {TestIdBuilder} from 'amis-core';
|
||||
|
||||
export interface PickerContainerProps
|
||||
extends ThemeProps,
|
||||
LocaleProps,
|
||||
Omit<ConfirmBoxProps, 'children' | 'type'> {
|
||||
children: (props: {
|
||||
onClick: (e: React.MouseEvent) => void;
|
||||
setState: (state: any) => void;
|
||||
isOpened: boolean;
|
||||
}) => JSX.Element;
|
||||
bodyRender: (props: {
|
||||
onClose: () => void;
|
||||
value: any;
|
||||
onChange: (value: any) => void;
|
||||
setState: (state: any) => void;
|
||||
loading?: boolean;
|
||||
[propName: string]: any;
|
||||
}) => JSX.Element | null;
|
||||
value?: any;
|
||||
onFocus?: () => void;
|
||||
onClose?: () => void;
|
||||
disabled?: boolean;
|
||||
onPickerOpen?: (props: PickerContainerProps) => any;
|
||||
popOverContainer?: any;
|
||||
testIdBuilder?: TestIdBuilder;
|
||||
}
|
||||
|
||||
export interface PickerContainerState {
|
||||
isOpened: boolean;
|
||||
value?: any;
|
||||
}
|
||||
|
||||
export class PickerContainer extends React.Component<
|
||||
PickerContainerProps,
|
||||
PickerContainerState
|
||||
> {
|
||||
state: PickerContainerState = {
|
||||
isOpened: false,
|
||||
value: this.props.value
|
||||
};
|
||||
|
||||
componentDidUpdate(prevProps: PickerContainerProps) {
|
||||
const props = this.props;
|
||||
|
||||
if (props.value !== prevProps.value) {
|
||||
this.setState({
|
||||
value: props.value
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@autobind
|
||||
async handleClick() {
|
||||
const state = {
|
||||
value: this.props.value,
|
||||
...(await this.props.onPickerOpen?.(this.props)),
|
||||
isOpened: true
|
||||
};
|
||||
this.setState(state, () => this.props.onFocus?.());
|
||||
}
|
||||
|
||||
@autobind
|
||||
close(e?: any, callback?: () => void) {
|
||||
this.setState(
|
||||
{
|
||||
isOpened: false
|
||||
},
|
||||
() => {
|
||||
this.props.onClose?.();
|
||||
if (callback) {
|
||||
callback();
|
||||
return;
|
||||
}
|
||||
this.props.onCancel?.();
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleChange(value: any) {
|
||||
this.setState({
|
||||
value
|
||||
});
|
||||
}
|
||||
|
||||
@autobind
|
||||
async beforeConfirm(form?: any): Promise<any> {
|
||||
const {onConfirm, beforeConfirm} = this.props;
|
||||
|
||||
const ret = beforeConfirm
|
||||
? await beforeConfirm?.(form)
|
||||
: await form?.submit?.();
|
||||
|
||||
let state: any = {
|
||||
isOpened: false
|
||||
};
|
||||
|
||||
// beforeConfirm 返回 false 则阻止后续动作
|
||||
if (ret === false) {
|
||||
return false;
|
||||
} else if (isObject(ret)) {
|
||||
state.value = ret;
|
||||
}
|
||||
await onConfirm?.(state.value ?? this.state.value);
|
||||
this.setState(state);
|
||||
}
|
||||
|
||||
@autobind
|
||||
updateState(state: any = {}) {
|
||||
const {isOpened, ...rest} = state;
|
||||
this.setState({
|
||||
...this.state,
|
||||
...rest
|
||||
});
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
children,
|
||||
bodyRender: popOverRender,
|
||||
title,
|
||||
showTitle,
|
||||
headerClassName,
|
||||
bodyClassName,
|
||||
className,
|
||||
translate: __,
|
||||
size,
|
||||
showFooter,
|
||||
closeOnEsc,
|
||||
popOverContainer,
|
||||
mobileUI,
|
||||
disabled,
|
||||
testIdBuilder
|
||||
} = this.props;
|
||||
return (
|
||||
<>
|
||||
{children({
|
||||
isOpened: this.state.isOpened,
|
||||
onClick: this.handleClick,
|
||||
setState: this.updateState
|
||||
})}
|
||||
|
||||
<ConfirmBox
|
||||
type="dialog"
|
||||
size={size}
|
||||
closeOnEsc={closeOnEsc}
|
||||
show={this.state.isOpened}
|
||||
onCancel={this.close}
|
||||
title={title || __('Select.placeholder')}
|
||||
showTitle={showTitle}
|
||||
headerClassName={headerClassName}
|
||||
bodyClassName={bodyClassName}
|
||||
className={className}
|
||||
showFooter={showFooter}
|
||||
beforeConfirm={this.beforeConfirm}
|
||||
popOverContainer={popOverContainer}
|
||||
mobileUI={mobileUI}
|
||||
disabled={disabled}
|
||||
testIdBuilder={testIdBuilder?.getChild('confirm-box')}
|
||||
>
|
||||
{({popOverContainer, loading, onConfirm, bodyRef}) =>
|
||||
popOverRender?.({
|
||||
...(this.state as any),
|
||||
ref: bodyRef,
|
||||
setState: this.updateState,
|
||||
onClose: this.close,
|
||||
onChange: this.handleChange,
|
||||
onConfirm: onConfirm,
|
||||
popOverContainer,
|
||||
loading
|
||||
})!
|
||||
}
|
||||
</ConfirmBox>
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(localeable(PickerContainer));
|
||||
213
packages/amis-ui/src/components/PopOverContainer.tsx
Normal file
213
packages/amis-ui/src/components/PopOverContainer.tsx
Normal file
@@ -0,0 +1,213 @@
|
||||
import React from 'react';
|
||||
import {autobind, PopOver, Overlay, toNumber} from 'amis-core';
|
||||
import PopUp from './PopUp';
|
||||
import {findDOMNode} from 'react-dom';
|
||||
import isNumber from 'lodash/isNumber';
|
||||
|
||||
export type OverlayAlignType = 'left' | 'center' | 'right';
|
||||
|
||||
export interface PopOverOverlay {
|
||||
width?: string | number;
|
||||
align?: OverlayAlignType;
|
||||
}
|
||||
|
||||
export interface PopOverContainerProps {
|
||||
show?: boolean;
|
||||
children: (props: {
|
||||
disabled?: boolean;
|
||||
onClick: (e: React.MouseEvent) => void;
|
||||
isOpened: boolean;
|
||||
ref: any;
|
||||
}) => JSX.Element;
|
||||
disabled?: boolean;
|
||||
/** 弹出层打开时触发的事件 */
|
||||
onOpen?: () => void;
|
||||
popOverRender: (props: {onClose: () => void}) => JSX.Element;
|
||||
popOverContainer?: any;
|
||||
popOverClassName?: string;
|
||||
mobileUI?: boolean;
|
||||
placement?: string;
|
||||
overlayWidth?: number | string;
|
||||
overlayWidthField?: 'minWidth' | 'width';
|
||||
showConfirm?: boolean;
|
||||
// 相当于 placement 的简化版
|
||||
align?: OverlayAlignType;
|
||||
/** Popover层隐藏前触发的事件 */
|
||||
onBeforeHide?: () => void;
|
||||
/** Popover层隐藏后触发的事件 */
|
||||
onAfterHide?: () => void;
|
||||
onConfirm?: () => void;
|
||||
}
|
||||
|
||||
export interface PopOverContainerState {
|
||||
isOpened: boolean;
|
||||
}
|
||||
|
||||
export class PopOverContainer extends React.Component<
|
||||
PopOverContainerProps,
|
||||
PopOverContainerState
|
||||
> {
|
||||
static alignPlacementMap = {
|
||||
left: 'left-bottom-left-top',
|
||||
right: 'right-bottom-right-top',
|
||||
center: 'center-bottom-center-top'
|
||||
};
|
||||
|
||||
state: PopOverContainerState = {
|
||||
isOpened: false
|
||||
};
|
||||
|
||||
target: any;
|
||||
|
||||
@autobind
|
||||
targetRef(target: any) {
|
||||
this.target = target ? findDOMNode(target) : null;
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleClick(e?: React.MouseEvent) {
|
||||
e?.preventDefault();
|
||||
|
||||
this.props.disabled ||
|
||||
this.setState(
|
||||
{
|
||||
isOpened: true
|
||||
},
|
||||
() => {
|
||||
this.props.onOpen?.();
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@autobind
|
||||
close() {
|
||||
const {onBeforeHide, onAfterHide} = this.props;
|
||||
|
||||
if (onBeforeHide && typeof onBeforeHide === 'function') {
|
||||
onBeforeHide?.();
|
||||
}
|
||||
|
||||
this.setState({
|
||||
isOpened: false
|
||||
});
|
||||
|
||||
if (onAfterHide && typeof onAfterHide === 'function') {
|
||||
onAfterHide?.();
|
||||
}
|
||||
}
|
||||
|
||||
@autobind
|
||||
getTarget() {
|
||||
return this.target || (findDOMNode(this) as HTMLElement);
|
||||
}
|
||||
|
||||
@autobind
|
||||
getParent() {
|
||||
return this.getTarget()?.parentElement;
|
||||
}
|
||||
|
||||
@autobind
|
||||
onConfirm() {
|
||||
this.props.onConfirm?.();
|
||||
this.close();
|
||||
}
|
||||
|
||||
static calcOverlayWidth(overlay: PopOverOverlay, targetWidth: number) {
|
||||
const overlayWidth = overlay && overlay.width;
|
||||
|
||||
if (!overlayWidth || !isNumber(targetWidth) || targetWidth < 1) return;
|
||||
// 数字字符串需要转化下,否则不生效
|
||||
if (typeof overlayWidth === 'number' || /^\d+$/.test(overlayWidth)) {
|
||||
return toNumber(overlayWidth);
|
||||
}
|
||||
// 带单位,如: 80%、200px、30vw、5rem
|
||||
if (/^\d+(px|%|rem|em|vw)$/.test(overlayWidth)) {
|
||||
return overlayWidth;
|
||||
}
|
||||
// 带单位的相对值
|
||||
// 如: -100px 代表 100% - 100px。+10vw 代表 100% + 10vw
|
||||
if (/^(\+|\-)\d+(px|%|rem|em|vw)$/.test(overlayWidth)) {
|
||||
// 不能使用 calc(100% $1 $2),需要考虑到 popOverContainer
|
||||
return overlayWidth.replace(
|
||||
/^(\+|\-)(.*)/,
|
||||
`calc(${targetWidth}px $1 $2)`
|
||||
);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
static alignToPlacement(overlay?: PopOverOverlay) {
|
||||
const align = overlay && overlay.align;
|
||||
return (align && PopOverContainer.alignPlacementMap[align]) || 'auto';
|
||||
}
|
||||
|
||||
// 可以自定义下拉框宽度
|
||||
getOverlayStyle() {
|
||||
const {overlayWidth, overlayWidthField} = this.props;
|
||||
|
||||
return {
|
||||
[overlayWidthField || 'minWidth']:
|
||||
PopOverContainer.calcOverlayWidth(
|
||||
{width: overlayWidth},
|
||||
this.target?.offsetWidth
|
||||
) || (this.target ? Math.max(this.target.offsetWidth, 100) : 'auto')
|
||||
};
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
mobileUI,
|
||||
children,
|
||||
popOverContainer,
|
||||
popOverClassName,
|
||||
popOverRender: dropdownRender,
|
||||
placement,
|
||||
align,
|
||||
showConfirm,
|
||||
onConfirm,
|
||||
disabled
|
||||
} = this.props;
|
||||
|
||||
return (
|
||||
<>
|
||||
{children({
|
||||
isOpened: this.state.isOpened && this.props.show !== false,
|
||||
onClick: this.handleClick,
|
||||
ref: this.targetRef,
|
||||
disabled
|
||||
})}
|
||||
{mobileUI ? (
|
||||
<PopUp
|
||||
isShow={this.state.isOpened && this.props.show !== false}
|
||||
container={popOverContainer}
|
||||
className={popOverClassName}
|
||||
showConfirm={showConfirm}
|
||||
onHide={this.close}
|
||||
onConfirm={this.onConfirm}
|
||||
>
|
||||
{dropdownRender({onClose: this.close})}
|
||||
</PopUp>
|
||||
) : (
|
||||
<Overlay
|
||||
container={popOverContainer || this.getParent}
|
||||
target={this.getTarget}
|
||||
placement={placement || PopOverContainer.alignToPlacement({align})}
|
||||
show={this.state.isOpened && this.props.show !== false}
|
||||
>
|
||||
<PopOver
|
||||
overlay
|
||||
className={popOverClassName}
|
||||
style={this.getOverlayStyle()}
|
||||
onHide={this.close}
|
||||
>
|
||||
{dropdownRender({onClose: this.close})}
|
||||
</PopOver>
|
||||
</Overlay>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default PopOverContainer;
|
||||
174
packages/amis-ui/src/components/PopUp.tsx
Normal file
174
packages/amis-ui/src/components/PopUp.tsx
Normal file
@@ -0,0 +1,174 @@
|
||||
/**
|
||||
* @file PopUp
|
||||
* @description
|
||||
* @author fex
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import {themeable, ThemeProps} from 'amis-core';
|
||||
import {localeable, LocaleProps} from 'amis-core';
|
||||
import Transition, {
|
||||
ENTERED,
|
||||
EXITING,
|
||||
EXITED,
|
||||
ENTERING
|
||||
} from 'react-transition-group/Transition';
|
||||
import Portal from 'react-overlays/Portal';
|
||||
import {Icon} from './icons';
|
||||
import Button from './Button';
|
||||
|
||||
export interface PopUpPorps extends ThemeProps, LocaleProps {
|
||||
title?: string;
|
||||
className?: string;
|
||||
style?: {
|
||||
[styleName: string]: string;
|
||||
};
|
||||
overlay?: boolean;
|
||||
onHide?: () => void;
|
||||
isShow?: boolean;
|
||||
container?: any;
|
||||
showConfirm?: boolean;
|
||||
onConfirm?: (value: any) => void;
|
||||
showClose?: boolean;
|
||||
placement?: 'left' | 'center' | 'right';
|
||||
header?: JSX.Element;
|
||||
children?: React.ReactNode | Array<React.ReactNode>;
|
||||
onExited?: () => void;
|
||||
onEntered?: () => void;
|
||||
}
|
||||
|
||||
const fadeStyles: {
|
||||
[propName: string]: string;
|
||||
} = {
|
||||
[ENTERED]: '',
|
||||
[EXITING]: 'out',
|
||||
[EXITED]: '',
|
||||
[ENTERING]: 'in'
|
||||
};
|
||||
export class PopUp extends React.PureComponent<PopUpPorps> {
|
||||
scrollTop: number = 0;
|
||||
static defaultProps = {
|
||||
className: '',
|
||||
overlay: true,
|
||||
isShow: false,
|
||||
container: document.body,
|
||||
showClose: true,
|
||||
onConfirm: () => {}
|
||||
};
|
||||
componentDidUpdate() {
|
||||
if (this.props.isShow) {
|
||||
this.scrollTop =
|
||||
document.body.scrollTop || document.documentElement.scrollTop;
|
||||
document.body.style.overflow = 'hidden';
|
||||
} else {
|
||||
document.body.style.overflow = 'auto';
|
||||
document.body.scrollTop = this.scrollTop;
|
||||
}
|
||||
}
|
||||
componentWillUnmount() {
|
||||
document.body.style.overflow = 'auto';
|
||||
document.body.scrollTop = this.scrollTop;
|
||||
}
|
||||
handleClick(e: React.MouseEvent) {
|
||||
e.stopPropagation();
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
style,
|
||||
title,
|
||||
children,
|
||||
overlay,
|
||||
onHide,
|
||||
onConfirm,
|
||||
classPrefix: ns,
|
||||
classnames: cx,
|
||||
className,
|
||||
isShow,
|
||||
container,
|
||||
showConfirm,
|
||||
translate: __,
|
||||
showClose,
|
||||
header,
|
||||
placement = 'center',
|
||||
onEntered,
|
||||
onExited,
|
||||
...rest
|
||||
} = this.props;
|
||||
|
||||
const outerStyle: any = {
|
||||
...style
|
||||
};
|
||||
delete outerStyle.top;
|
||||
return (
|
||||
<Portal container={container}>
|
||||
<Transition
|
||||
onEntered={onEntered}
|
||||
onExit={onExited}
|
||||
mountOnEnter
|
||||
unmountOnExit
|
||||
in={isShow}
|
||||
timeout={500}
|
||||
appear
|
||||
>
|
||||
{(status: string) => {
|
||||
return (
|
||||
<div
|
||||
className={cx(`${ns}PopUp`, className, fadeStyles[status])}
|
||||
style={outerStyle}
|
||||
{...rest}
|
||||
onClick={this.handleClick}
|
||||
>
|
||||
{overlay && (
|
||||
<div className={`${ns}PopUp-overlay`} onClick={onHide} />
|
||||
)}
|
||||
<div className={cx(`${ns}PopUp-inner`)}>
|
||||
{!showConfirm && showClose ? (
|
||||
<div className={cx(`${ns}PopUp-closeWrap`)}>
|
||||
{header}
|
||||
<span className={cx(`PopUp-closeBox`)} onClick={onHide}>
|
||||
<Icon
|
||||
icon="close"
|
||||
className={cx('icon', `${ns}PopUp-close`)}
|
||||
/>
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
{showConfirm && (
|
||||
<div className={cx(`${ns}PopUp-toolbar`)}>
|
||||
<Button
|
||||
className={cx(`${ns}PopUp-cancel`)}
|
||||
level="link"
|
||||
onClick={onHide}
|
||||
>
|
||||
{__('cancel')}
|
||||
</Button>
|
||||
{title && (
|
||||
<span className={cx(`${ns}PopUp-title`)}>{title}</span>
|
||||
)}
|
||||
<Button
|
||||
className={cx(`${ns}PopUp-confirm`)}
|
||||
level="link"
|
||||
onClick={onConfirm}
|
||||
>
|
||||
{__('confirm')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
className={cx(`${ns}PopUp-content`, `justify-${placement}`)}
|
||||
>
|
||||
{isShow ? children : null}
|
||||
</div>
|
||||
<div className={cx(`PopUp-safearea`)}></div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
</Transition>
|
||||
</Portal>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(localeable(PopUp));
|
||||
220
packages/amis-ui/src/components/Progress.tsx
Normal file
220
packages/amis-ui/src/components/Progress.tsx
Normal file
@@ -0,0 +1,220 @@
|
||||
import React from 'react';
|
||||
import cx from 'classnames';
|
||||
import {Circle} from 'rc-progress';
|
||||
import {ClassNamesFn, ClassName, themeable, ThemeProps} from 'amis-core';
|
||||
|
||||
interface ColorProps {
|
||||
value: number;
|
||||
color: string;
|
||||
}
|
||||
|
||||
export interface ThresholdProps {
|
||||
value: string;
|
||||
color?: string;
|
||||
}
|
||||
|
||||
export type ColorMapType = Array<string> | Array<ColorProps> | string;
|
||||
|
||||
interface ProgressProps extends ThemeProps {
|
||||
type: 'line' | 'circle' | 'dashboard';
|
||||
showLabel: boolean;
|
||||
value: number;
|
||||
stripe?: boolean;
|
||||
animate?: boolean;
|
||||
map?: ColorMapType;
|
||||
placeholder?: string;
|
||||
format?: (value?: number) => JSX.Element;
|
||||
gapDegree?: number;
|
||||
gapPosition?: 'top' | 'bottom' | 'left' | 'right';
|
||||
strokeWidth?: number;
|
||||
progressClassName?: ClassName;
|
||||
classnames: ClassNamesFn;
|
||||
threshold: ThresholdProps | ThresholdProps[];
|
||||
showThresholdText: boolean;
|
||||
}
|
||||
export class Progress extends React.Component<ProgressProps, Object> {
|
||||
static defaultProps: Partial<ProgressProps> = {
|
||||
type: 'line',
|
||||
placeholder: '-',
|
||||
progressClassName: '',
|
||||
map: ['bg-danger', 'bg-warning', 'bg-info', 'bg-success', 'bg-success'],
|
||||
showLabel: true
|
||||
};
|
||||
|
||||
getCurrentColor() {
|
||||
const color = this.props.map;
|
||||
if (!color || !color.length) {
|
||||
return 'bg-primary';
|
||||
}
|
||||
if (typeof color === 'string') {
|
||||
return color;
|
||||
} else {
|
||||
return this.getLevelColor(color);
|
||||
}
|
||||
}
|
||||
|
||||
getLevelColor(color: Array<string> | Array<ColorProps>) {
|
||||
const value = this.props.value;
|
||||
const colorArray = this.getColorArray(color).sort(
|
||||
(a: {value: number}, b: {value: number}) => a.value - b.value
|
||||
);
|
||||
for (let i = 0; i < colorArray.length; i++) {
|
||||
if (colorArray[i].value >= value) {
|
||||
return colorArray[i].color;
|
||||
}
|
||||
}
|
||||
return colorArray[colorArray.length - 1].color;
|
||||
}
|
||||
|
||||
getColorArray(color: Array<string> | Array<ColorProps>) {
|
||||
const span = 100 / color.length;
|
||||
return color.map((item, index) => {
|
||||
if (typeof item === 'string') {
|
||||
return {
|
||||
color: item,
|
||||
value: (index + 1) * span
|
||||
};
|
||||
}
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
getLabel(prefixCls: string) {
|
||||
const {value, format, showLabel, classnames: cx} = this.props;
|
||||
if (!showLabel) {
|
||||
return null;
|
||||
}
|
||||
const textFormatter = format || (value => `${value}%`);
|
||||
const content = textFormatter(value);
|
||||
return (
|
||||
<span className={cx(`${prefixCls}-text`)} key="value">
|
||||
{content}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
className,
|
||||
style,
|
||||
progressClassName,
|
||||
type,
|
||||
value,
|
||||
placeholder,
|
||||
stripe,
|
||||
animate,
|
||||
gapDegree,
|
||||
gapPosition,
|
||||
strokeWidth,
|
||||
classnames: cx,
|
||||
threshold,
|
||||
showThresholdText
|
||||
} = this.props;
|
||||
|
||||
const isLineType = type === 'line';
|
||||
const prefixCls = isLineType ? 'Progress-line' : 'Progress-circle';
|
||||
const bgColor = this.getCurrentColor();
|
||||
const isColorClass = /bg-/.test(bgColor);
|
||||
|
||||
let viewValue: React.ReactNode;
|
||||
if (typeof value !== 'number') {
|
||||
viewValue = <span className="text-muted">{placeholder}</span>;
|
||||
} else if (type === 'line') {
|
||||
const barStyle: any = {
|
||||
width: `${value}%`
|
||||
};
|
||||
strokeWidth && (barStyle.height = strokeWidth);
|
||||
!isColorClass && (barStyle.backgroundColor = bgColor);
|
||||
let thresholdDom = null;
|
||||
if (threshold) {
|
||||
const temp = (text: string, color?: string) => (
|
||||
<div
|
||||
style={{
|
||||
left: text,
|
||||
borderColor: color || 'var(--text-color)'
|
||||
}}
|
||||
className={cx(`${prefixCls}-threshold`)}
|
||||
key={text}
|
||||
>
|
||||
{showThresholdText ? (
|
||||
<span className={cx(`${prefixCls}-threshold-text`)}>{text}</span>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
if (Array.isArray(threshold)) {
|
||||
thresholdDom = threshold.map(item => {
|
||||
const text = parseFloat(item.value) + '%';
|
||||
return temp(text, item.color);
|
||||
});
|
||||
} else {
|
||||
const text = parseFloat(threshold.value) + '%';
|
||||
thresholdDom = temp(text, threshold.color);
|
||||
}
|
||||
}
|
||||
|
||||
viewValue = [
|
||||
<div key="progress" className={cx(prefixCls, progressClassName)}>
|
||||
{thresholdDom}
|
||||
<div className={cx(`${prefixCls}-inter`)}>
|
||||
<div
|
||||
className={cx(
|
||||
`${prefixCls}-bar`,
|
||||
{[bgColor]: isColorClass},
|
||||
{[`${prefixCls}-bar--stripe`]: stripe},
|
||||
{[`${prefixCls}-bar--animate`]: animate && !stripe},
|
||||
{[`${prefixCls}-bar--stripe-animate`]: animate && stripe}
|
||||
)}
|
||||
title={`${value}%`}
|
||||
style={barStyle}
|
||||
/>
|
||||
</div>
|
||||
</div>,
|
||||
this.getLabel(prefixCls)
|
||||
];
|
||||
} else if (type === 'circle' || type === 'dashboard') {
|
||||
const circleWidth = strokeWidth || 8;
|
||||
const circleStyle = {
|
||||
width: circleWidth * 10 + 'px',
|
||||
height: circleWidth * 10 + 'px'
|
||||
};
|
||||
const gapPos = gapPosition || (type === 'dashboard' && 'bottom') || 'top';
|
||||
const getGapDegree = () => {
|
||||
if (gapDegree || gapDegree === 0) {
|
||||
return gapDegree;
|
||||
}
|
||||
if (type === 'dashboard') {
|
||||
return 75;
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
viewValue = [
|
||||
<div
|
||||
className={cx(prefixCls, progressClassName)}
|
||||
key="circle"
|
||||
style={circleStyle}
|
||||
>
|
||||
<Circle
|
||||
percent={value}
|
||||
strokeColor={!isColorClass ? bgColor : ''}
|
||||
strokeWidth={circleWidth}
|
||||
trailWidth={circleWidth}
|
||||
prefixCls={isColorClass ? bgColor : ''}
|
||||
gapDegree={getGapDegree()}
|
||||
gapPosition={gapPos}
|
||||
style={circleStyle}
|
||||
/>
|
||||
{this.getLabel(prefixCls)}
|
||||
</div>
|
||||
];
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cx('Progress', className)} style={style}>
|
||||
{viewValue}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(Progress);
|
||||
277
packages/amis-ui/src/components/PullRefresh.tsx
Normal file
277
packages/amis-ui/src/components/PullRefresh.tsx
Normal file
@@ -0,0 +1,277 @@
|
||||
/**
|
||||
* @file PullRefresh.tsx
|
||||
* @description 下拉刷新
|
||||
* @author hongyang03
|
||||
*/
|
||||
|
||||
import React, {forwardRef, useEffect} from 'react';
|
||||
import {ClassNamesFn, themeable} from 'amis-core';
|
||||
import {useOnScreen, useSetState} from '../hooks';
|
||||
import useTouch from '../hooks/use-touch';
|
||||
import {Icon} from './icons';
|
||||
import {TranslateFn} from 'amis-core';
|
||||
import {Spinner} from './Spinner';
|
||||
|
||||
export interface PullRefreshProps {
|
||||
classnames: ClassNamesFn;
|
||||
classPrefix: string;
|
||||
translate: TranslateFn;
|
||||
disabled?: boolean;
|
||||
completed?: boolean;
|
||||
direction?: 'up' | 'down';
|
||||
showIcon?: boolean;
|
||||
showText?: boolean;
|
||||
iconType?: string;
|
||||
color?: string;
|
||||
contentText?: {
|
||||
normalText?: string;
|
||||
pullingText?: string;
|
||||
loosingText?: string;
|
||||
loadingText?: string;
|
||||
successText?: string;
|
||||
completedText?: string;
|
||||
};
|
||||
normalText?: string;
|
||||
pullingText?: string;
|
||||
loosingText?: string;
|
||||
loadingText?: string;
|
||||
successText?: string;
|
||||
completedText?: string;
|
||||
onRefresh?: () => void;
|
||||
loading?: boolean;
|
||||
successDuration?: number;
|
||||
loadingDuration?: number;
|
||||
children?: React.ReactNode | Array<React.ReactNode>;
|
||||
}
|
||||
|
||||
type statusText = 'normal' | 'pulling' | 'loosing' | 'success' | 'loading';
|
||||
|
||||
export interface PullRefreshState {
|
||||
status: statusText;
|
||||
offsetY: number;
|
||||
}
|
||||
|
||||
const defaultProps: {
|
||||
successDuration: number;
|
||||
loadingDuration: number;
|
||||
direction?: 'up' | 'down';
|
||||
showIcon: boolean;
|
||||
showText: boolean;
|
||||
iconType: string;
|
||||
} = {
|
||||
successDuration: 0,
|
||||
loadingDuration: 0,
|
||||
direction: 'down',
|
||||
showIcon: true,
|
||||
showText: true,
|
||||
iconType: 'loading-outline'
|
||||
};
|
||||
|
||||
const defaultHeaderHeight = 28;
|
||||
|
||||
const PullRefresh = forwardRef<{}, PullRefreshProps>((props, ref) => {
|
||||
const {
|
||||
classnames: cx,
|
||||
translate: __,
|
||||
children,
|
||||
successDuration,
|
||||
loadingDuration,
|
||||
direction,
|
||||
completed,
|
||||
showIcon,
|
||||
showText,
|
||||
iconType,
|
||||
color,
|
||||
contentText
|
||||
} = props;
|
||||
|
||||
const refreshText = {
|
||||
normalText: contentText?.normalText ?? __('pullRefresh.normalText'),
|
||||
pullingText: contentText?.pullingText ?? __('pullRefresh.pullingText'),
|
||||
loosingText: contentText?.loosingText ?? __('pullRefresh.loosingText'),
|
||||
loadingText: contentText?.loadingText ?? __('pullRefresh.loadingText'),
|
||||
successText: contentText?.successText ?? __('pullRefresh.successText'),
|
||||
completedText: contentText?.completedText ?? __('pullRefresh.completedText')
|
||||
};
|
||||
|
||||
const touch = useTouch();
|
||||
const loadingRef = React.useRef<HTMLDivElement>(null);
|
||||
// 当占位文字在屏幕内时,需要刷新
|
||||
const needRefresh = useOnScreen(loadingRef);
|
||||
|
||||
useEffect(() => {
|
||||
if (props.loading === false) {
|
||||
loadSuccess();
|
||||
}
|
||||
}, [props.loading]);
|
||||
|
||||
const [state, updateState] = useSetState({
|
||||
status: 'normal',
|
||||
offsetY: 0
|
||||
} as PullRefreshState);
|
||||
|
||||
const isTouchable = () => {
|
||||
return (
|
||||
!completed &&
|
||||
needRefresh &&
|
||||
!props.disabled &&
|
||||
state.status !== 'loading' &&
|
||||
state.status !== 'success'
|
||||
);
|
||||
};
|
||||
|
||||
const ease = (distance: number) => {
|
||||
const pullDistance = defaultHeaderHeight;
|
||||
|
||||
if (distance > pullDistance) {
|
||||
if (distance < pullDistance * 2) {
|
||||
distance = pullDistance + (distance - pullDistance) / 2;
|
||||
} else {
|
||||
distance = pullDistance * 1.5 + (distance - pullDistance * 2) / 4;
|
||||
}
|
||||
}
|
||||
|
||||
return Math.round(distance);
|
||||
};
|
||||
|
||||
const setStatus = (distance: number, isLoading?: boolean) => {
|
||||
const pullDistance = defaultHeaderHeight;
|
||||
let status: statusText = 'normal';
|
||||
|
||||
if (isLoading) {
|
||||
status = 'loading';
|
||||
} else if (distance === 0) {
|
||||
status = 'normal';
|
||||
} else if (Math.abs(distance) < pullDistance) {
|
||||
status = 'pulling';
|
||||
} else {
|
||||
status = 'loosing';
|
||||
}
|
||||
|
||||
updateState({offsetY: distance, status});
|
||||
};
|
||||
|
||||
const loadSuccess = () => {
|
||||
if (!successDuration) {
|
||||
setStatus(0);
|
||||
return;
|
||||
}
|
||||
updateState({status: 'success'});
|
||||
|
||||
setTimeout(() => {
|
||||
setStatus(0);
|
||||
}, successDuration);
|
||||
};
|
||||
|
||||
const onTouchStart = (event: any) => {
|
||||
event.stopPropagation();
|
||||
|
||||
if (isTouchable() && state.offsetY === 0) {
|
||||
touch.start(event);
|
||||
updateState({});
|
||||
}
|
||||
};
|
||||
|
||||
const onTouchMove = (event: any) => {
|
||||
event.stopPropagation();
|
||||
|
||||
if (isTouchable()) {
|
||||
touch.move(event);
|
||||
updateState({});
|
||||
|
||||
if (touch.isVertical()) {
|
||||
if (direction === 'down' && touch.deltaY > 0) {
|
||||
setStatus(ease(touch.deltaY));
|
||||
} else if (direction === 'up' && touch.deltaY < 0) {
|
||||
setStatus(-1 * ease(-1 * touch.deltaY));
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const onTouchEnd = (event: any) => {
|
||||
event.stopPropagation();
|
||||
if (isTouchable() && state.offsetY !== 0) {
|
||||
if (state.status === 'loosing') {
|
||||
if (loadingDuration) {
|
||||
setStatus(defaultHeaderHeight, true);
|
||||
} else {
|
||||
setStatus(0);
|
||||
}
|
||||
props.onRefresh && props.onRefresh();
|
||||
} else {
|
||||
setStatus(0);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const transformStyle = {
|
||||
transform: `translate3d(0, ${state.offsetY}px, 0)`,
|
||||
// 不清楚历史原因为什么要加这个,兼容一下
|
||||
...(direction === 'down'
|
||||
? {
|
||||
touchAction: 'none'
|
||||
}
|
||||
: {})
|
||||
};
|
||||
|
||||
const getStatusText = (status: statusText) => {
|
||||
if (props.loading) {
|
||||
return refreshText.loadingText;
|
||||
}
|
||||
if (completed) {
|
||||
return refreshText.completedText;
|
||||
}
|
||||
return refreshText[`${status}Text`];
|
||||
};
|
||||
|
||||
const loadingDom = (className: string) => {
|
||||
return (
|
||||
<div
|
||||
className={className}
|
||||
ref={loadingRef}
|
||||
style={
|
||||
color
|
||||
? ({
|
||||
'--Spinner-color': color,
|
||||
'color': color
|
||||
} as React.CSSProperties)
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{showIcon && props.loading && (
|
||||
<Spinner
|
||||
show={true}
|
||||
icon={iconType}
|
||||
size="sm"
|
||||
className="PullRefresh-spinner"
|
||||
classnames={cx}
|
||||
classPrefix={props.classPrefix}
|
||||
/>
|
||||
)}
|
||||
{showText && getStatusText(state.status)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx('PullRefresh')}
|
||||
onTouchStart={onTouchStart}
|
||||
onTouchMove={onTouchMove}
|
||||
onTouchEnd={onTouchEnd}
|
||||
onTouchCancel={onTouchEnd}
|
||||
>
|
||||
<div className={cx('PullRefresh-wrap')} style={transformStyle}>
|
||||
{direction === 'down' ? loadingDom(cx('PullRefresh-header')) : null}
|
||||
{children}
|
||||
{direction === 'up' ? loadingDom(cx('PullRefresh-footer')) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
PullRefresh.defaultProps = defaultProps;
|
||||
|
||||
export default themeable(PullRefresh);
|
||||
229
packages/amis-ui/src/components/Radios.tsx
Normal file
229
packages/amis-ui/src/components/Radios.tsx
Normal file
@@ -0,0 +1,229 @@
|
||||
/**
|
||||
* @file Radios
|
||||
* @description
|
||||
* @author fex
|
||||
*
|
||||
* @param 参数说明:
|
||||
* options: [
|
||||
* {
|
||||
* label: '显示的名字',
|
||||
* value: '值',
|
||||
* disabled: false
|
||||
* }
|
||||
* ]
|
||||
*
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import {uncontrollable} from 'amis-core';
|
||||
import Checkbox from './Checkbox';
|
||||
import Button from './Button';
|
||||
import {value2array, OptionProps, Option} from './Select';
|
||||
import chunk from 'lodash/chunk';
|
||||
import {ClassNamesFn, themeable} from 'amis-core';
|
||||
import {columnsSplit} from 'amis-core';
|
||||
import {TestIdBuilder} from 'amis-core';
|
||||
import TooltipWrapper from './TooltipWrapper';
|
||||
import Icon from './icons';
|
||||
|
||||
interface RadioProps extends OptionProps {
|
||||
id?: string;
|
||||
type: string;
|
||||
optionType?: 'default' | 'button';
|
||||
value?: string;
|
||||
className?: string;
|
||||
style?: React.CSSProperties;
|
||||
inline?: boolean;
|
||||
level?: string; // 'link' | 'primary' | 'secondary' | 'info' | 'success' | 'warning' | 'danger' | 'light' | 'dark' | 'default';
|
||||
btnActiveLevel?: string;
|
||||
disabled?: boolean;
|
||||
onChange?: Function;
|
||||
columnsCount: number | number[];
|
||||
itemClassName?: string;
|
||||
labelField?: string;
|
||||
labelClassName?: string;
|
||||
classPrefix: string;
|
||||
classnames: ClassNamesFn;
|
||||
renderLabel?: (item: Option, props: RadioProps) => JSX.Element;
|
||||
testIdBuilder?: TestIdBuilder;
|
||||
}
|
||||
|
||||
const defaultLabelRender = (item: Option, props: RadioProps) => (
|
||||
<>{`${item[props.labelField || 'label']}`}</>
|
||||
);
|
||||
export class Radios extends React.Component<RadioProps, any> {
|
||||
static defaultProps = {
|
||||
type: 'radio',
|
||||
btnActiveLevel: 'primary',
|
||||
resetValue: '',
|
||||
inline: true,
|
||||
joinValues: true,
|
||||
clearable: false,
|
||||
columnsCount: 1 // 一行显示一个
|
||||
};
|
||||
|
||||
toggleOption(option: Option) {
|
||||
const {value, onChange, valueField, clearable, delimiter, options} =
|
||||
this.props;
|
||||
|
||||
let valueArray = value2array(value, {
|
||||
multiple: false,
|
||||
delimiter,
|
||||
valueField,
|
||||
options
|
||||
});
|
||||
const idx = valueArray.indexOf(option);
|
||||
|
||||
if (~idx) {
|
||||
clearable && valueArray.splice(idx, 1);
|
||||
} else {
|
||||
valueArray = [option];
|
||||
}
|
||||
|
||||
let newValue = valueArray[0];
|
||||
|
||||
onChange && onChange(newValue);
|
||||
}
|
||||
|
||||
renderGroup(option: Option, index: number, valueArray: Array<Option>) {
|
||||
const {
|
||||
classnames: cx,
|
||||
optionType,
|
||||
classPrefix: ns,
|
||||
renderLabel = defaultLabelRender
|
||||
} = this.props;
|
||||
|
||||
return (
|
||||
<div key={index} className={cx('RadiosControl-group', option.className)}>
|
||||
<label
|
||||
className={cx('RadiosControl-groupLabel', option.labelClassName)}
|
||||
>
|
||||
{renderLabel(option, this.props)}
|
||||
</label>
|
||||
|
||||
{option.children && option.children.length
|
||||
? option.children.map((option, index) =>
|
||||
this.renderItem(option, index, valueArray)
|
||||
)
|
||||
: null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
renderItem(option: Option, index: number, valueArray: Array<Option>) {
|
||||
if (option.children?.length) {
|
||||
return this.renderGroup(option, index, valueArray);
|
||||
}
|
||||
|
||||
const {
|
||||
disabled,
|
||||
inline,
|
||||
itemClassName,
|
||||
classnames: cx,
|
||||
labelClassName,
|
||||
labelField,
|
||||
optionType,
|
||||
level,
|
||||
btnActiveLevel,
|
||||
classPrefix: ns,
|
||||
testIdBuilder,
|
||||
renderLabel = defaultLabelRender
|
||||
} = this.props;
|
||||
const itemTestIdBuilder = testIdBuilder?.getChild(option.value || index);
|
||||
|
||||
// if (optionType === 'button') {
|
||||
// const active = !!~valueArray.indexOf(option);
|
||||
// return (
|
||||
// <Button
|
||||
// key={index}
|
||||
// active={active}
|
||||
// onClick={() => this.toggleOption(option)}
|
||||
// className={cx(itemClassName, option.className)}
|
||||
// disabled={disabled || option.disabled}
|
||||
// level={(active ? btnActiveLevel : '') || level}
|
||||
// >
|
||||
// <span>{renderLabel(option, this.props)}</span>
|
||||
// </Button>
|
||||
// );
|
||||
// }
|
||||
|
||||
const finalDisabled = disabled || option.disabled;
|
||||
|
||||
return (
|
||||
<Checkbox
|
||||
type="radio"
|
||||
key={index}
|
||||
onChange={() => this.toggleOption(option)}
|
||||
checked={!!~valueArray.indexOf(option)}
|
||||
className={cx(itemClassName, option.className)}
|
||||
disabled={finalDisabled}
|
||||
description={option.description}
|
||||
inline={inline}
|
||||
labelClassName={labelClassName}
|
||||
testIdBuilder={itemTestIdBuilder}
|
||||
optionType={optionType}
|
||||
>
|
||||
{renderLabel(option, this.props)}
|
||||
{option.disabledTip && finalDisabled ? (
|
||||
<TooltipWrapper
|
||||
placement="right"
|
||||
tooltip={option.disabledTip}
|
||||
trigger="hover"
|
||||
>
|
||||
<a className={cx('Select-option-disabledTip')}>
|
||||
<Icon className="icon" icon="question2" />
|
||||
</a>
|
||||
</TooltipWrapper>
|
||||
) : null}
|
||||
</Checkbox>
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
value,
|
||||
options,
|
||||
className,
|
||||
style,
|
||||
classnames: cx,
|
||||
placeholder,
|
||||
columnsCount,
|
||||
joinValues,
|
||||
extractValue,
|
||||
disabled,
|
||||
inline,
|
||||
delimiter,
|
||||
valueField
|
||||
} = this.props;
|
||||
|
||||
let valueArray = value2array(value, {
|
||||
multiple: false,
|
||||
delimiter,
|
||||
valueField,
|
||||
options
|
||||
});
|
||||
let body: Array<React.ReactNode> = [];
|
||||
|
||||
if (options) {
|
||||
body = options.map((option, key) =>
|
||||
this.renderItem(option, key, valueArray)
|
||||
);
|
||||
}
|
||||
|
||||
if (!inline) {
|
||||
body = columnsSplit(body, cx, columnsCount);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={className} style={style}>
|
||||
{body && body.length ? body : placeholder}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(
|
||||
uncontrollable(Radios, {
|
||||
value: 'onChange'
|
||||
})
|
||||
);
|
||||
680
packages/amis-ui/src/components/Range.tsx
Normal file
680
packages/amis-ui/src/components/Range.tsx
Normal file
@@ -0,0 +1,680 @@
|
||||
/**
|
||||
* @file Range
|
||||
* @description
|
||||
* @author fex
|
||||
*/
|
||||
|
||||
import range from 'lodash/range';
|
||||
import keys from 'lodash/keys';
|
||||
import isString from 'lodash/isString';
|
||||
import difference from 'lodash/difference';
|
||||
import React from 'react';
|
||||
import TooltipWrapper from './TooltipWrapper';
|
||||
import {uncontrollable} from 'amis-core';
|
||||
|
||||
import {Overlay} from 'amis-core';
|
||||
import type {ThemeProps} from 'amis-core';
|
||||
import {themeable} from 'amis-core';
|
||||
import {autobind, camel} from 'amis-core';
|
||||
import {stripNumber} from 'amis-core';
|
||||
import {safeAdd, safeSub} from 'amis-core';
|
||||
import {findDOMNode} from 'react-dom';
|
||||
import {Icon} from './icons';
|
||||
|
||||
type MarksType = {
|
||||
[index: number | string]: Record<
|
||||
number,
|
||||
React.ReactNode | {style?: React.CSSProperties; label?: string}
|
||||
>;
|
||||
};
|
||||
|
||||
interface HandleItemState {
|
||||
isDrag: boolean;
|
||||
labelActive: boolean;
|
||||
}
|
||||
|
||||
export interface MultipleValue {
|
||||
min: number;
|
||||
max: number;
|
||||
}
|
||||
export type Value = string | MultipleValue | number | [number, number];
|
||||
export type FormatValue = MultipleValue | number;
|
||||
export type TooltipPosType = 'auto' | 'top' | 'right' | 'bottom' | 'left';
|
||||
export type InputRangeRendererEvent = 'change' | 'blur' | 'focus';
|
||||
export type InputRangeRendererAction = 'clear';
|
||||
|
||||
interface HandleItemProps extends ThemeProps {
|
||||
disabled: boolean;
|
||||
value: number;
|
||||
min: number;
|
||||
max: number;
|
||||
type?: 'min' | 'max';
|
||||
onChange: (value: number, type: 'min' | 'max') => void;
|
||||
onAfterChange: () => void;
|
||||
tooltipVisible?: boolean;
|
||||
tipFormatter?: (value: Value) => boolean;
|
||||
unit?: string;
|
||||
tooltipPlacement?: string;
|
||||
}
|
||||
|
||||
interface LabelProps extends ThemeProps {
|
||||
show: boolean;
|
||||
value: number;
|
||||
tooltipVisible?: boolean;
|
||||
tipFormatter?: (value: Value) => boolean;
|
||||
unit?: string;
|
||||
placement?: string;
|
||||
activePlacement?: string;
|
||||
positionLeft?: number;
|
||||
positionTop?: number;
|
||||
}
|
||||
|
||||
// 小数或者整数
|
||||
const MARKS_REG = /^[0-9]+(\.?[0-9]+)?%$/;
|
||||
|
||||
/**
|
||||
* 滑块值 -> position.left
|
||||
* @param value 滑块值
|
||||
* @param min 最小值
|
||||
* @param max 最大值
|
||||
* @returns position.left
|
||||
*/
|
||||
const valueToOffsetLeft = (value: any, min: number, max: number) =>
|
||||
// 最多保留两位小数,且尽量取整
|
||||
Math.floor(((value - min) * 10000) / (max - min)) / 100 + '%';
|
||||
|
||||
/**
|
||||
* 滑块handle
|
||||
* 双滑块涉及两个handle,单独抽一个组件
|
||||
*/
|
||||
class HandleItem extends React.Component<HandleItemProps, HandleItemState> {
|
||||
handleRef: React.RefObject<HTMLDivElement> = React.createRef();
|
||||
constructor(props: HandleItemProps) {
|
||||
super(props);
|
||||
|
||||
this.state = {
|
||||
isDrag: false,
|
||||
labelActive: false
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* mouseDown事件
|
||||
* 防止拖动过快,全局监听 mousemove、mouseup
|
||||
*/
|
||||
@autobind
|
||||
onMouseDown() {
|
||||
this.setState({
|
||||
isDrag: true,
|
||||
labelActive: true
|
||||
});
|
||||
window.addEventListener('mousemove', this.onMouseMove);
|
||||
window.addEventListener('mouseup', this.onMouseUp);
|
||||
}
|
||||
|
||||
/**
|
||||
* mouseMove事件
|
||||
* 触发公共onchange事件
|
||||
*/
|
||||
@autobind
|
||||
onMouseMove(e: MouseEvent) {
|
||||
const {isDrag} = this.state;
|
||||
const {type = 'min'} = this.props;
|
||||
if (!isDrag) {
|
||||
return;
|
||||
}
|
||||
this.props.onChange(e.pageX, type);
|
||||
}
|
||||
|
||||
/**
|
||||
* mouseUp事件
|
||||
* 移除全局 mousemove、mouseup
|
||||
*/
|
||||
@autobind
|
||||
onMouseUp() {
|
||||
this.setState({
|
||||
isDrag: false
|
||||
});
|
||||
const {onAfterChange} = this.props;
|
||||
onAfterChange && onAfterChange();
|
||||
window.removeEventListener('mousemove', this.onMouseMove);
|
||||
window.removeEventListener('mouseup', this.onMouseUp);
|
||||
}
|
||||
|
||||
/**
|
||||
* mouseEnter事件
|
||||
* 鼠标移入 -> 展示label
|
||||
*/
|
||||
@autobind
|
||||
onMouseEnter() {
|
||||
this.setState({
|
||||
labelActive: true
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* mouseLeave事件
|
||||
* 鼠标移出 & !isDrag -> 隐藏label
|
||||
*/
|
||||
@autobind
|
||||
onMouseLeave() {
|
||||
const {isDrag} = this.state;
|
||||
if (isDrag) {
|
||||
return;
|
||||
}
|
||||
this.setState({
|
||||
labelActive: false
|
||||
});
|
||||
}
|
||||
|
||||
@autobind
|
||||
onTouchStart() {
|
||||
this.setState({
|
||||
isDrag: true,
|
||||
labelActive: true
|
||||
});
|
||||
}
|
||||
|
||||
@autobind
|
||||
onTouchMove(e: any) {
|
||||
const {isDrag} = this.state;
|
||||
const {type = 'min'} = this.props;
|
||||
if (!isDrag) {
|
||||
return;
|
||||
}
|
||||
this.props.onChange(e.touches[0].clientX, type);
|
||||
}
|
||||
|
||||
@autobind
|
||||
onTouchEnd() {
|
||||
this.setState({
|
||||
labelActive: false
|
||||
});
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
classnames: cx,
|
||||
disabled,
|
||||
value,
|
||||
min,
|
||||
max,
|
||||
tooltipVisible,
|
||||
tipFormatter,
|
||||
unit,
|
||||
tooltipPlacement = 'auto',
|
||||
mobileUI
|
||||
} = this.props;
|
||||
const {isDrag, labelActive} = this.state;
|
||||
const style = {
|
||||
left: valueToOffsetLeft(value, min, max),
|
||||
zIndex: isDrag ? 2 : 1
|
||||
};
|
||||
|
||||
return disabled ? (
|
||||
<div className={cx('InputRange-handle')} style={style}>
|
||||
<div className={cx('InputRange-handle-icon')}>
|
||||
<Icon icon="slider-handle" className="icon" />
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className={cx('InputRange-handle', {
|
||||
'is-mobile': mobileUI
|
||||
})}
|
||||
style={style}
|
||||
ref={this.handleRef}
|
||||
>
|
||||
<div
|
||||
className={cx(
|
||||
isDrag ? 'InputRange-handle-drage' : 'InputRange-handle-icon'
|
||||
)}
|
||||
onMouseDown={this.onMouseDown}
|
||||
onMouseEnter={this.onMouseEnter}
|
||||
onMouseLeave={this.onMouseLeave}
|
||||
onTouchStart={this.onTouchStart}
|
||||
onTouchMove={this.onTouchMove}
|
||||
onTouchEnd={this.onTouchEnd}
|
||||
>
|
||||
<Icon icon="slider-handle" className="icon" />
|
||||
</div>
|
||||
|
||||
<Overlay
|
||||
placement={tooltipPlacement}
|
||||
target={() => findDOMNode(this)}
|
||||
container={() => findDOMNode(this) as HTMLElement}
|
||||
rootClose={false}
|
||||
show={true}
|
||||
>
|
||||
<Label
|
||||
show={labelActive}
|
||||
classPrefix={this.props.classPrefix}
|
||||
classnames={cx}
|
||||
value={value}
|
||||
tooltipVisible={tooltipVisible}
|
||||
tipFormatter={tipFormatter}
|
||||
unit={unit}
|
||||
placement={tooltipPlacement}
|
||||
/>
|
||||
</Overlay>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 滑块标签
|
||||
*/
|
||||
class Label extends React.Component<LabelProps, any> {
|
||||
render() {
|
||||
const {
|
||||
classnames: cx,
|
||||
value,
|
||||
show,
|
||||
tooltipVisible,
|
||||
tipFormatter,
|
||||
unit = '',
|
||||
positionLeft = 0,
|
||||
positionTop = 0
|
||||
} = this.props;
|
||||
|
||||
let {placement} = this.props;
|
||||
if (placement === 'auto') {
|
||||
positionLeft >= 0 && positionTop >= 0 && (placement = 'top');
|
||||
positionLeft >= 0 && positionTop < 0 && (placement = 'bottom');
|
||||
positionLeft < 0 && positionTop >= 0 && (placement = 'left');
|
||||
positionLeft < 0 && positionTop < 0 && (placement = 'right');
|
||||
}
|
||||
|
||||
// tooltipVisible 优先级 比show高
|
||||
// tooltipVisible 为 true时,tipFormatter才生效
|
||||
const isShow =
|
||||
tooltipVisible !== undefined
|
||||
? tooltipVisible && tipFormatter
|
||||
? tipFormatter(value)
|
||||
: tooltipVisible
|
||||
: show;
|
||||
return (
|
||||
<div
|
||||
className={cx('InputRange-label', `pos-${camel(placement)}`, {
|
||||
'InputRange-label-visible': isShow
|
||||
})}
|
||||
>
|
||||
<span>{value + unit}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// @todo 丰富这个
|
||||
export interface RangeItemProps extends ThemeProps {
|
||||
[propName: string]: any;
|
||||
}
|
||||
|
||||
export class Range extends React.Component<RangeItemProps, any> {
|
||||
multipleValue: MultipleValue = {
|
||||
min: (this.props.value as MultipleValue).min,
|
||||
max: (this.props.value as MultipleValue).max
|
||||
};
|
||||
trackRef: React.RefObject<HTMLDivElement> = React.createRef();
|
||||
|
||||
/**
|
||||
* 接收组件value变换
|
||||
* value变换 -> Range.updateValue
|
||||
* @param value
|
||||
*/
|
||||
@autobind
|
||||
updateValue(value: FormatValue) {
|
||||
const {onChange} = this.props;
|
||||
onChange && onChange(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 坐标、宽高
|
||||
*/
|
||||
@autobind
|
||||
getBoundingClient(dom: Element) {
|
||||
const {x, y, width, height} = dom?.getBoundingClientRect();
|
||||
return {x, y, width, height};
|
||||
}
|
||||
|
||||
/**
|
||||
* 坐标 -> 滑块值
|
||||
* @param pageX target.target 坐标
|
||||
* @returns 滑块值
|
||||
*/
|
||||
pageXToValue(pageX: number) {
|
||||
const {x, width} = this.getBoundingClient(this.trackRef.current as Element);
|
||||
const {max, min} = this.props;
|
||||
return ((pageX - x) * (max - min)) / width + min;
|
||||
}
|
||||
|
||||
/**
|
||||
* 滑块改变事件
|
||||
* @param pageX target.pageX 坐标
|
||||
* @param type min max
|
||||
* @returns void
|
||||
*/
|
||||
@autobind
|
||||
onChange(pageX: number, type: string = 'min') {
|
||||
const {max, min, step, multiple, value: originValue} = this.props;
|
||||
const value = this.pageXToValue(pageX);
|
||||
if (value > max || value < min) {
|
||||
return;
|
||||
}
|
||||
const result = stripNumber(this.getStepValue(value, step));
|
||||
// 值相同 不更新
|
||||
if (result === originValue) {
|
||||
return;
|
||||
}
|
||||
if (multiple) {
|
||||
this.updateValue({...(originValue as MultipleValue), [type]: result});
|
||||
} else {
|
||||
this.updateValue(result);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取step为单位的value
|
||||
* @param value 拖拽后计算的value
|
||||
* @param step 步长
|
||||
* @returns step为单位的value
|
||||
*/
|
||||
getStepValue(value: number, step: number) {
|
||||
const surplus = value % step;
|
||||
let curValue = 0;
|
||||
const closeNum = value - surplus;
|
||||
// 余数 >= 步长一半 -> 向上取,value为正值的时候,使用 safeAdd,否则使用 safeSub
|
||||
// 余数 < 步长一半 -> 向下取,使用 closeNum
|
||||
if (Math.abs(surplus) >= step / 2) {
|
||||
curValue = value >= 0 ? safeAdd(closeNum, step) : safeSub(closeNum, step);
|
||||
} else {
|
||||
curValue = closeNum;
|
||||
}
|
||||
/*
|
||||
let result = 0;
|
||||
let closeNum = Math.floor(value - surplus);
|
||||
// 余数 >= 步长一半 -> 向上取
|
||||
// 余数 < 步长一半 -> 向下取
|
||||
const _value = Math.abs(surplus) >= step / 2 ? value : safeSub(value, step);
|
||||
while (result <= _value) {
|
||||
if (step < 1 || result === 0 || result === closeNum) {
|
||||
result = safeAdd(result, step);
|
||||
} else {
|
||||
result = closeNum;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
*/
|
||||
return curValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* 点击滑轨 -> 触发onchange 改变value
|
||||
* @param e event
|
||||
* @returns void
|
||||
*/
|
||||
@autobind
|
||||
onClickTrack(e: any) {
|
||||
if (!!this.props.disabled) {
|
||||
return;
|
||||
}
|
||||
const {value} = this.props;
|
||||
const _value = this.pageXToValue(e.pageX);
|
||||
const type =
|
||||
Math.abs(_value - (value as MultipleValue).min) >
|
||||
Math.abs(_value - (value as MultipleValue).max)
|
||||
? 'max'
|
||||
: 'min';
|
||||
this.onChange(e.pageX, type);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置步长
|
||||
* @returns ReactNode
|
||||
*/
|
||||
@autobind
|
||||
renderSteps() {
|
||||
const {max, min, step, showSteps, classnames: cx, parts} = this.props;
|
||||
let isShowSteps = showSteps;
|
||||
// 只要设置了 parts 就展示分隔
|
||||
if (parts > 1 || Array.isArray(parts)) {
|
||||
isShowSteps = true;
|
||||
}
|
||||
// 总区间
|
||||
const section = max - min;
|
||||
// 总区间被平均分为多少块
|
||||
const steps = parts > 1 ? parts : Math.floor(section / step);
|
||||
// 平均分 每块的长度
|
||||
const partLength = section / steps;
|
||||
// parts为数组时,以0为起点(传入的值 - min)
|
||||
const partLengthList = Array.isArray(parts)
|
||||
? parts.map(item => item - min)
|
||||
: range(steps - 1).map(item => (item + 1) * partLength);
|
||||
return (
|
||||
isShowSteps && (
|
||||
<div>
|
||||
{partLengthList.map(item => (
|
||||
<span
|
||||
key={item}
|
||||
className={cx('InputRange-track-dot')}
|
||||
style={{left: (item * 100) / (max - min) + '%'}}
|
||||
></span>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 双滑块改变最大值、最小值
|
||||
* @param pageX 拖拽后的pageX
|
||||
* @param type 'min' | 'max'
|
||||
*/
|
||||
@autobind
|
||||
onGetChangeValue(pageX: number, type: keyof MultipleValue) {
|
||||
const {max, min} = this.props;
|
||||
const value = this.pageXToValue(pageX);
|
||||
if (value > max || value < min) {
|
||||
return;
|
||||
}
|
||||
this.multipleValue[type] = stripNumber(
|
||||
this.getStepValue(value, this.props.step)
|
||||
);
|
||||
const _min = Math.min(this.multipleValue.min, this.multipleValue.max);
|
||||
const _max = Math.max(this.multipleValue.min, this.multipleValue.max);
|
||||
this.updateValue({max: _max, min: _min});
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算每个标记 position.left
|
||||
* @param value 滑块值
|
||||
* @returns
|
||||
*/
|
||||
@autobind
|
||||
getOffsetLeft(value: number | string, getNumber?: boolean) {
|
||||
const {max, min} = this.props;
|
||||
if (isString(value) && MARKS_REG.test(value)) {
|
||||
return getNumber ? parseFloat(value) : value;
|
||||
}
|
||||
value = Math.min(Math.max(+value, min), max);
|
||||
return getNumber
|
||||
? ((value - min) * 100) / (max - min)
|
||||
: ((value - min) * 100) / (max - min) + '%';
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算每个刻度标记mark 的最大宽度 max-width
|
||||
* 通过给父元素div的width赋值,从而继承
|
||||
* @param value 刻度标记key
|
||||
* @param marks 整个刻度标记对象
|
||||
* @returns 刻度标记的最大宽度 string
|
||||
*/
|
||||
@autobind
|
||||
getMarkMaxWidth(value: keyof MarksType, marks: MarksType) {
|
||||
const {max, min, mobileUI} = this.props;
|
||||
const curNum = isString(value) ? parseInt(value, 10) : value;
|
||||
// 给最大宽度赋初始值 默认最大
|
||||
let maxWidth = Math.abs(max - min);
|
||||
// 遍历刻度标记masks 寻找距离当前节点最近的刻度标记 并记录差值
|
||||
keys(marks).forEach((mKey: keyof MarksType) => {
|
||||
const mNum = isString(mKey) ? parseInt(mKey, 10) : mKey;
|
||||
if (mKey !== value && !isNaN(mNum)) {
|
||||
maxWidth = Math.min(Math.abs(curNum - mNum), maxWidth);
|
||||
}
|
||||
});
|
||||
// 差值的1/2 即为此刻度标记的最大宽度
|
||||
return mobileUI
|
||||
? Math.floor(maxWidth) + '%'
|
||||
: Math.floor(maxWidth / 2) + '%';
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
classnames: cx,
|
||||
marks,
|
||||
multiple,
|
||||
value,
|
||||
max,
|
||||
min,
|
||||
disabled,
|
||||
tooltipVisible,
|
||||
unit,
|
||||
tooltipPlacement,
|
||||
tipFormatter,
|
||||
onAfterChange,
|
||||
mobileUI
|
||||
} = this.props;
|
||||
|
||||
// trace
|
||||
const traceActiveStyle = {
|
||||
width: valueToOffsetLeft(
|
||||
multiple
|
||||
? (value as MultipleValue).max - (value as MultipleValue).min + min
|
||||
: value,
|
||||
min,
|
||||
max
|
||||
),
|
||||
left: valueToOffsetLeft(
|
||||
multiple ? (value as MultipleValue).min : min,
|
||||
min,
|
||||
max
|
||||
)
|
||||
};
|
||||
|
||||
// handle 双滑块
|
||||
const diff = difference(
|
||||
Object.values(value as MultipleValue),
|
||||
Object.values(this.multipleValue)
|
||||
);
|
||||
if (diff && !!diff.length) {
|
||||
this.multipleValue = {
|
||||
min: (value as MultipleValue).min,
|
||||
max: (value as MultipleValue).max
|
||||
};
|
||||
}
|
||||
|
||||
const sortMaks = marks
|
||||
? keys(marks).sort(
|
||||
(a: keyof MarksType, b: keyof MarksType) =>
|
||||
(this.getOffsetLeft(a, true) as number) -
|
||||
(this.getOffsetLeft(b, true) as number)
|
||||
)
|
||||
: [];
|
||||
|
||||
return (
|
||||
<div className={cx('InputRange-wrap')}>
|
||||
<div
|
||||
ref={this.trackRef}
|
||||
className={cx('InputRange-track', 'InputRange-track--background')}
|
||||
onClick={this.onClickTrack}
|
||||
>
|
||||
<div
|
||||
className={cx('InputRange-track-active')}
|
||||
style={traceActiveStyle}
|
||||
/>
|
||||
|
||||
{/* 显示步长 */}
|
||||
{this.renderSteps()}
|
||||
|
||||
{/* 滑块handle */}
|
||||
{multiple ? (
|
||||
['min', 'max'].map((type: 'min' | 'max') => (
|
||||
<HandleItem
|
||||
key={type}
|
||||
value={this.multipleValue[type]}
|
||||
type={type}
|
||||
min={min}
|
||||
max={max}
|
||||
classPrefix={this.props.classPrefix}
|
||||
classnames={cx}
|
||||
disabled={disabled}
|
||||
tooltipVisible={tooltipVisible}
|
||||
tipFormatter={tipFormatter}
|
||||
unit={unit}
|
||||
mobileUI={mobileUI}
|
||||
tooltipPlacement={tooltipPlacement}
|
||||
onAfterChange={onAfterChange}
|
||||
onChange={this.onGetChangeValue.bind(this)}
|
||||
/>
|
||||
))
|
||||
) : (
|
||||
<HandleItem
|
||||
value={+value}
|
||||
min={min}
|
||||
max={max}
|
||||
classPrefix={this.props.classPrefix}
|
||||
classnames={cx}
|
||||
disabled={disabled}
|
||||
tooltipVisible={tooltipVisible}
|
||||
tipFormatter={tipFormatter}
|
||||
unit={unit}
|
||||
mobileUI={mobileUI}
|
||||
tooltipPlacement={tooltipPlacement}
|
||||
onAfterChange={onAfterChange}
|
||||
onChange={this.onChange.bind(this)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 刻度标记 */}
|
||||
{marks && (
|
||||
<div className={cx('InputRange-marks')}>
|
||||
{sortMaks.map((key: keyof MarksType) => {
|
||||
const offsetLeft = this.getOffsetLeft(key) as string;
|
||||
const markMaxWidth = this.getMarkMaxWidth(key, marks);
|
||||
|
||||
if (MARKS_REG.test(offsetLeft)) {
|
||||
return (
|
||||
<div
|
||||
key={key}
|
||||
style={{left: offsetLeft, width: markMaxWidth}}
|
||||
>
|
||||
<TooltipWrapper
|
||||
placement={'bottom'}
|
||||
tooltip={(marks[key] as any)?.label || marks[key]}
|
||||
trigger={['hover', 'focus']}
|
||||
rootClose={false}
|
||||
>
|
||||
<span style={(marks[key] as any)?.style}>
|
||||
{(marks[key] as any)?.label || marks[key]}
|
||||
</span>
|
||||
</TooltipWrapper>
|
||||
</div>
|
||||
);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(
|
||||
uncontrollable(Range, {
|
||||
value: 'onChange'
|
||||
})
|
||||
);
|
||||
454
packages/amis-ui/src/components/Rating.tsx
Normal file
454
packages/amis-ui/src/components/Rating.tsx
Normal file
@@ -0,0 +1,454 @@
|
||||
/**
|
||||
* @file Rating
|
||||
* @description
|
||||
* @author fex
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import {ClassNamesFn, themeable} from 'amis-core';
|
||||
import {isObject} from 'amis-core';
|
||||
import {validations} from 'amis-core';
|
||||
import {Icon} from './icons';
|
||||
import {isObjectShallowModified} from 'amis-core';
|
||||
import isEmpty from 'lodash/isEmpty';
|
||||
|
||||
export type textPositionType = 'left' | 'right';
|
||||
|
||||
interface RatingProps {
|
||||
id?: string;
|
||||
key?: string | number;
|
||||
style?: React.CSSProperties;
|
||||
count: number;
|
||||
half: boolean;
|
||||
char: string | React.ReactNode;
|
||||
className?: string;
|
||||
charClassName?: string;
|
||||
textClassName?: string;
|
||||
onChange?: (value: number) => void;
|
||||
onHoverChange?: (value: number) => void;
|
||||
value: number;
|
||||
containerClass?: string;
|
||||
readOnly: boolean;
|
||||
classPrefix: string;
|
||||
disabled?: boolean;
|
||||
allowClear?: boolean;
|
||||
inactiveColor?: string;
|
||||
colors?: string | {[propName: string]: string};
|
||||
texts?: {[propName: string]: string};
|
||||
textPosition?: textPositionType;
|
||||
classnames: ClassNamesFn;
|
||||
}
|
||||
|
||||
export class Rating extends React.Component<RatingProps, any> {
|
||||
static defaultProps = {
|
||||
containerClass: 'rating',
|
||||
readOnly: false,
|
||||
half: true,
|
||||
allowClear: true,
|
||||
value: 0,
|
||||
count: 5,
|
||||
char: <Icon icon="star" className="icon" iconContent="Rating-star-icon" />,
|
||||
colors: '',
|
||||
textPosition: 'right' as textPositionType
|
||||
};
|
||||
ratingRef = React.createRef<HTMLDivElement>();
|
||||
|
||||
starsNode: Record<string, any>;
|
||||
|
||||
constructor(props: RatingProps) {
|
||||
super(props);
|
||||
|
||||
this.starsNode = {};
|
||||
|
||||
this.state = {
|
||||
value: props.value || 0,
|
||||
stars: [],
|
||||
isClear: false,
|
||||
halfStar: {
|
||||
at: Math.floor(props.value),
|
||||
hidden: props.half && props.value % 1 < 0.5
|
||||
},
|
||||
showColor: '',
|
||||
showText: null,
|
||||
hoverValue: null
|
||||
};
|
||||
|
||||
this.getRate = this.getRate.bind(this);
|
||||
this.getStars = this.getStars.bind(this);
|
||||
this.moreThanHalf = this.moreThanHalf.bind(this);
|
||||
this.mouseOver = this.mouseOver.bind(this);
|
||||
this.mouseLeave = this.mouseLeave.bind(this);
|
||||
this.handleClick = this.handleClick.bind(this);
|
||||
this.saveRef = this.saveRef.bind(this);
|
||||
this.handleStarMouseLeave = this.handleStarMouseLeave.bind(this);
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
const {value} = this.state;
|
||||
this.setState({
|
||||
stars: this.getStars(value)
|
||||
});
|
||||
|
||||
this.getShowColorAndText(value);
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps: RatingProps) {
|
||||
const props = this.props;
|
||||
|
||||
if (
|
||||
isObjectShallowModified(
|
||||
{
|
||||
value: props.value,
|
||||
count: props.count
|
||||
},
|
||||
{
|
||||
value: prevProps.value,
|
||||
count: prevProps.count
|
||||
}
|
||||
)
|
||||
) {
|
||||
this.setState(
|
||||
{
|
||||
stars: this.getStars(props.value),
|
||||
value: props.value,
|
||||
halfStar: {
|
||||
at: Math.floor(props.value),
|
||||
hidden: props.half && props.value % 1 < 0.5
|
||||
}
|
||||
},
|
||||
() => {
|
||||
this.getShowColorAndText(props.value);
|
||||
}
|
||||
);
|
||||
} else if (
|
||||
isObjectShallowModified(props.colors, prevProps.colors) ||
|
||||
isObjectShallowModified(props.texts, prevProps.texts)
|
||||
) {
|
||||
this.getShowColorAndText(props.value);
|
||||
}
|
||||
}
|
||||
|
||||
sortKeys(map: {[propName: number]: string}) {
|
||||
// 需验证 key 是否是数字,需要过滤掉非数字key,如 $$id
|
||||
return Object.keys(map)
|
||||
.filter(item => validations.isNumeric({}, item))
|
||||
.sort((a: number | string, b: number | string) => Number(a) - Number(b));
|
||||
}
|
||||
|
||||
getShowColorAndText(value: number) {
|
||||
const {colors, texts, half} = this.props;
|
||||
let tempColor = colors;
|
||||
if (this.ratingRef.current) {
|
||||
const style = getComputedStyle(this.ratingRef.current);
|
||||
let defaultColors = [];
|
||||
try {
|
||||
defaultColors = JSON.parse(
|
||||
JSON.parse(style.getPropertyValue('content'))
|
||||
);
|
||||
} catch (e) {
|
||||
console.warn(e);
|
||||
}
|
||||
const obj: any = {};
|
||||
defaultColors.forEach((item: any) => {
|
||||
obj[item.id] = item.value;
|
||||
});
|
||||
if (isEmpty(colors) && !isEmpty(obj)) {
|
||||
tempColor = obj;
|
||||
}
|
||||
}
|
||||
if (!value)
|
||||
return this.setState({
|
||||
showText: null
|
||||
});
|
||||
|
||||
// 对 value 取整
|
||||
if (half) {
|
||||
value = Math.floor(Number(value) * 2) / 2;
|
||||
} else {
|
||||
value = Math.floor(value);
|
||||
}
|
||||
|
||||
if (tempColor && typeof tempColor !== 'string') {
|
||||
const keys: string[] = this.sortKeys(tempColor);
|
||||
const showKey = keys.filter(item => Number(item) < value).length;
|
||||
|
||||
const showColor = keys[showKey] !== undefined && tempColor[keys[showKey]];
|
||||
|
||||
// 取最大 key 的颜色,避免如下情况:tempColor 只设置了 1-4,value 为 5,导致取不到颜色而无法显示
|
||||
const lastColor = keys.length && tempColor[keys[keys.length - 1]];
|
||||
|
||||
this.setState({
|
||||
showColor: showColor || lastColor || ''
|
||||
});
|
||||
} else if (tempColor && typeof tempColor === 'string') {
|
||||
this.setState({
|
||||
showColor: tempColor
|
||||
});
|
||||
}
|
||||
|
||||
if (texts && isObject(texts)) {
|
||||
const keys: string[] = this.sortKeys(texts);
|
||||
const showKey = keys.filter(item => Number(item) < value).length;
|
||||
const showText =
|
||||
keys[showKey] !== undefined &&
|
||||
texts[keys[showKey] as keyof typeof texts];
|
||||
|
||||
this.setState({
|
||||
showText: showText || ''
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
getRate() {
|
||||
let stars;
|
||||
const {value} = this.state;
|
||||
const {half} = this.props;
|
||||
if (half) {
|
||||
stars = Math.floor(value);
|
||||
} else {
|
||||
stars = Math.round(value);
|
||||
}
|
||||
return stars;
|
||||
}
|
||||
|
||||
getStars(activeCount?: number) {
|
||||
if (typeof activeCount === 'undefined') {
|
||||
activeCount = this.getRate();
|
||||
}
|
||||
let stars = [];
|
||||
const {count} = this.props;
|
||||
for (let i = 0; i < count; i++) {
|
||||
stars.push({
|
||||
active: i <= activeCount - 1
|
||||
});
|
||||
}
|
||||
return stars;
|
||||
}
|
||||
|
||||
saveRef(index: number) {
|
||||
return (node?: HTMLLIElement | null) => {
|
||||
this.starsNode[String(index)] = node;
|
||||
};
|
||||
}
|
||||
|
||||
mouseOver(event: React.ChangeEvent<any>, index: number) {
|
||||
const {isClear} = this.state;
|
||||
if (isClear) return;
|
||||
|
||||
const {readOnly, half} = this.props;
|
||||
|
||||
if (readOnly) return;
|
||||
|
||||
if (half) {
|
||||
const isAtHalf = this.moreThanHalf(event, index);
|
||||
|
||||
const tmpValue = isAtHalf ? index + 1 : index + 0.5;
|
||||
|
||||
this.getShowColorAndText(tmpValue);
|
||||
this.onHoverChange(tmpValue);
|
||||
|
||||
if (isAtHalf) index = index + 1;
|
||||
this.setState({
|
||||
halfStar: {
|
||||
at: index,
|
||||
hidden: isAtHalf
|
||||
}
|
||||
});
|
||||
} else {
|
||||
index = index + 1;
|
||||
this.onHoverChange(index);
|
||||
this.getShowColorAndText(index);
|
||||
}
|
||||
this.setState({
|
||||
stars: this.getStars(index)
|
||||
});
|
||||
}
|
||||
|
||||
onHoverChange(value: number) {
|
||||
const {onHoverChange} = this.props;
|
||||
const {hoverValue} = this.state;
|
||||
|
||||
if (!hoverValue || (hoverValue && hoverValue !== value)) {
|
||||
this.setState({
|
||||
hoverValue: value
|
||||
});
|
||||
onHoverChange && onHoverChange(value);
|
||||
}
|
||||
}
|
||||
|
||||
moreThanHalf(event: any, index: number) {
|
||||
const star = this.starsNode[index];
|
||||
const leftPos = star.getBoundingClientRect().left;
|
||||
|
||||
return event.clientX - leftPos > star.clientWidth / 2;
|
||||
}
|
||||
|
||||
mouseLeave() {
|
||||
const {value, isClear} = this.state;
|
||||
const {half, readOnly} = this.props;
|
||||
if (readOnly) return;
|
||||
if (isClear)
|
||||
return this.setState({
|
||||
isClear: false,
|
||||
hoverValue: null
|
||||
});
|
||||
|
||||
if (half) {
|
||||
this.setState({
|
||||
halfStar: {
|
||||
at: Math.floor(value),
|
||||
hidden: value % 1 === 0 // check value is decimal or not
|
||||
}
|
||||
});
|
||||
}
|
||||
this.setState({
|
||||
stars: this.getStars(),
|
||||
hoverValue: null
|
||||
});
|
||||
this.getShowColorAndText(value);
|
||||
}
|
||||
|
||||
handleStarMouseLeave(event: any, index: number) {
|
||||
const star = this.starsNode[index];
|
||||
const leftSideX = star.getBoundingClientRect().left;
|
||||
const {isClear} = this.state;
|
||||
|
||||
if (isClear) return this.setState({isClear: false});
|
||||
|
||||
// leave star from left side
|
||||
if (event.clientX <= leftSideX) {
|
||||
this.getShowColorAndText(index);
|
||||
this.setState({
|
||||
stars: this.getStars(index),
|
||||
halfStar: {
|
||||
at: index,
|
||||
hidden: true
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
handleClick(event: React.ChangeEvent<any>, index: number) {
|
||||
const {half, readOnly, onChange, allowClear} = this.props;
|
||||
if (readOnly) return;
|
||||
|
||||
let value;
|
||||
if (half) {
|
||||
const isAtHalf = this.moreThanHalf(event, index);
|
||||
if (isAtHalf) index = index + 1;
|
||||
value = isAtHalf ? index : index + 0.5;
|
||||
this.setState({
|
||||
halfStar: {
|
||||
at: index,
|
||||
hidden: isAtHalf
|
||||
}
|
||||
});
|
||||
} else {
|
||||
value = index = index + 1;
|
||||
}
|
||||
|
||||
const isClear = allowClear && value === this.state.value;
|
||||
if (isClear) value = index = 0;
|
||||
this.setState({
|
||||
value,
|
||||
stars: this.getStars(index),
|
||||
isClear
|
||||
});
|
||||
|
||||
this.getShowColorAndText(value);
|
||||
|
||||
onChange && onChange(value);
|
||||
}
|
||||
|
||||
renderStars() {
|
||||
const {halfStar, stars, showColor} = this.state;
|
||||
const {
|
||||
inactiveColor,
|
||||
char,
|
||||
half,
|
||||
disabled,
|
||||
readOnly,
|
||||
charClassName,
|
||||
classnames: cx
|
||||
} = this.props;
|
||||
|
||||
return (
|
||||
<ul onMouseLeave={this.mouseLeave}>
|
||||
{stars.map((star: any, i: number) => {
|
||||
const isThisHalf = half && !halfStar.hidden && halfStar.at === i;
|
||||
|
||||
return (
|
||||
<li
|
||||
ref={this.saveRef(i)}
|
||||
className={cx('Rating-star', charClassName, {
|
||||
'is-half': isThisHalf,
|
||||
'is-active': star.active,
|
||||
'is-disabled': readOnly || disabled
|
||||
})}
|
||||
key={i}
|
||||
style={{
|
||||
color: star.active ? showColor : inactiveColor
|
||||
}}
|
||||
onMouseOver={e => this.mouseOver(e, i)}
|
||||
onMouseMove={e => this.mouseOver(e, i)}
|
||||
onClick={e => this.handleClick(e, i)}
|
||||
onMouseLeave={e => this.handleStarMouseLeave(e, i)}
|
||||
>
|
||||
{isThisHalf && (
|
||||
<div
|
||||
className={cx('Rating-star-half')}
|
||||
style={{
|
||||
color: showColor
|
||||
}}
|
||||
>
|
||||
{char}
|
||||
</div>
|
||||
)}
|
||||
{char}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
renderText() {
|
||||
const {showText} = this.state;
|
||||
const {textClassName, textPosition, classnames: cx} = this.props;
|
||||
|
||||
if (!showText) return null;
|
||||
|
||||
return (
|
||||
<span
|
||||
className={cx('Rating-text', textClassName, {
|
||||
[`Rating-text--${textPosition === 'left' ? 'left' : 'right'}`]:
|
||||
textPosition
|
||||
})}
|
||||
>
|
||||
{showText}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {className, textPosition, classnames: cx} = this.props;
|
||||
|
||||
return (
|
||||
<div className={cx('Rating', className)} ref={this.ratingRef}>
|
||||
{textPosition === 'left' ? (
|
||||
<>
|
||||
{this.renderText()}
|
||||
{this.renderStars()}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{this.renderStars()}
|
||||
{this.renderText()}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(Rating);
|
||||
375
packages/amis-ui/src/components/ResultBox.tsx
Normal file
375
packages/amis-ui/src/components/ResultBox.tsx
Normal file
@@ -0,0 +1,375 @@
|
||||
import {TestIdBuilder, ThemeProps, themeable} from 'amis-core';
|
||||
import React from 'react';
|
||||
import omit from 'lodash/omit';
|
||||
import isInteger from 'lodash/isInteger';
|
||||
import {InputBoxProps} from './InputBox';
|
||||
import {uncontrollable} from 'amis-core';
|
||||
import {Icon} from './icons';
|
||||
import Input from './Input';
|
||||
import {autobind, ucFirst} from 'amis-core';
|
||||
import {LocaleProps, localeable} from 'amis-core';
|
||||
import isPlainObject from 'lodash/isPlainObject';
|
||||
import TooltipWrapper, {TooltipObject} from './TooltipWrapper';
|
||||
import AutoFoldedList from './AutoFoldedList';
|
||||
|
||||
export interface ResultBoxProps
|
||||
extends ThemeProps,
|
||||
LocaleProps,
|
||||
Omit<InputBoxProps, 'result' | 'prefix' | 'onChange' | 'translate'> {
|
||||
onChange?: (value: string) => void;
|
||||
onResultClick?: (e: React.MouseEvent<HTMLElement>) => void;
|
||||
result?: Array<any> | any;
|
||||
itemRender: (value: any) => JSX.Element | string;
|
||||
onResultChange?: (value: Array<any>) => void;
|
||||
onItemClick?: (item: Object) => void;
|
||||
onClear?: (e: React.MouseEvent<HTMLElement>) => void;
|
||||
allowInput?: boolean;
|
||||
inputPlaceholder: string;
|
||||
hasDropDownArrow?: boolean;
|
||||
maxTagCount?: number;
|
||||
overflowTagPopover?: TooltipObject;
|
||||
actions?: JSX.Element | JSX.Element[];
|
||||
showInvalidMatch?: boolean;
|
||||
popOverContainer?: any;
|
||||
showArrow?: boolean;
|
||||
testIdBuilder?: TestIdBuilder;
|
||||
}
|
||||
|
||||
export class ResultBox extends React.Component<ResultBoxProps> {
|
||||
static defaultProps: Pick<
|
||||
ResultBoxProps,
|
||||
| 'clearable'
|
||||
| 'placeholder'
|
||||
| 'itemRender'
|
||||
| 'inputPlaceholder'
|
||||
| 'showArrow'
|
||||
> = {
|
||||
clearable: false,
|
||||
placeholder: 'placeholder.noData',
|
||||
inputPlaceholder: 'placeholder.enter',
|
||||
showArrow: true,
|
||||
itemRender: (option: any) => (
|
||||
<span>{`${option.scopeLabel || ''}${option.label}`}</span>
|
||||
)
|
||||
};
|
||||
|
||||
state = {
|
||||
isFocused: false
|
||||
};
|
||||
|
||||
inputRef: React.RefObject<any> = React.createRef();
|
||||
|
||||
focus() {
|
||||
this.inputRef.current?.focus();
|
||||
}
|
||||
|
||||
blur() {
|
||||
this.inputRef.current?.blur();
|
||||
}
|
||||
|
||||
@autobind
|
||||
clearValue(e: React.MouseEvent<any>) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
this.props.onClear && this.props.onClear(e);
|
||||
this.props.onResultChange && this.props.onResultChange([]);
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleFocus(e: any) {
|
||||
const onFocus = this.props.onFocus;
|
||||
onFocus && onFocus(e);
|
||||
this.setState({
|
||||
isFocused: true
|
||||
});
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleBlur(e: any) {
|
||||
const onBlur = this.props.onBlur;
|
||||
onBlur && onBlur(e);
|
||||
this.setState({
|
||||
isFocused: false
|
||||
});
|
||||
}
|
||||
|
||||
@autobind
|
||||
removeItem(e: React.MouseEvent<HTMLElement>) {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
|
||||
const {result, onResultChange} = this.props;
|
||||
const index = parseInt(e.currentTarget.getAttribute('data-index')!, 10);
|
||||
const newResult = Array.isArray(result) ? result.concat() : [];
|
||||
newResult.splice(index, 1);
|
||||
onResultChange && onResultChange(newResult);
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleItemClick(e: React.MouseEvent<HTMLElement>) {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
|
||||
const {result, onItemClick} = this.props;
|
||||
const index = parseInt(e.currentTarget.getAttribute('data-index')!, 10);
|
||||
const newResult = Array.isArray(result) ? result.concat() : [];
|
||||
onItemClick && onItemClick(newResult[index] || {});
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleChange(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const {onChange} = this.props;
|
||||
|
||||
onChange?.(e.currentTarget.value);
|
||||
}
|
||||
|
||||
renderMultipleTags(tags: any[]) {
|
||||
const {
|
||||
maxTagCount,
|
||||
overflowTagPopover,
|
||||
itemRender,
|
||||
classnames: cx,
|
||||
showInvalidMatch,
|
||||
popOverContainer,
|
||||
testIdBuilder
|
||||
} = this.props;
|
||||
|
||||
if (typeof maxTagCount === 'number' && maxTagCount > 0) {
|
||||
const tooltipProps: TooltipObject = {
|
||||
offset: [0, -10],
|
||||
tooltipClassName: cx(
|
||||
'ResultBox-overflow',
|
||||
overflowTagPopover?.tooltipClassName
|
||||
),
|
||||
...omit(overflowTagPopover, ['children', 'content', 'tooltipClassName'])
|
||||
};
|
||||
|
||||
return (
|
||||
<AutoFoldedList
|
||||
tooltipClassName={cx('Select-overflow-wrapper')}
|
||||
items={tags}
|
||||
popOverContainer={popOverContainer}
|
||||
tooltipOptions={tooltipProps}
|
||||
maxVisibleCount={maxTagCount}
|
||||
renderItem={(item, index, folded) => {
|
||||
const itemTIB = testIdBuilder?.getChild(item.value || index);
|
||||
const isShowInvalid = showInvalidMatch && item?.__unmatched;
|
||||
const body = (
|
||||
<div
|
||||
className={cx('ResultBox-value', {
|
||||
'is-invalid': isShowInvalid
|
||||
})}
|
||||
onClick={this.handleItemClick}
|
||||
{...itemTIB?.getTestId()}
|
||||
>
|
||||
<span
|
||||
className={cx('ResultBox-valueLabel')}
|
||||
data-index={index}
|
||||
{...itemTIB?.getChild('click').getTestId()}
|
||||
>
|
||||
{itemRender(item)}
|
||||
</span>
|
||||
<a
|
||||
data-index={index}
|
||||
onClick={this.removeItem}
|
||||
{...itemTIB?.getChild('close').getTestId()}
|
||||
>
|
||||
<Icon icon="close" className="icon" />
|
||||
</a>
|
||||
</div>
|
||||
);
|
||||
return folded ? (
|
||||
body
|
||||
) : (
|
||||
<TooltipWrapper
|
||||
container={popOverContainer}
|
||||
placement={'top'}
|
||||
tooltip={item['label']}
|
||||
trigger={'hover'}
|
||||
key={index}
|
||||
>
|
||||
{body}
|
||||
</TooltipWrapper>
|
||||
);
|
||||
}}
|
||||
></AutoFoldedList>
|
||||
);
|
||||
}
|
||||
|
||||
return tags.map((item, index) => {
|
||||
const itemTIB = testIdBuilder?.getChild(index);
|
||||
return (
|
||||
<TooltipWrapper
|
||||
container={popOverContainer}
|
||||
placement={'top'}
|
||||
tooltip={item['label']}
|
||||
trigger={'hover'}
|
||||
key={index}
|
||||
>
|
||||
<div
|
||||
className={cx('ResultBox-value', {
|
||||
'is-invalid': showInvalidMatch && item?.__unmatched
|
||||
})}
|
||||
onClick={this.handleItemClick}
|
||||
{...itemTIB?.getTestId()}
|
||||
>
|
||||
<span
|
||||
className={cx('ResultBox-valueLabel')}
|
||||
data-index={index}
|
||||
{...itemTIB?.getChild('click').getTestId()}
|
||||
>
|
||||
{itemRender(item)}
|
||||
</span>
|
||||
<a
|
||||
data-index={index}
|
||||
onClick={this.removeItem}
|
||||
{...itemTIB?.getChild('close').getTestId()}
|
||||
>
|
||||
<Icon icon="close" className="icon" />
|
||||
</a>
|
||||
</div>
|
||||
</TooltipWrapper>
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
render() {
|
||||
/** 不需要透传给Input的属性要解构出来 */
|
||||
const {
|
||||
className,
|
||||
classnames: cx,
|
||||
classPrefix,
|
||||
clearable,
|
||||
disabled,
|
||||
hasError,
|
||||
result,
|
||||
value,
|
||||
placeholder,
|
||||
children,
|
||||
itemRender,
|
||||
allowInput,
|
||||
inputPlaceholder,
|
||||
onResultChange,
|
||||
onChange,
|
||||
onResultClick,
|
||||
translate: __,
|
||||
locale,
|
||||
onKeyPress,
|
||||
onFocus,
|
||||
onBlur,
|
||||
borderMode,
|
||||
mobileUI,
|
||||
hasDropDownArrow,
|
||||
actions,
|
||||
onClear,
|
||||
maxTagCount,
|
||||
overflowTagPopover,
|
||||
showArrow,
|
||||
popOverContainer,
|
||||
testIdBuilder,
|
||||
...rest
|
||||
} = this.props;
|
||||
const isFocused = this.state.isFocused;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx('ResultBox', className, {
|
||||
'is-focused': isFocused,
|
||||
'is-disabled': disabled,
|
||||
'is-error': hasError,
|
||||
'is-clickable': onResultClick,
|
||||
'is-clearable': clearable,
|
||||
'is-mobile': mobileUI,
|
||||
'is-group': Array.isArray(result),
|
||||
[`ResultBox--border${ucFirst(borderMode)}`]: borderMode
|
||||
})}
|
||||
onClick={onResultClick}
|
||||
tabIndex={!allowInput && !disabled && onFocus ? 0 : -1}
|
||||
onKeyPress={allowInput ? undefined : onKeyPress}
|
||||
onFocus={allowInput ? undefined : onFocus}
|
||||
onBlur={allowInput ? undefined : onBlur}
|
||||
{...testIdBuilder?.getTestId()}
|
||||
>
|
||||
<div className={cx('ResultBox-value-wrap')}>
|
||||
{Array.isArray(result) && result.length ? (
|
||||
this.renderMultipleTags(result)
|
||||
) : result && !Array.isArray(result) ? (
|
||||
<span className={cx('ResultBox-singleValue')}>
|
||||
{isPlainObject(result) ? itemRender(result) : result}
|
||||
</span>
|
||||
) : allowInput && !disabled ? null : (
|
||||
<span className={cx('ResultBox-placeholder')}>
|
||||
{__(placeholder || 'placeholder.noData')}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{allowInput && !disabled ? (
|
||||
<Input
|
||||
{...rest}
|
||||
className={cx('ResultBox-value-input')}
|
||||
onKeyPress={onKeyPress}
|
||||
ref={this.inputRef}
|
||||
value={value || ''}
|
||||
onChange={this.handleChange}
|
||||
placeholder={__(
|
||||
/** 数组模式下输入内容后将不再展示placeholder */
|
||||
Array.isArray(result)
|
||||
? result.length > 0
|
||||
? inputPlaceholder
|
||||
: placeholder
|
||||
: result
|
||||
? ''
|
||||
: placeholder
|
||||
)}
|
||||
onFocus={this.handleFocus}
|
||||
onBlur={this.handleBlur}
|
||||
testIdBuilder={testIdBuilder?.getChild('input')}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{children}
|
||||
</div>
|
||||
|
||||
<div className={cx('ResultBox-actions')}>
|
||||
{clearable &&
|
||||
!disabled &&
|
||||
(Array.isArray(result) ? result.length : result) ? (
|
||||
<a
|
||||
onClick={this.clearValue}
|
||||
className={cx('ResultBox-clear', {
|
||||
'ResultBox-clear-with-arrow': hasDropDownArrow
|
||||
})}
|
||||
{...testIdBuilder?.getChild('clear').getTestId()}
|
||||
>
|
||||
<div className={cx('ResultBox-clear-wrap')}>
|
||||
<Icon icon="input-clear" className="icon" />
|
||||
</div>
|
||||
</a>
|
||||
) : null}
|
||||
|
||||
{actions}
|
||||
|
||||
{hasDropDownArrow && !mobileUI && (
|
||||
<span className={cx('ResultBox-pc-arrow')}>
|
||||
<Icon icon="right-arrow-bold" className="icon" />
|
||||
</span>
|
||||
)}
|
||||
{!allowInput && mobileUI && showArrow ? (
|
||||
<span className={cx('ResultBox-arrow')}>
|
||||
<Icon icon="right-arrow-bold" className="icon" />
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(
|
||||
localeable(
|
||||
uncontrollable(ResultBox, {
|
||||
value: 'onChange',
|
||||
result: 'onResultChange'
|
||||
})
|
||||
)
|
||||
);
|
||||
408
packages/amis-ui/src/components/ResultList.tsx
Normal file
408
packages/amis-ui/src/components/ResultList.tsx
Normal file
@@ -0,0 +1,408 @@
|
||||
/**
|
||||
* 用来显示选择结果,垂直显示。支持移出、排序等操作。
|
||||
*/
|
||||
import React from 'react';
|
||||
import Sortable from 'sortablejs';
|
||||
import {findDOMNode} from 'react-dom';
|
||||
import cloneDeep from 'lodash/cloneDeep';
|
||||
import cx from 'classnames';
|
||||
|
||||
import {Option, Options} from './Select';
|
||||
import {ThemeProps, themeable} from 'amis-core';
|
||||
import {Icon} from './icons';
|
||||
import {autobind, guid} from 'amis-core';
|
||||
import {LocaleProps, localeable, ClassNamesFn} from 'amis-core';
|
||||
import TransferSearch from './TransferSearch';
|
||||
import VirtualList, {AutoSizer} from './virtual-list';
|
||||
|
||||
import type {TestIdBuilder} from 'amis-core';
|
||||
|
||||
export interface ResultListProps extends ThemeProps, LocaleProps {
|
||||
className?: string;
|
||||
value?: Array<Option>;
|
||||
onChange?: (value: Array<Option>, optionModified?: boolean) => void;
|
||||
sortable?: boolean;
|
||||
disabled?: boolean;
|
||||
title?: string;
|
||||
searchPlaceholder?: string;
|
||||
placeholder: string;
|
||||
itemRender: (option: Option, states: ItemRenderStates) => JSX.Element;
|
||||
itemClassName?: string;
|
||||
searchable?: boolean;
|
||||
onSearch?: Function;
|
||||
valueField?: string;
|
||||
labelField?: string;
|
||||
itemHeight?: number; // 每个选项的高度,主要用于虚拟渲染
|
||||
virtualThreshold?: number; // 数据量多大的时候开启虚拟渲染
|
||||
showInvalidMatch?: boolean;
|
||||
testIdBuilder?: TestIdBuilder;
|
||||
}
|
||||
|
||||
export interface ItemRenderStates {
|
||||
index: number;
|
||||
disabled?: boolean;
|
||||
labelField?: string;
|
||||
classnames: ClassNamesFn;
|
||||
onChange: (value: any, name: string) => void;
|
||||
}
|
||||
|
||||
interface ResultListState {
|
||||
searchResult: Options | null;
|
||||
}
|
||||
|
||||
export class ResultList extends React.Component<
|
||||
ResultListProps,
|
||||
ResultListState
|
||||
> {
|
||||
static itemRender(option: Option, states: ItemRenderStates) {
|
||||
const scopeLabel = option.scopeLabel || '';
|
||||
const label = option[states?.labelField || 'label'];
|
||||
const canScopeLabelTitle =
|
||||
typeof scopeLabel === 'string' || typeof scopeLabel === 'number';
|
||||
const canLabelTitle =
|
||||
typeof label === 'string' || typeof label === 'number';
|
||||
const title =
|
||||
canScopeLabelTitle && canLabelTitle ? `${scopeLabel}${label}` : '';
|
||||
const classnames = states.classnames;
|
||||
return (
|
||||
<span title={title} className={classnames('Selection-ellipsis-line')}>
|
||||
{scopeLabel}
|
||||
{label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
static defaultProps: Pick<
|
||||
ResultListProps,
|
||||
| 'placeholder'
|
||||
| 'itemRender'
|
||||
| 'searchPlaceholder'
|
||||
| 'virtualThreshold'
|
||||
| 'itemHeight'
|
||||
> = {
|
||||
placeholder: 'placeholder.selectData',
|
||||
itemRender: this.itemRender,
|
||||
searchPlaceholder: '',
|
||||
virtualThreshold: 100,
|
||||
itemHeight: 32
|
||||
};
|
||||
|
||||
state: ResultListState = {
|
||||
searchResult: null
|
||||
};
|
||||
|
||||
cancelSearch?: () => void;
|
||||
id = guid();
|
||||
sortable?: Sortable;
|
||||
unmounted = false;
|
||||
searchRef?: any;
|
||||
|
||||
componentDidMount() {
|
||||
this.props.sortable && this.initSortable();
|
||||
}
|
||||
|
||||
componentDidUpdate() {
|
||||
if (this.props.sortable) {
|
||||
this.sortable || this.initSortable();
|
||||
} else {
|
||||
this.desposeSortable();
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.desposeSortable();
|
||||
this.unmounted = true;
|
||||
}
|
||||
|
||||
@autobind
|
||||
domSearchRef(ref: any) {
|
||||
while (ref && ref.getWrappedInstance) {
|
||||
ref = ref.getWrappedInstance();
|
||||
}
|
||||
this.searchRef = ref;
|
||||
}
|
||||
|
||||
initSortable() {
|
||||
const ns = this.props.classPrefix;
|
||||
const dom = findDOMNode(this) as HTMLElement;
|
||||
const container = dom.querySelector(
|
||||
`.${ns}Selections-items`
|
||||
) as HTMLElement;
|
||||
|
||||
if (!container) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.sortable = new Sortable(container, {
|
||||
group: `selections-${this.id}`,
|
||||
animation: 150,
|
||||
handle: `.${ns}Selections-dragbar`,
|
||||
ghostClass: `${ns}Selections-item--dragging`,
|
||||
onEnd: (e: any) => {
|
||||
// 没有移动
|
||||
if (e.newIndex === e.oldIndex) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 换回来
|
||||
const parent = e.to as HTMLElement;
|
||||
if (e.oldIndex < parent.childNodes.length - 1) {
|
||||
parent.insertBefore(
|
||||
e.item,
|
||||
parent.childNodes[
|
||||
e.oldIndex > e.newIndex ? e.oldIndex + 1 : e.oldIndex
|
||||
]
|
||||
);
|
||||
} else {
|
||||
parent.appendChild(e.item);
|
||||
}
|
||||
|
||||
const value = this.props.value;
|
||||
if (!Array.isArray(value)) {
|
||||
return;
|
||||
}
|
||||
const newValue = value.concat();
|
||||
newValue.splice(e.newIndex, 0, newValue.splice(e.oldIndex, 1)[0]);
|
||||
this.props.onChange?.(newValue);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
desposeSortable() {
|
||||
this.sortable?.destroy();
|
||||
delete this.sortable;
|
||||
}
|
||||
|
||||
handleValueChange(index: number, value: any, name: string) {
|
||||
if (typeof name !== 'string') {
|
||||
return;
|
||||
}
|
||||
const {value: list, onChange} = this.props;
|
||||
|
||||
const result = Array.isArray(list) ? list.concat() : [];
|
||||
if (!result[index]) {
|
||||
return;
|
||||
}
|
||||
result.splice(index, 1, {
|
||||
...result[index],
|
||||
[name]: value
|
||||
});
|
||||
onChange?.(result, true);
|
||||
}
|
||||
|
||||
@autobind
|
||||
search(inputValue: string) {
|
||||
const {onSearch, value} = this.props;
|
||||
const searchResult = (value || []).filter(
|
||||
item => onSearch && onSearch(inputValue, item)
|
||||
);
|
||||
this.setState({searchResult});
|
||||
}
|
||||
|
||||
@autobind
|
||||
clearSearch() {
|
||||
this.setState({searchResult: null});
|
||||
}
|
||||
|
||||
@autobind
|
||||
clearInput() {
|
||||
if (this.props.searchable) {
|
||||
this.searchRef?.clearInput?.();
|
||||
}
|
||||
this.clearSearch();
|
||||
}
|
||||
|
||||
// 删除项
|
||||
@autobind
|
||||
handleCloseItem(e: React.MouseEvent<HTMLElement>, option: Option) {
|
||||
const {
|
||||
value,
|
||||
onChange,
|
||||
disabled,
|
||||
searchable,
|
||||
valueField = 'value'
|
||||
} = this.props;
|
||||
|
||||
if (disabled || option.disabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const {searchResult} = this.state;
|
||||
// 结果搜索
|
||||
if (searchable && searchResult) {
|
||||
// 删除普通值
|
||||
const valueArray = cloneDeep(value) || [];
|
||||
const idx = valueArray.findIndex(
|
||||
(item: Option) => item[valueField] === option[valueField]
|
||||
);
|
||||
if (idx > -1) {
|
||||
valueArray.splice(idx, 1);
|
||||
onChange && onChange(valueArray);
|
||||
}
|
||||
// 删除搜索结果
|
||||
const searchIdx = parseInt(
|
||||
e.currentTarget.getAttribute('data-index')!,
|
||||
10
|
||||
);
|
||||
if (searchIdx > -1) {
|
||||
searchResult.splice(searchIdx, 1);
|
||||
this.setState({searchResult});
|
||||
}
|
||||
}
|
||||
// 没有搜索,走旧的删除方式
|
||||
else {
|
||||
const index = parseInt(e.currentTarget.getAttribute('data-index')!, 10);
|
||||
const {value, onChange} = this.props;
|
||||
|
||||
if (!Array.isArray(value)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const newValue = value.concat();
|
||||
newValue.splice(index, 1);
|
||||
onChange?.(newValue);
|
||||
}
|
||||
}
|
||||
|
||||
renderOption(
|
||||
option: any,
|
||||
index: number,
|
||||
value: Options,
|
||||
styles: object = {}
|
||||
) {
|
||||
const {
|
||||
classnames: cx,
|
||||
itemRender,
|
||||
disabled,
|
||||
itemClassName,
|
||||
sortable,
|
||||
labelField,
|
||||
translate: __,
|
||||
showInvalidMatch,
|
||||
testIdBuilder
|
||||
} = this.props;
|
||||
const itemTIB = testIdBuilder?.getChild(`item-${option.value || index}`);
|
||||
return (
|
||||
<div
|
||||
style={styles}
|
||||
className={cx('Selections-item', itemClassName, option?.className)}
|
||||
key={index}
|
||||
>
|
||||
{sortable && !disabled && value!.length > 1 ? (
|
||||
<Icon className={cx('Selections-dragbar icon')} icon="drag-bar" />
|
||||
) : null}
|
||||
|
||||
<label
|
||||
className={cx('Selections-label', {
|
||||
'is-invalid': showInvalidMatch ? option?.__unmatched : false
|
||||
})}
|
||||
>
|
||||
{itemRender(option, {
|
||||
index,
|
||||
disabled,
|
||||
onChange: this.handleValueChange.bind(this, index),
|
||||
labelField,
|
||||
classnames: cx
|
||||
})}
|
||||
</label>
|
||||
|
||||
{!disabled ? (
|
||||
<a
|
||||
className={cx('Selections-delBtn')}
|
||||
data-index={index}
|
||||
onClick={(e: React.MouseEvent<HTMLElement>) =>
|
||||
this.handleCloseItem(e, option)
|
||||
}
|
||||
{...itemTIB?.getChild('close').getTestId()}
|
||||
>
|
||||
<Icon icon="close" className="icon" />
|
||||
</a>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
renderNormalList(value?: Options) {
|
||||
const {
|
||||
classnames: cx,
|
||||
translate: __,
|
||||
placeholder,
|
||||
virtualThreshold = 1000,
|
||||
itemHeight = 30
|
||||
} = this.props;
|
||||
|
||||
return (
|
||||
<>
|
||||
{Array.isArray(value) && value.length ? (
|
||||
<div className={cx('Selections-items')}>
|
||||
{value.length > virtualThreshold ? (
|
||||
<AutoSizer>
|
||||
{({height}: {height: number}) => (
|
||||
<VirtualList
|
||||
height={height}
|
||||
itemCount={value.length}
|
||||
itemSize={itemHeight}
|
||||
renderItem={({
|
||||
index,
|
||||
style
|
||||
}: {
|
||||
index: number;
|
||||
style?: object;
|
||||
}) => {
|
||||
const option = value[index];
|
||||
if (!option) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.renderOption(option, index, value, {
|
||||
...style,
|
||||
width: '100%'
|
||||
});
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</AutoSizer>
|
||||
) : (
|
||||
value.map((option, index) =>
|
||||
this.renderOption(option, index, value)
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className={cx('Selections-placeholder')}>{__(placeholder)}</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
classnames: cx,
|
||||
className,
|
||||
title,
|
||||
searchable,
|
||||
value,
|
||||
translate: __,
|
||||
searchPlaceholder = __('Transfer.searchKeyword')
|
||||
} = this.props;
|
||||
|
||||
const {searchResult} = this.state;
|
||||
|
||||
return (
|
||||
<div className={cx('Selections', className)}>
|
||||
{title ? <div className={cx('Selections-title')}>{title}</div> : null}
|
||||
{searchable ? (
|
||||
<TransferSearch
|
||||
ref={this.domSearchRef}
|
||||
placeholder={searchPlaceholder}
|
||||
onSearch={this.search}
|
||||
onCancelSearch={this.clearSearch}
|
||||
/>
|
||||
) : null}
|
||||
{this.renderNormalList(searchResult !== null ? searchResult : value)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(localeable(ResultList));
|
||||
272
packages/amis-ui/src/components/ResultTableList.tsx
Normal file
272
packages/amis-ui/src/components/ResultTableList.tsx
Normal file
@@ -0,0 +1,272 @@
|
||||
/**
|
||||
* 结果表格(暂时不支持结果排序)
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
|
||||
import {BaseSelection, BaseSelectionProps} from './Selection';
|
||||
import {themeable} from 'amis-core';
|
||||
import {Option, Options} from './Select';
|
||||
import {resolveVariable} from 'amis-core';
|
||||
import {localeable} from 'amis-core';
|
||||
import {autobind} from 'amis-core';
|
||||
import TransferSearch from './TransferSearch';
|
||||
|
||||
import {CloseIcon} from './icons';
|
||||
import TableSelection from './TableSelection';
|
||||
|
||||
export interface ResultTableSelectionProps extends BaseSelectionProps {
|
||||
title?: string;
|
||||
searchPlaceholder?: string;
|
||||
placeholder?: string;
|
||||
searchable?: boolean;
|
||||
onSearch?: Function;
|
||||
columns: Array<{
|
||||
name: string;
|
||||
label: string;
|
||||
[propName: string]: any;
|
||||
}>;
|
||||
cellRender: (
|
||||
column: {
|
||||
name: string;
|
||||
label: string;
|
||||
[propName: string]: any;
|
||||
},
|
||||
option: Option,
|
||||
colIndex: number,
|
||||
rowIndex: number
|
||||
) => JSX.Element;
|
||||
}
|
||||
|
||||
export interface ResultTableSelectionState {
|
||||
tableOptions: Options;
|
||||
searching: Boolean;
|
||||
searchTableOptions: Options;
|
||||
}
|
||||
|
||||
export class BaseResultTableSelection extends BaseSelection<
|
||||
ResultTableSelectionProps,
|
||||
ResultTableSelectionState
|
||||
> {
|
||||
static defaultProps = {
|
||||
...BaseSelection.defaultProps,
|
||||
cellRender: (
|
||||
column: {
|
||||
name: string;
|
||||
label: string;
|
||||
[propName: string]: any;
|
||||
},
|
||||
option: Option,
|
||||
colIndex: number,
|
||||
rowIndex: number
|
||||
) => <span>{resolveVariable(column.name, option)}</span>
|
||||
};
|
||||
|
||||
state: ResultTableSelectionState = {
|
||||
tableOptions: [],
|
||||
searching: false,
|
||||
searchTableOptions: []
|
||||
};
|
||||
|
||||
searchRef?: any;
|
||||
|
||||
static getDerivedStateFromProps(props: ResultTableSelectionProps) {
|
||||
const {options, value, option2value, valueField} = props;
|
||||
const valueArray = BaseSelection.value2array(
|
||||
value,
|
||||
options,
|
||||
option2value,
|
||||
valueField
|
||||
);
|
||||
return {
|
||||
tableOptions: valueArray
|
||||
};
|
||||
}
|
||||
|
||||
@autobind
|
||||
domSearchRef(ref: any) {
|
||||
while (ref && ref.getWrappedInstance) {
|
||||
ref = ref.getWrappedInstance();
|
||||
}
|
||||
this.searchRef = ref;
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleCloseItem(option: Option) {
|
||||
const {value, onChange, option2value, options, disabled, valueField} =
|
||||
this.props;
|
||||
|
||||
const {searching, searchTableOptions} = this.state;
|
||||
|
||||
if (disabled || option.disabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 删除普通值
|
||||
let valueArray = BaseSelection.value2array(
|
||||
value,
|
||||
options,
|
||||
option2value,
|
||||
valueField
|
||||
);
|
||||
|
||||
let idx = valueArray.indexOf(option);
|
||||
valueArray.splice(idx, 1);
|
||||
let newValue: string | Array<Option> = option2value
|
||||
? valueArray.map(item => option2value(item))
|
||||
: valueArray;
|
||||
onChange && onChange(newValue);
|
||||
|
||||
if (searching) {
|
||||
const searchArray = BaseSelection.value2array(
|
||||
searchTableOptions,
|
||||
options,
|
||||
option2value,
|
||||
valueField
|
||||
);
|
||||
const searchIdx = searchArray.indexOf(option);
|
||||
searchTableOptions.splice(searchIdx, 1);
|
||||
this.setState({searchTableOptions});
|
||||
}
|
||||
}
|
||||
|
||||
@autobind
|
||||
search(inputValue: string) {
|
||||
// 结果为空,直接清空
|
||||
if (!inputValue) {
|
||||
this.clearSearch();
|
||||
return;
|
||||
}
|
||||
|
||||
const {value, onSearch} = this.props;
|
||||
const searchOptions = ((value || []) as Options).filter(item =>
|
||||
onSearch?.(inputValue, item)
|
||||
);
|
||||
|
||||
this.setState({
|
||||
searching: true,
|
||||
searchTableOptions: searchOptions
|
||||
});
|
||||
}
|
||||
|
||||
@autobind
|
||||
clearSearch() {
|
||||
this.setState({
|
||||
searching: false,
|
||||
searchTableOptions: []
|
||||
});
|
||||
}
|
||||
|
||||
@autobind
|
||||
clearInput() {
|
||||
if (this.props.searchable) {
|
||||
this.searchRef?.clearInput?.();
|
||||
}
|
||||
this.clearSearch();
|
||||
}
|
||||
|
||||
renderTable() {
|
||||
const {
|
||||
classnames: cx,
|
||||
className,
|
||||
columns,
|
||||
cellRender,
|
||||
value,
|
||||
disabled,
|
||||
option2value,
|
||||
onChange,
|
||||
translate: __,
|
||||
placeholder,
|
||||
virtualThreshold,
|
||||
itemHeight,
|
||||
testIdBuilder
|
||||
} = this.props;
|
||||
|
||||
const {searching, tableOptions, searchTableOptions} = this.state;
|
||||
|
||||
return (
|
||||
<div className={cx('ResultTableList', className)}>
|
||||
{Array.isArray(value) && value.length ? (
|
||||
<TableSelection
|
||||
columns={columns}
|
||||
options={!searching ? tableOptions : searchTableOptions}
|
||||
value={value}
|
||||
disabled={disabled}
|
||||
option2value={option2value}
|
||||
onChange={onChange}
|
||||
multiple={false}
|
||||
resultMode={true}
|
||||
virtualThreshold={virtualThreshold}
|
||||
itemHeight={itemHeight}
|
||||
cellRender={(
|
||||
column: {
|
||||
name: string;
|
||||
label: string;
|
||||
[propName: string]: any;
|
||||
},
|
||||
option: Option,
|
||||
colIndex: number,
|
||||
rowIndex: number
|
||||
) => {
|
||||
const raw = cellRender(column, option, colIndex, rowIndex);
|
||||
const itemTIB = testIdBuilder?.getChild(
|
||||
`item-${option.value || rowIndex}`
|
||||
);
|
||||
|
||||
if (colIndex === columns.length - 1) {
|
||||
return (
|
||||
<>
|
||||
{raw}
|
||||
{
|
||||
<span
|
||||
className={cx('ResultTableList-close-btn')}
|
||||
onClick={(e: React.SyntheticEvent<HTMLElement>) => {
|
||||
e.stopPropagation();
|
||||
this.handleCloseItem(option);
|
||||
}}
|
||||
{...itemTIB?.getChild(`close`).getTestId()}
|
||||
>
|
||||
<CloseIcon />
|
||||
</span>
|
||||
}
|
||||
</>
|
||||
);
|
||||
}
|
||||
return raw;
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<div className={cx('Selections-placeholder')}>{__(placeholder)}</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
classnames: cx,
|
||||
className,
|
||||
title,
|
||||
searchable,
|
||||
translate: __,
|
||||
searchPlaceholder = __('Transfer.searchKeyword')
|
||||
} = this.props;
|
||||
|
||||
return (
|
||||
<div className={cx('Selections', className)}>
|
||||
{title ? <div className={cx('Selections-title')}>{title}</div> : null}
|
||||
{searchable ? (
|
||||
<TransferSearch
|
||||
ref={this.domSearchRef}
|
||||
placeholder={searchPlaceholder}
|
||||
onSearch={this.search}
|
||||
onCancelSearch={this.clearSearch}
|
||||
/>
|
||||
) : null}
|
||||
{this.renderTable()}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(localeable(BaseResultTableSelection));
|
||||
349
packages/amis-ui/src/components/ResultTreeList.tsx
Normal file
349
packages/amis-ui/src/components/ResultTreeList.tsx
Normal file
@@ -0,0 +1,349 @@
|
||||
/**
|
||||
* 结果树(暂时不支持结果排序)
|
||||
*/
|
||||
import React from 'react';
|
||||
import cloneDeep from 'lodash/cloneDeep';
|
||||
import isEqual from 'lodash/isEqual';
|
||||
import omit from 'lodash/omit';
|
||||
|
||||
import {Option, Options} from './Select';
|
||||
import {ThemeProps, themeable} from 'amis-core';
|
||||
import {autobind, noop} from 'amis-core';
|
||||
import {LocaleProps, localeable} from 'amis-core';
|
||||
import {BaseSelectionProps} from './Selection';
|
||||
import Tree from './Tree';
|
||||
import TransferSearch from './TransferSearch';
|
||||
import {SpinnerExtraProps} from './Spinner';
|
||||
|
||||
export interface ResultTreeListProps
|
||||
extends ThemeProps,
|
||||
LocaleProps,
|
||||
BaseSelectionProps,
|
||||
SpinnerExtraProps {
|
||||
className?: string;
|
||||
title?: string;
|
||||
searchable?: boolean;
|
||||
value: Array<Option>;
|
||||
valueField: string;
|
||||
onSearch?: Function;
|
||||
onChange: (value: Array<Option>, optionModified?: boolean) => void;
|
||||
placeholder: string;
|
||||
searchPlaceholder?: string;
|
||||
itemRender: (option: Option, states: ItemRenderStates) => JSX.Element;
|
||||
itemClassName?: string;
|
||||
cellRender?: (
|
||||
column: {
|
||||
name: string;
|
||||
label: string;
|
||||
[propName: string]: any;
|
||||
},
|
||||
option: Option,
|
||||
colIndex: number,
|
||||
rowIndex: number
|
||||
) => JSX.Element;
|
||||
}
|
||||
|
||||
export interface ItemRenderStates {
|
||||
index: number;
|
||||
disabled?: boolean;
|
||||
onChange: (value: any, name: string) => void;
|
||||
}
|
||||
|
||||
interface ResultTreeListState {
|
||||
searching: Boolean;
|
||||
treeOptions: Options;
|
||||
searchTreeOptions: Options;
|
||||
}
|
||||
|
||||
// 递归找到对应选中节点(dfs)
|
||||
function getDeep(
|
||||
node: Option,
|
||||
cb: (node: Option) => boolean,
|
||||
pathNodes: Array<Option>,
|
||||
valueField: string
|
||||
) {
|
||||
if (node[valueField] && cb(node)) {
|
||||
node.isChecked = true;
|
||||
for (let i = pathNodes.length - 2; i >= 0; i--) {
|
||||
if (!pathNodes[i].isChecked) {
|
||||
pathNodes[i].isChecked = true;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
} else if (node.children && Array.isArray(node.children)) {
|
||||
node.children.forEach(n => {
|
||||
pathNodes.push(n);
|
||||
getDeep(n, cb, pathNodes, valueField);
|
||||
pathNodes.pop();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 递归删除树多余的节点
|
||||
function deepCheckedTreeNode(nodes: Array<Option>) {
|
||||
let arr: Array<Option> = [];
|
||||
for (let i = 0; i < nodes.length; i++) {
|
||||
const node = nodes[i];
|
||||
if (node.isChecked) {
|
||||
if (node.children && Array.isArray(node.children)) {
|
||||
node.children = deepCheckedTreeNode(node.children);
|
||||
}
|
||||
arr.push(node);
|
||||
}
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
// 根据选项获取到结果
|
||||
function getResultOptions(
|
||||
value: Options = [],
|
||||
options: Options,
|
||||
valueField: string
|
||||
) {
|
||||
const newOptions = cloneDeep(options) as Array<Option>;
|
||||
const callBack = (node: Option) =>
|
||||
!!(value || []).find(target => target[valueField] === node[valueField]);
|
||||
newOptions &&
|
||||
newOptions.forEach(op => {
|
||||
getDeep(op, callBack, [op], valueField);
|
||||
});
|
||||
return deepCheckedTreeNode(newOptions);
|
||||
}
|
||||
|
||||
// 在包含回调函数情况下,遍历树
|
||||
function deepTree(nodes: Options, cb: (node: Option) => void) {
|
||||
for (let i = 0; i < nodes.length; i++) {
|
||||
const node = nodes[i];
|
||||
cb(node);
|
||||
if (node.children && Array.isArray(node.children)) {
|
||||
deepTree(node.children, cb);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 树的节点删除
|
||||
function deepDeleteTree(nodes: Options, option: Option, valueField: string) {
|
||||
let arr: Array<Option> = [];
|
||||
for (let i = 0; i < nodes.length; i++) {
|
||||
const node = nodes[i];
|
||||
if (isEqual(node, option)) {
|
||||
continue;
|
||||
}
|
||||
if (node.children && Array.isArray(node.children)) {
|
||||
node.children = deepDeleteTree(node.children, option, valueField);
|
||||
}
|
||||
if (
|
||||
(node.children && node.children.length > 0) ||
|
||||
node[valueField] !== undefined
|
||||
) {
|
||||
arr.push(node);
|
||||
}
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
export class BaseResultTreeList extends React.Component<
|
||||
ResultTreeListProps,
|
||||
ResultTreeListState
|
||||
> {
|
||||
static itemRender(option: any) {
|
||||
return <span>{`${option.scopeLabel || ''}${option.label}`}</span>;
|
||||
}
|
||||
|
||||
static defaultProps: Pick<ResultTreeListProps, 'placeholder' | 'itemRender'> =
|
||||
{
|
||||
placeholder: 'placeholder.selectData',
|
||||
itemRender: this.itemRender
|
||||
};
|
||||
|
||||
state: ResultTreeListState = {
|
||||
searching: false,
|
||||
treeOptions: [],
|
||||
searchTreeOptions: []
|
||||
};
|
||||
|
||||
searchRef?: any;
|
||||
|
||||
static getDerivedStateFromProps(props: ResultTreeListProps) {
|
||||
const newOptions = getResultOptions(
|
||||
props.value,
|
||||
props.options,
|
||||
props.valueField
|
||||
);
|
||||
return {
|
||||
treeOptions: cloneDeep(newOptions)
|
||||
};
|
||||
}
|
||||
|
||||
@autobind
|
||||
domSearchRef(ref: any) {
|
||||
while (ref && ref.getWrappedInstance) {
|
||||
ref = ref.getWrappedInstance();
|
||||
}
|
||||
this.searchRef = ref;
|
||||
}
|
||||
|
||||
// 删除非选中节点
|
||||
@autobind
|
||||
deleteTreeChecked(option: Option) {
|
||||
const {value = [], onChange, valueField} = this.props;
|
||||
const {searching, treeOptions} = this.state;
|
||||
let temNode: Options = [];
|
||||
const cb = (node: Option) => {
|
||||
// 对比时去掉 parent,因为其无限嵌套
|
||||
if (isEqual(omit(node, 'parent'), omit(option, 'parent'))) {
|
||||
temNode = [node];
|
||||
}
|
||||
};
|
||||
deepTree(treeOptions || [], cb);
|
||||
let arr: Options = [];
|
||||
const cb2 = (node: Option) => {
|
||||
if (node.isChecked && node[valueField]) {
|
||||
arr.push(node);
|
||||
}
|
||||
};
|
||||
deepTree(temNode, cb2);
|
||||
onChange &&
|
||||
onChange(
|
||||
value.filter(
|
||||
item =>
|
||||
!arr.find(arrItem =>
|
||||
// 对比时去掉 parent,因为其无限嵌套,且不相等
|
||||
isEqual(
|
||||
omit(arrItem, ['isChecked', 'childrens', 'parent']),
|
||||
omit(item, 'parent')
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
// 搜索时,重新生成树
|
||||
searching && this.deleteResultTreeNode(option);
|
||||
}
|
||||
|
||||
// 搜索树点击删除时,删除对应节点
|
||||
deleteResultTreeNode(option: Option) {
|
||||
const arr = deepDeleteTree(
|
||||
cloneDeep(this.state.searchTreeOptions) || [],
|
||||
option,
|
||||
this.props.valueField
|
||||
);
|
||||
this.setState({searchTreeOptions: arr});
|
||||
}
|
||||
|
||||
@autobind
|
||||
search(inputValue: string) {
|
||||
// 结果为空,直接清空
|
||||
if (!inputValue) {
|
||||
this.clearSearch();
|
||||
return;
|
||||
}
|
||||
|
||||
const {valueField, onSearch} = this.props;
|
||||
let temOptions: Array<Option> = this.state.treeOptions || [];
|
||||
const cb = (node: Option) => {
|
||||
node.isChecked = false;
|
||||
return true;
|
||||
};
|
||||
deepTree(temOptions, cb);
|
||||
|
||||
const callBack = (node: Option) => onSearch?.(inputValue, node);
|
||||
|
||||
temOptions &&
|
||||
temOptions.forEach(op => {
|
||||
getDeep(op, callBack, [op], valueField);
|
||||
});
|
||||
|
||||
this.setState({
|
||||
searching: true,
|
||||
searchTreeOptions: deepCheckedTreeNode(temOptions)
|
||||
});
|
||||
}
|
||||
|
||||
@autobind
|
||||
clearSearch() {
|
||||
this.setState({
|
||||
searching: false,
|
||||
searchTreeOptions: []
|
||||
});
|
||||
}
|
||||
|
||||
@autobind
|
||||
clearInput() {
|
||||
if (this.props.searchable) {
|
||||
this.searchRef?.clearInput?.();
|
||||
}
|
||||
this.clearSearch();
|
||||
}
|
||||
|
||||
renderTree() {
|
||||
const {
|
||||
className,
|
||||
classnames: cx,
|
||||
value,
|
||||
valueField,
|
||||
itemRender,
|
||||
translate: __,
|
||||
placeholder,
|
||||
virtualThreshold,
|
||||
itemHeight,
|
||||
loadingConfig,
|
||||
testIdBuilder
|
||||
} = this.props;
|
||||
|
||||
const {treeOptions, searching, searchTreeOptions} = this.state;
|
||||
|
||||
return (
|
||||
<div className={cx('ResultTreeList', className)}>
|
||||
{Array.isArray(value) && value.length ? (
|
||||
<Tree
|
||||
className={cx('Transfer-tree')}
|
||||
options={!searching ? treeOptions : searchTreeOptions}
|
||||
valueField={valueField}
|
||||
value={[]}
|
||||
onChange={noop}
|
||||
showIcon={false}
|
||||
itemRender={itemRender}
|
||||
removable
|
||||
loadingConfig={loadingConfig}
|
||||
onDelete={(option: Option) => this.deleteTreeChecked(option)}
|
||||
virtualThreshold={virtualThreshold}
|
||||
// itemHeight={itemHeight}
|
||||
testIdBuilder={testIdBuilder}
|
||||
/>
|
||||
) : (
|
||||
<div className={cx('Selections-placeholder')}>{__(placeholder)}</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
classnames: cx,
|
||||
className,
|
||||
title,
|
||||
searchable,
|
||||
translate: __,
|
||||
searchPlaceholder = __('Transfer.searchKeyword')
|
||||
} = this.props;
|
||||
|
||||
return (
|
||||
<div className={cx('Selections', className)}>
|
||||
{title ? <div className={cx('Selections-title')}>{title}</div> : null}
|
||||
{searchable ? (
|
||||
<TransferSearch
|
||||
ref={this.domSearchRef}
|
||||
placeholder={searchPlaceholder}
|
||||
onSearch={this.search}
|
||||
onCancelSearch={this.clearSearch}
|
||||
/>
|
||||
) : null}
|
||||
{this.renderTree()}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(localeable(BaseResultTreeList));
|
||||
323
packages/amis-ui/src/components/RichText.tsx
Normal file
323
packages/amis-ui/src/components/RichText.tsx
Normal file
@@ -0,0 +1,323 @@
|
||||
/**
|
||||
* @file RichText
|
||||
* @description
|
||||
* @author fex
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import isEqual from 'lodash/isEqual';
|
||||
|
||||
// @ts-ignore
|
||||
import FroalaEditor from 'froala-editor';
|
||||
// @ts-ignore
|
||||
import Froala from 'froala-editor/js/froala_editor.min.js';
|
||||
import 'froala-editor/js/plugins/align.min';
|
||||
import 'froala-editor/js/plugins/colors.min';
|
||||
import 'froala-editor/js/plugins/char_counter.min';
|
||||
import 'froala-editor/js/plugins/code_view.min';
|
||||
import 'froala-editor/js/plugins/draggable.min';
|
||||
import 'froala-editor/js/plugins/entities.min';
|
||||
import 'froala-editor/js/plugins/font_family.min';
|
||||
import 'froala-editor/js/plugins/font_size.min';
|
||||
import 'froala-editor/js/plugins/forms.min';
|
||||
import 'froala-editor/js/plugins/fullscreen.min';
|
||||
import 'froala-editor/js/plugins/help.min';
|
||||
import 'froala-editor/js/plugins/image.min';
|
||||
import 'froala-editor/js/plugins/inline_class.min';
|
||||
import 'froala-editor/js/plugins/inline_style.min';
|
||||
import 'froala-editor/js/plugins/line_breaker.min';
|
||||
import 'froala-editor/js/plugins/line_height.min';
|
||||
import 'froala-editor/js/plugins/link.min';
|
||||
import 'froala-editor/js/plugins/lists.min';
|
||||
import 'froala-editor/js/plugins/paragraph_format.min';
|
||||
import 'froala-editor/js/plugins/paragraph_style.min';
|
||||
import 'froala-editor/js/plugins/print.min';
|
||||
import 'froala-editor/js/plugins/quick_insert.min';
|
||||
import 'froala-editor/js/plugins/quote.min';
|
||||
import 'froala-editor/js/plugins/save.min';
|
||||
import 'froala-editor/js/plugins/special_characters.min';
|
||||
import 'froala-editor/js/plugins/table.min';
|
||||
import 'froala-editor/js/plugins/url.min';
|
||||
import 'froala-editor/js/plugins/video.min';
|
||||
import 'froala-editor/js/plugins/word_paste.min';
|
||||
import 'froala-editor/js/languages/zh_cn.js';
|
||||
|
||||
// Require Editor CSS files.
|
||||
// import 'froala-editor/css/froala_style.min.css';
|
||||
// import 'froala-editor/css/froala_editor.pkgd.min.css';
|
||||
|
||||
export interface FroalaEditorComponentProps {
|
||||
config: any;
|
||||
model: string;
|
||||
onModelChange: (value: string) => void;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
// 代码来源于:https://github.com/froala/react-froala-wysiwyg/blob/master/lib/FroalaEditorFunctionality.jsx
|
||||
// 改动原因是model 同步有些问题,有时候不更新,所以基于官方代码改造一下。
|
||||
// 目前发现的问题是,如果 model 数据修改,如果此时 editor 还没有初始化完成则不会同步成功
|
||||
class FroalaEditorComponent extends React.Component<FroalaEditorComponentProps> {
|
||||
listeningEvents: any;
|
||||
element: any;
|
||||
editor: any;
|
||||
config: any;
|
||||
editorInitialized: any;
|
||||
INNER_HTML_ATTR: any;
|
||||
oldModel: any;
|
||||
el: any;
|
||||
_initEvents: any;
|
||||
|
||||
constructor(props: FroalaEditorComponentProps) {
|
||||
super(props);
|
||||
|
||||
this.listeningEvents = [];
|
||||
this.element = null;
|
||||
this.editor = null;
|
||||
this.config = {
|
||||
immediateReactModelUpdate: false,
|
||||
reactIgnoreAttrs: null
|
||||
};
|
||||
|
||||
this.editorInitialized = false;
|
||||
this.INNER_HTML_ATTR = 'innerHTML';
|
||||
|
||||
this.oldModel = null;
|
||||
}
|
||||
|
||||
// After first time render.
|
||||
componentDidMount() {
|
||||
this.createEditor();
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.destroyEditor();
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps: Readonly<FroalaEditorComponentProps>) {
|
||||
if (!isEqual(this.props.config, prevProps.config)) {
|
||||
this.destroyEditor();
|
||||
this.createEditor();
|
||||
return;
|
||||
}
|
||||
|
||||
if (JSON.stringify(this.oldModel) == JSON.stringify(this.props.model)) {
|
||||
return;
|
||||
}
|
||||
this.setContent();
|
||||
}
|
||||
|
||||
// Return cloned object
|
||||
clone(item: any) {
|
||||
const me = this;
|
||||
if (!item) {
|
||||
return item;
|
||||
} // null, undefined values check
|
||||
|
||||
let types = [Number, String, Boolean],
|
||||
result: any;
|
||||
|
||||
// normalizing primitives if someone did new String('aaa'), or new Number('444');
|
||||
types.forEach(function (type) {
|
||||
if (item instanceof type) {
|
||||
result = type(item);
|
||||
}
|
||||
});
|
||||
|
||||
if (typeof result == 'undefined') {
|
||||
if (Object.prototype.toString.call(item) === '[object Array]') {
|
||||
result = [];
|
||||
item.forEach(function (child: any, index: number, array: Array<any>) {
|
||||
result[index] = me.clone(child);
|
||||
});
|
||||
} else if (typeof item == 'object') {
|
||||
// testing that this is DOM
|
||||
if (item.nodeType && typeof item.cloneNode == 'function') {
|
||||
result = item.cloneNode(true);
|
||||
} else if (!item.prototype) {
|
||||
// check that this is a literal
|
||||
if (item instanceof Date) {
|
||||
result = new Date(item);
|
||||
} else {
|
||||
// it is an object literal
|
||||
result = {};
|
||||
for (var i in item) {
|
||||
result[i] = me.clone(item[i]);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (false && item.constructor) {
|
||||
result = new item.constructor();
|
||||
} else {
|
||||
result = item;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
result = item;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
createEditor() {
|
||||
if (this.editorInitialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.config = this.clone(this.props.config || this.config);
|
||||
this.config = {...this.config};
|
||||
|
||||
this.element = this.el;
|
||||
|
||||
if (this.props.model) {
|
||||
this.element.innerHTML = this.props.model;
|
||||
}
|
||||
|
||||
this.setContent();
|
||||
|
||||
// Default initialized.
|
||||
this.registerEvent(
|
||||
'initialized',
|
||||
this.config.events && this.config.events.initialized
|
||||
);
|
||||
|
||||
// Check if events are set.
|
||||
if (!this.config.events) this.config.events = {};
|
||||
this.config.events.initialized = () => {
|
||||
this.editorInitialized = true;
|
||||
this.initListeners();
|
||||
};
|
||||
|
||||
this.editor = new FroalaEditor(this.element, this.config);
|
||||
}
|
||||
|
||||
setContent() {
|
||||
if (this.props.model || this.props.model == '') {
|
||||
this.oldModel = this.props.model;
|
||||
|
||||
if (this.editorInitialized) {
|
||||
this.setNormalTagContent();
|
||||
} else {
|
||||
if (!this._initEvents) this._initEvents = [];
|
||||
this._initEvents.push(() => this.setNormalTagContent());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setNormalTagContent() {
|
||||
let self = this;
|
||||
|
||||
self.editor.html && self.editor.html.set(self.props.model || '');
|
||||
if (self.editorInitialized && self.editor.undo) {
|
||||
//This will reset the undo stack everytime the model changes externally. Can we fix this?
|
||||
self.editor.undo.reset();
|
||||
self.editor.undo.saveStep();
|
||||
}
|
||||
}
|
||||
|
||||
destroyEditor() {
|
||||
if (this.element) {
|
||||
this.editor.destroy && this.editor.destroy();
|
||||
this.listeningEvents.length = 0;
|
||||
this.element = null;
|
||||
this.editorInitialized = false;
|
||||
this._initEvents = [];
|
||||
}
|
||||
}
|
||||
|
||||
getEditor() {
|
||||
if (this.element) {
|
||||
return this.editor;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
updateModel() {
|
||||
if (!this.props.onModelChange) {
|
||||
return;
|
||||
}
|
||||
|
||||
let modelContent = '';
|
||||
|
||||
let returnedHtml = this.editor.html.get();
|
||||
if (typeof returnedHtml === 'string') {
|
||||
modelContent = returnedHtml;
|
||||
}
|
||||
|
||||
if (this.oldModel !== modelContent) {
|
||||
this.oldModel = modelContent;
|
||||
this.props.onModelChange(modelContent);
|
||||
}
|
||||
}
|
||||
|
||||
initListeners() {
|
||||
let self = this;
|
||||
|
||||
// bind contentChange and keyup event to froalaModel
|
||||
this.editor.events.on('contentChanged', function () {
|
||||
self.updateModel();
|
||||
});
|
||||
if (this.config.immediateReactModelUpdate) {
|
||||
this.editor.events.on('keyup', function () {
|
||||
self.updateModel();
|
||||
});
|
||||
}
|
||||
|
||||
// Call init events.
|
||||
if (this._initEvents) {
|
||||
for (let i = 0; i < this._initEvents.length; i++) {
|
||||
this._initEvents[i].call(this.editor);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// register event on jquery editor element
|
||||
registerEvent(eventName: string, callback: Function) {
|
||||
if (!eventName || !callback) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (eventName == 'initialized') {
|
||||
if (!this._initEvents) this._initEvents = [];
|
||||
this._initEvents.push(callback);
|
||||
} else {
|
||||
if (!this.config.events) {
|
||||
this.config.events = {};
|
||||
}
|
||||
|
||||
this.config.events[eventName] = callback;
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<textarea ref={el => (this.el = el)}>{this.props.children}</textarea>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default class extends React.Component<any, any> {
|
||||
constructor(props: any) {
|
||||
super(props);
|
||||
Froala.VIDEO_PROVIDERS = [
|
||||
{
|
||||
test_regex: /.*/,
|
||||
url_regex: '',
|
||||
url_text: '',
|
||||
html: '<span class="fr-video fr-dvb fr-draggable" contenteditable="false" draggable="true"><video class="fr-draggable" controls="" data-msg="ok" data-status="0" src="{url}" style="width: 600px;"></video></span>'
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<FroalaEditorComponent
|
||||
config={this.props.config}
|
||||
model={this.props.model}
|
||||
onModelChange={this.props.onModelChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export {FroalaEditor};
|
||||
463
packages/amis-ui/src/components/SearchBox.tsx
Normal file
463
packages/amis-ui/src/components/SearchBox.tsx
Normal file
@@ -0,0 +1,463 @@
|
||||
import React from 'react';
|
||||
import isInteger from 'lodash/isInteger';
|
||||
import debounce from 'lodash/debounce';
|
||||
import moment from 'moment';
|
||||
import {TestIdBuilder, ThemeProps, themeable} from 'amis-core';
|
||||
import {Icon} from './icons';
|
||||
import {uncontrollable} from 'amis-core';
|
||||
import {autobind} from 'amis-core';
|
||||
import {LocaleProps, localeable} from 'amis-core';
|
||||
import chain from 'lodash/chain';
|
||||
import Input from './Input';
|
||||
import Spinner from './Spinner';
|
||||
|
||||
import {SpinnerExtraProps} from './Spinner';
|
||||
|
||||
export interface HistoryRecord {
|
||||
/** 历史记录值 */
|
||||
value: string;
|
||||
/** 历史记录生成的unix时间戳 */
|
||||
timestamp?: number;
|
||||
}
|
||||
|
||||
export interface SearchHistoryOptions {
|
||||
/** 是否开启历史记录 */
|
||||
enable: boolean;
|
||||
/** 本地存储历史记录的key */
|
||||
key?: string;
|
||||
/** 历史记录数量上限 */
|
||||
limit?: number;
|
||||
/** 历史记录下拉面板CSS类名 */
|
||||
dropdownClassName?: string;
|
||||
}
|
||||
|
||||
export interface SearchBoxProps
|
||||
extends ThemeProps,
|
||||
LocaleProps,
|
||||
SpinnerExtraProps {
|
||||
name?: string;
|
||||
disabled?: boolean;
|
||||
mini?: boolean;
|
||||
enhance?: boolean;
|
||||
clearable?: boolean;
|
||||
searchImediately?: boolean;
|
||||
onChange?: (text: string) => void;
|
||||
placeholder?: string;
|
||||
defaultValue?: string;
|
||||
value?: string;
|
||||
active?: boolean;
|
||||
defaultActive?: boolean;
|
||||
onActiveChange?: (active: boolean) => void;
|
||||
onSearch?: (value: string) => any;
|
||||
onCancel?: () => void;
|
||||
onFocus?: () => void;
|
||||
onBlur?: () => void;
|
||||
/** 历史记录配置 */
|
||||
history?: SearchHistoryOptions;
|
||||
clearAndSubmit?: boolean;
|
||||
loading?: boolean;
|
||||
testIdBuilder?: TestIdBuilder;
|
||||
}
|
||||
|
||||
export interface SearchBoxState {
|
||||
isFocused: boolean;
|
||||
isHistoryOpened: boolean;
|
||||
inputValue: string;
|
||||
historyRecords: HistoryRecord[];
|
||||
}
|
||||
|
||||
const historyDefaultOptions: Required<SearchHistoryOptions> = {
|
||||
enable: false,
|
||||
key: 'amis:search_history',
|
||||
limit: 5,
|
||||
dropdownClassName: ''
|
||||
};
|
||||
|
||||
export class SearchBox extends React.Component<SearchBoxProps, SearchBoxState> {
|
||||
inputRef: React.RefObject<HTMLInputElement> = React.createRef();
|
||||
|
||||
static defaultProps = {
|
||||
mini: true,
|
||||
enhance: false,
|
||||
clearable: false,
|
||||
searchImediately: true,
|
||||
history: historyDefaultOptions,
|
||||
clearAndSubmit: false
|
||||
};
|
||||
|
||||
state = {
|
||||
isHistoryOpened: false,
|
||||
isFocused: false,
|
||||
inputValue: this.props.value ?? '',
|
||||
historyRecords: this.getHistoryRecords()
|
||||
};
|
||||
|
||||
lazyEmitSearch = debounce(
|
||||
() => {
|
||||
const onSearch = this.props.onSearch;
|
||||
|
||||
onSearch?.(this.state.inputValue ?? '');
|
||||
},
|
||||
250,
|
||||
{
|
||||
leading: false,
|
||||
trailing: true
|
||||
}
|
||||
);
|
||||
|
||||
componentDidUpdate(prevProps: SearchBoxProps) {
|
||||
if (prevProps.value !== this.props.value) {
|
||||
this.setState({inputValue: this.props.value ?? ''});
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.lazyEmitSearch.cancel();
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleActive() {
|
||||
const {onActiveChange} = this.props;
|
||||
onActiveChange?.(true);
|
||||
this.inputRef.current?.focus();
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleCancel() {
|
||||
const {onActiveChange, onCancel, onChange} = this.props;
|
||||
|
||||
onActiveChange?.(false);
|
||||
onCancel?.();
|
||||
this.setState({inputValue: ''}, () => onChange?.(''));
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleChange(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const {searchImediately, onChange} = this.props;
|
||||
const inputValue = e.currentTarget.value;
|
||||
|
||||
this.setState({inputValue}, () => {
|
||||
onChange?.(inputValue);
|
||||
searchImediately && this.lazyEmitSearch();
|
||||
});
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleSearch() {
|
||||
const {onSearch} = this.props;
|
||||
const {inputValue} = this.state;
|
||||
const {enable} = this.getHistoryOptions();
|
||||
|
||||
if (enable) {
|
||||
this.insertHistoryRecord(inputValue);
|
||||
this.setState({isFocused: false, isHistoryOpened: false});
|
||||
}
|
||||
|
||||
onSearch?.(inputValue || '');
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleKeyDown(e: React.KeyboardEvent<any>) {
|
||||
if (e.key === 'Enter') {
|
||||
this.handleSearch();
|
||||
e.preventDefault();
|
||||
}
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleClear() {
|
||||
const {searchImediately, clearAndSubmit, onChange} = this.props;
|
||||
|
||||
this.setState({inputValue: ''}, () => {
|
||||
onChange?.('');
|
||||
|
||||
if (clearAndSubmit === true || searchImediately) {
|
||||
this.lazyEmitSearch();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleFocus() {
|
||||
const {enable} = this.getHistoryOptions();
|
||||
this.setState({isFocused: true, isHistoryOpened: enable});
|
||||
this.props.onFocus?.();
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleBlur(e: React.FocusEvent<HTMLInputElement>) {
|
||||
this.setState({isFocused: false, isHistoryOpened: false});
|
||||
this.props.onBlur?.();
|
||||
}
|
||||
|
||||
handleHistoryRecordSelect(record: HistoryRecord) {
|
||||
this.setState(
|
||||
{inputValue: record.value, isHistoryOpened: false, isFocused: false},
|
||||
() => this.handleSearch()
|
||||
);
|
||||
}
|
||||
|
||||
/** 获取历史搜索配置 */
|
||||
getHistoryOptions(): Required<SearchHistoryOptions> {
|
||||
const {history} = this.props;
|
||||
const options = {
|
||||
enable: !!history?.enable,
|
||||
key: history?.key ?? historyDefaultOptions.key,
|
||||
limit:
|
||||
history?.limit && isInteger(history?.limit) && history?.limit > 0
|
||||
? history?.limit
|
||||
: historyDefaultOptions.limit,
|
||||
dropdownClassName: history?.dropdownClassName ?? ''
|
||||
};
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
/** 获取历史记录 */
|
||||
getHistoryRecords() {
|
||||
const {key, limit} = this.getHistoryOptions();
|
||||
|
||||
try {
|
||||
const storageValues = localStorage.getItem(key);
|
||||
|
||||
return chain(storageValues ? JSON.parse(storageValues) : [])
|
||||
.uniqBy('value')
|
||||
.orderBy(['timestamp'], ['desc'])
|
||||
.slice(0, limit)
|
||||
.value();
|
||||
} catch {}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/** 清空历史记录 */
|
||||
clearHistoryRecords(): HistoryRecord[] {
|
||||
const {key} = this.getHistoryOptions();
|
||||
localStorage.removeItem(key);
|
||||
this.setState({historyRecords: []});
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/** 删除一条历史记录 */
|
||||
removeHistoryRecord(record: HistoryRecord): HistoryRecord[] {
|
||||
const {key} = this.getHistoryOptions();
|
||||
const datasource = this.getHistoryRecords();
|
||||
const recordIndex = datasource.findIndex(
|
||||
item => item.value === record.value
|
||||
);
|
||||
|
||||
if (~recordIndex) {
|
||||
datasource.splice(recordIndex, 1);
|
||||
localStorage.setItem(key, JSON.stringify(datasource));
|
||||
this.setState({historyRecords: datasource});
|
||||
}
|
||||
|
||||
return datasource;
|
||||
}
|
||||
|
||||
/** 新增一条历史记录 */
|
||||
insertHistoryRecord(value: string): HistoryRecord[] {
|
||||
const datasource = this.getHistoryRecords();
|
||||
|
||||
if (!value || datasource.find(item => item.value === value)) {
|
||||
return datasource;
|
||||
}
|
||||
|
||||
try {
|
||||
const {key, limit} = this.getHistoryOptions();
|
||||
const newDatasource = chain([
|
||||
...datasource,
|
||||
{value, timestamp: moment().unix()}
|
||||
])
|
||||
.orderBy(['timestamp'], ['desc'])
|
||||
.slice(0, limit)
|
||||
.value();
|
||||
|
||||
localStorage.setItem(key, JSON.stringify(newDatasource));
|
||||
this.setState({historyRecords: newDatasource});
|
||||
return newDatasource;
|
||||
} catch {}
|
||||
|
||||
return datasource;
|
||||
}
|
||||
|
||||
renderInput(isHistoryMode?: boolean) {
|
||||
const {
|
||||
classnames: cx,
|
||||
classPrefix,
|
||||
active,
|
||||
name,
|
||||
className,
|
||||
style,
|
||||
disabled,
|
||||
placeholder,
|
||||
mini,
|
||||
enhance,
|
||||
clearable,
|
||||
mobileUI,
|
||||
translate: __,
|
||||
loading,
|
||||
loadingConfig,
|
||||
testIdBuilder
|
||||
} = this.props;
|
||||
const {isFocused, inputValue} = this.state;
|
||||
const {enable} = this.getHistoryOptions();
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx(
|
||||
'SearchBox',
|
||||
enhance && 'SearchBox--enhance',
|
||||
!!isHistoryMode ? '' : className,
|
||||
disabled ? 'is-disabled' : '',
|
||||
isFocused ? 'is-focused' : '',
|
||||
!mini || active ? 'is-active' : '',
|
||||
{'is-history': enable},
|
||||
{'is-mobile': mobileUI}
|
||||
)}
|
||||
style={style}
|
||||
{...testIdBuilder?.getTestId()}
|
||||
>
|
||||
<Input
|
||||
name={name}
|
||||
ref={this.inputRef}
|
||||
disabled={disabled}
|
||||
placeholder={__(placeholder || 'placeholder.enter')}
|
||||
value={inputValue ?? ''}
|
||||
autoComplete="off"
|
||||
onFocus={this.handleFocus}
|
||||
onBlur={this.handleBlur}
|
||||
onChange={this.handleChange}
|
||||
onKeyDown={this.handleKeyDown}
|
||||
testIdBuilder={testIdBuilder?.getChild('input')}
|
||||
/>
|
||||
|
||||
{!mini && clearable && inputValue && !disabled ? (
|
||||
<div
|
||||
className={cx('SearchBox-clearable')}
|
||||
onClick={this.handleClear}
|
||||
{...testIdBuilder?.getChild('clear').getTestId()}
|
||||
>
|
||||
<Icon icon="input-clear" className="icon" />
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!mini ? (
|
||||
<a
|
||||
className={cx('SearchBox-searchBtn', {
|
||||
'SearchBox-searchBtn--loading': loading
|
||||
})}
|
||||
onClick={this.handleSearch}
|
||||
{...testIdBuilder?.getChild('search').getTestId()}
|
||||
>
|
||||
{loading ? (
|
||||
<Spinner
|
||||
classnames={cx}
|
||||
classPrefix={classPrefix}
|
||||
className={cx('SearchBox-spinner')}
|
||||
spinnerClassName={cx('SearchBox-spinner-icon')}
|
||||
disabled={disabled}
|
||||
size="sm"
|
||||
icon="loading-outline"
|
||||
loadingConfig={loadingConfig}
|
||||
/>
|
||||
) : (
|
||||
<Icon icon="search" className="icon" />
|
||||
)}
|
||||
</a>
|
||||
) : active ? (
|
||||
<a className={cx('SearchBox-cancelBtn')} onClick={this.handleCancel}>
|
||||
<Icon icon="close" className="icon" />
|
||||
</a>
|
||||
) : (
|
||||
<a className={cx('SearchBox-activeBtn')} onClick={this.handleActive}>
|
||||
<Icon icon="search" className="icon" />
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
renderTag(item: HistoryRecord, index: number) {
|
||||
const {classnames: cx} = this.props;
|
||||
|
||||
return (
|
||||
<span className={cx('Tag', 'SearchBox-history-tag')} key={index}>
|
||||
<span
|
||||
className={cx('SearchBox-history-tag-text')}
|
||||
onMouseDown={(e: React.MouseEvent<any>) => {
|
||||
e.preventDefault();
|
||||
this.handleHistoryRecordSelect(item);
|
||||
}}
|
||||
>
|
||||
{item.value}
|
||||
</span>
|
||||
<span
|
||||
className={cx(`SearchBox-history-tag-close`)}
|
||||
onMouseDown={(e: React.MouseEvent<any>) => {
|
||||
e.preventDefault();
|
||||
this.removeHistoryRecord(item);
|
||||
}}
|
||||
>
|
||||
<Icon icon="close" className="icon" />
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
renderHitoryMode() {
|
||||
const {classnames: cx, translate: __, className, style} = this.props;
|
||||
const {isHistoryOpened, inputValue, historyRecords} = this.state;
|
||||
const {dropdownClassName} = this.getHistoryOptions();
|
||||
const showDropdown =
|
||||
isHistoryOpened && !inputValue && historyRecords.length > 0;
|
||||
|
||||
return (
|
||||
<div
|
||||
id="searchbox-history"
|
||||
className={cx('SearchBox-history', className)}
|
||||
style={style}
|
||||
>
|
||||
{this.renderInput(true)}
|
||||
|
||||
<div
|
||||
className={cx('SearchBox-history-dropdown', dropdownClassName, {
|
||||
'is-active': showDropdown
|
||||
})}
|
||||
>
|
||||
<header>
|
||||
<h4>{__('searchHistory')}</h4>
|
||||
<a
|
||||
onMouseDown={(e: React.MouseEvent<any>) => {
|
||||
e.preventDefault();
|
||||
this.clearHistoryRecords();
|
||||
}}
|
||||
>
|
||||
{__('clear')}
|
||||
</a>
|
||||
</header>
|
||||
|
||||
<div className={cx('SearchBox-history-content')}>
|
||||
{historyRecords.map((item, index) => this.renderTag(item, index))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {enable} = this.getHistoryOptions();
|
||||
|
||||
return enable ? this.renderHitoryMode() : this.renderInput();
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(
|
||||
localeable(
|
||||
uncontrollable(SearchBox, {
|
||||
active: 'onActiveChange',
|
||||
value: 'onChange'
|
||||
})
|
||||
)
|
||||
);
|
||||
1427
packages/amis-ui/src/components/Select.tsx
Normal file
1427
packages/amis-ui/src/components/Select.tsx
Normal file
File diff suppressed because it is too large
Load Diff
531
packages/amis-ui/src/components/SelectMobile.tsx
Normal file
531
packages/amis-ui/src/components/SelectMobile.tsx
Normal file
@@ -0,0 +1,531 @@
|
||||
import React from 'react';
|
||||
import {findDOMNode} from 'react-dom';
|
||||
import Picker from './Picker';
|
||||
import PopUp from './PopUp';
|
||||
import {autobind, highlight} from 'amis-core';
|
||||
import merge from 'lodash/merge';
|
||||
// @ts-ignore
|
||||
import {matchSorter} from 'match-sorter';
|
||||
import {Option, value2array, SelectProps} from './Select';
|
||||
import VirtualList from './virtual-list';
|
||||
import Checkbox from './Checkbox';
|
||||
import Input from './Input';
|
||||
import {Icon} from './icons';
|
||||
|
||||
interface SelectState {
|
||||
isFocused: boolean;
|
||||
inputValue: string;
|
||||
itemHeight: number;
|
||||
selection: Array<Option>;
|
||||
}
|
||||
|
||||
interface Props extends SelectProps {
|
||||
isOpen: boolean;
|
||||
highlightedIndex: any;
|
||||
selectedItem: any;
|
||||
visibleItemCount?: number;
|
||||
getInputProps: (...params: any) => any;
|
||||
getItemProps: (...params: any) => any;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export default class SelectMobile extends React.Component<Props, SelectState> {
|
||||
input: HTMLInputElement;
|
||||
target: HTMLElement;
|
||||
|
||||
constructor(props: Props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
selection: value2array(props.value, props),
|
||||
isFocused: false,
|
||||
inputValue: '',
|
||||
itemHeight: 32 /** Select选项高度保持一致 */
|
||||
};
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleChange([item]: any) {
|
||||
const {onChange, multiple, simpleValue, valueField, options} = this.props;
|
||||
let {selection} = this.state;
|
||||
|
||||
// 单选是字符串
|
||||
const selectItem = options.find((option: Option) =>
|
||||
multiple
|
||||
? option[valueField] === item[valueField]
|
||||
: option[valueField] === item
|
||||
);
|
||||
if (multiple) {
|
||||
const selectionValues = selection.map(item => item[valueField]);
|
||||
selection = selection.concat();
|
||||
const idx = selectionValues.indexOf(selectItem?.[valueField]);
|
||||
if (~idx) {
|
||||
selection.splice(idx, 1);
|
||||
} else {
|
||||
selectItem && selection.push(selectItem);
|
||||
}
|
||||
this.setState({
|
||||
selection
|
||||
});
|
||||
} else {
|
||||
this.setState({
|
||||
selection: selectItem ? [selectItem] : []
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleInputChange(evt: React.ChangeEvent<HTMLInputElement>) {
|
||||
const {loadOptions} = this.props;
|
||||
this.setState(
|
||||
{
|
||||
inputValue: evt.currentTarget.value
|
||||
},
|
||||
() => loadOptions && loadOptions(this.state.inputValue)
|
||||
);
|
||||
}
|
||||
|
||||
@autobind
|
||||
getTarget() {
|
||||
if (!this.target) {
|
||||
this.target = findDOMNode(this) as HTMLElement;
|
||||
}
|
||||
return this.target as HTMLElement;
|
||||
}
|
||||
|
||||
@autobind
|
||||
inputRef(ref: HTMLInputElement) {
|
||||
this.input = ref;
|
||||
}
|
||||
|
||||
@autobind
|
||||
toggleCheckAll() {
|
||||
const {
|
||||
options,
|
||||
onChange,
|
||||
simpleValue,
|
||||
checkAllBySearch,
|
||||
labelField,
|
||||
valueField
|
||||
} = this.props;
|
||||
const inputValue = this.state.inputValue;
|
||||
let {selection} = this.state;
|
||||
let filtedOptions: Array<Option> =
|
||||
inputValue && checkAllBySearch !== false
|
||||
? matchSorter(options, inputValue, {
|
||||
keys: [labelField || 'label', valueField || 'value'],
|
||||
threshold: matchSorter.rankings.CONTAINS
|
||||
})
|
||||
: options.concat();
|
||||
const optionsValues = filtedOptions.map(option => option.value);
|
||||
const selectionValues = selection.map(select => select.value);
|
||||
const checkedAll = optionsValues.every(
|
||||
option => selectionValues.indexOf(option) > -1
|
||||
);
|
||||
|
||||
selection = checkedAll ? [] : filtedOptions;
|
||||
|
||||
this.setState({selection});
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleAddClick() {
|
||||
const {onAdd} = this.props;
|
||||
onAdd && onAdd();
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleEditClick(e: Event, item: any) {
|
||||
const {onEdit} = this.props;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
onEdit && onEdit(item);
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleDeleteClick(e: Event, item: any) {
|
||||
const {onDelete} = this.props;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
onDelete && onDelete(item);
|
||||
}
|
||||
|
||||
@autobind
|
||||
onFocus(e: any) {
|
||||
const {simpleValue} = this.props;
|
||||
const {selection} = this.state;
|
||||
const value = simpleValue ? selection.map(item => item.value) : selection;
|
||||
|
||||
this.props.disabled ||
|
||||
this.props.isOpen ||
|
||||
this.setState(
|
||||
{
|
||||
isFocused: true
|
||||
},
|
||||
this.focus
|
||||
);
|
||||
|
||||
this.props.onFocus &&
|
||||
this.props.onFocus({
|
||||
...e,
|
||||
value
|
||||
});
|
||||
}
|
||||
|
||||
@autobind
|
||||
onBlur(e: any) {
|
||||
const {simpleValue} = this.props;
|
||||
const {selection} = this.state;
|
||||
const value = simpleValue ? selection.map(item => item.value) : selection;
|
||||
|
||||
this.setState({
|
||||
isFocused: false
|
||||
});
|
||||
|
||||
this.props.onBlur &&
|
||||
this.props.onBlur({
|
||||
...e,
|
||||
value
|
||||
});
|
||||
}
|
||||
|
||||
@autobind
|
||||
focus() {
|
||||
this.input
|
||||
? this.input.focus()
|
||||
: this.getTarget() && this.getTarget().focus();
|
||||
}
|
||||
|
||||
blur() {
|
||||
this.input
|
||||
? this.input.blur()
|
||||
: this.getTarget() && this.getTarget().blur();
|
||||
}
|
||||
|
||||
@autobind
|
||||
clearSearchValue() {
|
||||
const {loadOptions} = this.props;
|
||||
this.setState(
|
||||
{
|
||||
inputValue: ''
|
||||
},
|
||||
() => loadOptions?.('')
|
||||
);
|
||||
}
|
||||
|
||||
@autobind
|
||||
onConfirm() {
|
||||
const {selection} = this.state;
|
||||
const {
|
||||
multiple,
|
||||
onChange,
|
||||
simpleValue,
|
||||
valueField,
|
||||
options,
|
||||
loadOptions,
|
||||
labelField
|
||||
} = this.props;
|
||||
if (multiple) {
|
||||
onChange(
|
||||
simpleValue ? selection.map(item => item[valueField]) : selection
|
||||
);
|
||||
} else {
|
||||
const inputValue = this.state.inputValue;
|
||||
let filtedOptions: Array<Option> = (
|
||||
inputValue && !loadOptions
|
||||
? matchSorter(options, inputValue, {
|
||||
keys: [labelField || 'label', valueField || 'value'],
|
||||
threshold: matchSorter.rankings.CONTAINS
|
||||
})
|
||||
: options.concat()
|
||||
).filter((option: Option) => !option.hidden && option.visible !== false);
|
||||
// picker 打开未滑动时选中第一项
|
||||
if (!selection.length && filtedOptions.length) {
|
||||
onChange(
|
||||
simpleValue ? filtedOptions[0]?.[valueField] : filtedOptions[0]
|
||||
);
|
||||
} else {
|
||||
onChange(simpleValue ? selection[0]?.[valueField] : selection[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
popOverContainer,
|
||||
options,
|
||||
valueField,
|
||||
labelField,
|
||||
noResultsText,
|
||||
loadOptions,
|
||||
multiple,
|
||||
valuesNoWrap,
|
||||
classnames: cx,
|
||||
checkAll,
|
||||
checkAllLabel,
|
||||
checkAllBySearch,
|
||||
searchable,
|
||||
disabled,
|
||||
searchPromptText,
|
||||
visibleItemCount,
|
||||
translate: __,
|
||||
hideSelected,
|
||||
renderMenu,
|
||||
virtualThreshold = 100,
|
||||
isOpen,
|
||||
onClose,
|
||||
getInputProps,
|
||||
getItemProps,
|
||||
selectedItem
|
||||
} = this.props;
|
||||
|
||||
const {selection} = this.state;
|
||||
|
||||
const inputValue = this.state.inputValue;
|
||||
let checkedAll = false;
|
||||
let checkedPartial = false;
|
||||
let filtedOptions: Array<Option> = (
|
||||
inputValue && isOpen && !loadOptions
|
||||
? matchSorter(options, inputValue, {
|
||||
keys: [labelField || 'label', valueField || 'value'],
|
||||
threshold: matchSorter.rankings.CONTAINS
|
||||
})
|
||||
: options.concat()
|
||||
).filter(
|
||||
(option: Option) =>
|
||||
!option.hidden &&
|
||||
option.visible !== false &&
|
||||
option[labelField || 'label']
|
||||
);
|
||||
const enableVirtualRender =
|
||||
filtedOptions.length && filtedOptions.length > virtualThreshold;
|
||||
const selectionValues = selection.map(select => select[valueField]);
|
||||
if (multiple && checkAll) {
|
||||
const optionsValues = (
|
||||
checkAllBySearch !== false ? filtedOptions : options
|
||||
).map(option => option[valueField]);
|
||||
|
||||
checkedAll = optionsValues.every(
|
||||
option => selectionValues.indexOf(option) > -1
|
||||
);
|
||||
checkedPartial = optionsValues.some(
|
||||
option => selectionValues.indexOf(option) > -1
|
||||
);
|
||||
}
|
||||
|
||||
// 用于虚拟渲染的每项高度
|
||||
const virtualItemHeight = this.props.itemHeight || this.state.itemHeight;
|
||||
|
||||
// 渲染单个选项
|
||||
const renderItem = ({index, style}: {index: number; style?: object}) => {
|
||||
const item = filtedOptions[index];
|
||||
if (!item) {
|
||||
return null;
|
||||
}
|
||||
const checked =
|
||||
selectedItem === item || !!~selectionValues.indexOf(item[valueField]);
|
||||
|
||||
if (hideSelected && checked) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<div
|
||||
{...getItemProps({
|
||||
key:
|
||||
typeof item.value === 'string'
|
||||
? `${item.label}-${item.value}`
|
||||
: index,
|
||||
index,
|
||||
item,
|
||||
disabled: item.disabled
|
||||
})}
|
||||
style={merge(style, enableVirtualRender ? {width: '100%'} : {})}
|
||||
className={cx(`Select-option`, {
|
||||
'is-disabled': item.disabled,
|
||||
'is-active': checked,
|
||||
'is-mobile': true
|
||||
})}
|
||||
>
|
||||
{renderMenu ? (
|
||||
multiple ? (
|
||||
<>
|
||||
<div
|
||||
title={item[labelField]}
|
||||
className={cx('Select-option-item-check')}
|
||||
onClick={() => !item.disabled && this.handleChange([item])}
|
||||
>
|
||||
{renderMenu(item, {
|
||||
multiple,
|
||||
checkAll,
|
||||
checked,
|
||||
onChange: () => this.handleChange(item),
|
||||
inputValue: inputValue || '',
|
||||
searchable,
|
||||
index
|
||||
})}
|
||||
</div>
|
||||
{checked ? (
|
||||
<Icon icon="check" className={cx('Select-option-mcheck')} />
|
||||
) : null}
|
||||
</>
|
||||
) : (
|
||||
renderMenu(item, {
|
||||
multiple,
|
||||
checkAll,
|
||||
checked,
|
||||
onChange: () => this.handleChange(item),
|
||||
inputValue: inputValue || '',
|
||||
searchable,
|
||||
index
|
||||
})
|
||||
)
|
||||
) : multiple ? (
|
||||
<>
|
||||
<div
|
||||
title={item[labelField]}
|
||||
className={cx('Select-option-item-check')}
|
||||
onClick={() => !item.disabled && this.handleChange([item])}
|
||||
>
|
||||
{item.disabled
|
||||
? item[labelField]
|
||||
: highlight(
|
||||
item[labelField],
|
||||
inputValue as string,
|
||||
cx('Select-option-hl')
|
||||
)}
|
||||
|
||||
{item.tip}
|
||||
</div>
|
||||
{checked ? (
|
||||
<Icon icon="check" className={cx('Select-option-mcheck')} />
|
||||
) : null}
|
||||
</>
|
||||
) : (
|
||||
<span
|
||||
className={cx('Select-option-content')}
|
||||
title={
|
||||
typeof item[labelField] === 'string' ? item[labelField] : ''
|
||||
}
|
||||
>
|
||||
{item.disabled
|
||||
? item[labelField]
|
||||
: highlight(
|
||||
item[labelField],
|
||||
inputValue as string,
|
||||
cx('Select-option-hl')
|
||||
)}
|
||||
{item.tip}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const searchInput = (
|
||||
<div
|
||||
className={cx(`Select-input`, {
|
||||
'is-focused': this.state.isFocused
|
||||
})}
|
||||
>
|
||||
<Icon icon="search" className="icon" />
|
||||
<Input
|
||||
{...getInputProps({
|
||||
onFocus: this.onFocus,
|
||||
onBlur: this.onBlur,
|
||||
disabled: disabled,
|
||||
placeholder: __(searchPromptText),
|
||||
onChange: this.handleInputChange,
|
||||
ref: this.inputRef
|
||||
})}
|
||||
/>
|
||||
{inputValue?.length ? (
|
||||
<a onClick={this.clearSearchValue} className={cx('Select-clear')}>
|
||||
<Icon icon="close" className="icon" />
|
||||
</a>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
|
||||
const menu = (
|
||||
<div
|
||||
className={cx('Select-menu', {
|
||||
'Select--longlist': enableVirtualRender,
|
||||
'is-mobile': true
|
||||
})}
|
||||
>
|
||||
{searchable ? searchInput : null}
|
||||
{multiple && valuesNoWrap ? (
|
||||
<div className={cx('Select-option')}>
|
||||
已选择({selectionValues.length})
|
||||
</div>
|
||||
) : null}
|
||||
{multiple && checkAll && filtedOptions.length ? (
|
||||
<div className={cx('Select-option')}>
|
||||
<Checkbox
|
||||
checked={checkedPartial}
|
||||
partial={checkedPartial && !checkedAll}
|
||||
onChange={this.toggleCheckAll}
|
||||
size="sm"
|
||||
>
|
||||
{__(checkAllLabel)}
|
||||
</Checkbox>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{filtedOptions.length ? (
|
||||
filtedOptions.length > virtualThreshold ? ( // 较多数据时才启用 virtuallist,避免滚动条问题
|
||||
<VirtualList
|
||||
height={
|
||||
filtedOptions.length > 8
|
||||
? 266
|
||||
: filtedOptions.length * virtualItemHeight
|
||||
}
|
||||
itemCount={filtedOptions.length}
|
||||
itemSize={virtualItemHeight}
|
||||
renderItem={renderItem}
|
||||
/>
|
||||
) : (
|
||||
filtedOptions.map((item, index) => {
|
||||
return renderItem({index});
|
||||
})
|
||||
)
|
||||
) : (
|
||||
<div className={cx('Select-noResult')}>{__(noResultsText)}</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<PopUp
|
||||
className={cx(`Select-popup`)}
|
||||
container={popOverContainer}
|
||||
isShow={isOpen}
|
||||
showConfirm={true}
|
||||
onConfirm={this.onConfirm}
|
||||
onHide={onClose}
|
||||
>
|
||||
{multiple ? (
|
||||
menu
|
||||
) : (
|
||||
<div className={cx(`Select-popup-inner`)}>
|
||||
{searchable ? searchInput : null}
|
||||
<Picker
|
||||
className={'Select-picker'}
|
||||
columns={{
|
||||
options: filtedOptions as Option[],
|
||||
optionRender: renderMenu
|
||||
}}
|
||||
highlightTxt={inputValue}
|
||||
onChange={item => this.handleChange(item as any)}
|
||||
showToolbar={false}
|
||||
labelField={labelField}
|
||||
valueField={valueField}
|
||||
itemHeight={40}
|
||||
visibleItemCount={visibleItemCount}
|
||||
value={[selection[0]?.[valueField]]}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</PopUp>
|
||||
);
|
||||
}
|
||||
}
|
||||
313
packages/amis-ui/src/components/Selection.tsx
Normal file
313
packages/amis-ui/src/components/Selection.tsx
Normal file
@@ -0,0 +1,313 @@
|
||||
/**
|
||||
* @file Checkboxes
|
||||
* @description 多选输入框
|
||||
* @author fex
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import isEqual from 'lodash/isEqual';
|
||||
import cx from 'classnames';
|
||||
import {
|
||||
uncontrollable,
|
||||
LocaleProps,
|
||||
localeable,
|
||||
themeable,
|
||||
ThemeProps,
|
||||
autobind,
|
||||
findTree,
|
||||
flattenTree,
|
||||
getOptionValue,
|
||||
getOptionValueBindField,
|
||||
ClassNamesFn
|
||||
} from 'amis-core';
|
||||
import Checkbox from './Checkbox';
|
||||
import {Option, Options} from './Select';
|
||||
|
||||
import type {TestIdBuilder} from 'amis-core';
|
||||
|
||||
export interface BaseSelectionProps extends ThemeProps, LocaleProps {
|
||||
options: Options;
|
||||
className?: string;
|
||||
placeholder?: string;
|
||||
value?: any | Array<any>;
|
||||
multiple?: boolean;
|
||||
clearable?: boolean;
|
||||
labelField?: string;
|
||||
valueField?: string;
|
||||
deferField?: string;
|
||||
onChange?: (value: Array<any> | any) => void;
|
||||
onDeferLoad?: (option: Option) => void;
|
||||
onLeftDeferLoad?: (option: Option, leftOptions: Option) => void;
|
||||
inline?: boolean;
|
||||
labelClassName?: string;
|
||||
option2value?: (option: Option) => any;
|
||||
itemClassName?: string;
|
||||
itemHeight?: number; // 每个选项的高度,主要用于虚拟渲染
|
||||
virtualThreshold?: number; // 数据量多大的时候开启虚拟渲染
|
||||
virtualListHeight?: number; // 虚拟渲染时,列表高度
|
||||
itemRender: (option: Option, states: ItemRenderStates) => JSX.Element;
|
||||
disabled?: boolean;
|
||||
onClick?: (e: React.MouseEvent) => void;
|
||||
placeholderRender?: (props: any) => JSX.Element | null;
|
||||
checkAll?: boolean;
|
||||
checkAllLabel?: string;
|
||||
testIdBuilder?: TestIdBuilder;
|
||||
}
|
||||
|
||||
export interface ItemRenderStates {
|
||||
index: number;
|
||||
labelField?: string;
|
||||
multiple?: boolean;
|
||||
checked: boolean;
|
||||
onChange: () => void;
|
||||
disabled?: boolean;
|
||||
classnames: ClassNamesFn;
|
||||
testIdBuilder?: TestIdBuilder;
|
||||
}
|
||||
|
||||
export class BaseSelection<
|
||||
T extends BaseSelectionProps = BaseSelectionProps,
|
||||
S = any
|
||||
> extends React.Component<T, S> {
|
||||
static itemRender(option: Option, states: ItemRenderStates) {
|
||||
const label = option[states?.labelField || 'label'];
|
||||
const tip = option.tip || '';
|
||||
const classnames = states.classnames;
|
||||
const testIdBuilder = states.testIdBuilder;
|
||||
|
||||
const canlabelTitle =
|
||||
typeof label === 'string' || typeof label === 'number';
|
||||
const canTipTitle = typeof tip === 'string' || typeof label === 'number';
|
||||
const title = canlabelTitle && canTipTitle ? `${label} ${tip}` : '';
|
||||
|
||||
return (
|
||||
<span
|
||||
title={title}
|
||||
className={`${cx({'is-invalid': option?.__unmatched})} ${classnames(
|
||||
'Selection-ellipsis-line'
|
||||
)}`}
|
||||
{...testIdBuilder?.getChild('span').getTestId()}
|
||||
>
|
||||
{label}
|
||||
{tip}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
static defaultProps = {
|
||||
placeholder: 'placeholder.noOption',
|
||||
itemRender: this.itemRender,
|
||||
multiple: true,
|
||||
clearable: false,
|
||||
virtualThreshold: 1000,
|
||||
itemHeight: 32
|
||||
};
|
||||
|
||||
static value2array(
|
||||
value: any,
|
||||
options: Options,
|
||||
option2value: (option: Option) => any = (option: Option) => option,
|
||||
valueField?: string
|
||||
): Options {
|
||||
if (value === void 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (!Array.isArray(value)) {
|
||||
value = [value];
|
||||
}
|
||||
|
||||
return value.map((value: any) => {
|
||||
const option = findTree(
|
||||
options,
|
||||
option => isEqual(option2value(option), value),
|
||||
valueField
|
||||
? {
|
||||
value: getOptionValue(value, valueField),
|
||||
resolve: getOptionValueBindField(valueField)
|
||||
}
|
||||
: undefined
|
||||
);
|
||||
return option || value;
|
||||
});
|
||||
}
|
||||
|
||||
static resolveSelected(
|
||||
value: any,
|
||||
options: Options,
|
||||
option2value: (option: Option) => any = (option: Option) => option
|
||||
) {
|
||||
value = Array.isArray(value) ? value[0] : value;
|
||||
return findTree(options, option => isEqual(option2value(option), value));
|
||||
}
|
||||
|
||||
// 获取两个数组的交集
|
||||
intersectArray(
|
||||
arr1: undefined | Array<Option>,
|
||||
arr2: undefined | Array<Option>
|
||||
): Array<Option> {
|
||||
if (!Array.isArray(arr1) || !Array.isArray(arr2)) {
|
||||
return [];
|
||||
}
|
||||
const len1 = arr1.length;
|
||||
const len2 = arr2.length;
|
||||
if (len1 < len2) {
|
||||
return this.intersectArray(arr2, arr1);
|
||||
}
|
||||
return Array.from(new Set(arr1.filter(item => arr2.includes(item))));
|
||||
}
|
||||
|
||||
toggleOption(option: Option) {
|
||||
const {
|
||||
value,
|
||||
onChange,
|
||||
option2value,
|
||||
options,
|
||||
disabled,
|
||||
multiple,
|
||||
clearable,
|
||||
valueField
|
||||
} = this.props;
|
||||
|
||||
if (disabled || option.disabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
let valueArray = BaseSelection.value2array(
|
||||
value,
|
||||
options,
|
||||
option2value,
|
||||
valueField
|
||||
);
|
||||
let idx = valueArray.indexOf(option);
|
||||
|
||||
if (~idx && (multiple || clearable)) {
|
||||
valueArray.splice(idx, 1);
|
||||
} else if (multiple) {
|
||||
valueArray.push(option);
|
||||
} else {
|
||||
valueArray = [option];
|
||||
}
|
||||
|
||||
let newValue: string | Array<Option> = option2value
|
||||
? valueArray.map(item => option2value(item))
|
||||
: valueArray;
|
||||
|
||||
onChange && onChange(multiple ? newValue : newValue[0]);
|
||||
}
|
||||
|
||||
getAvailableOptions() {
|
||||
const {options} = this.props;
|
||||
const flattendOptions = flattenTree(options, item =>
|
||||
item.children ? null : item
|
||||
).filter(a => a && !a.disabled);
|
||||
|
||||
return flattendOptions as Option[];
|
||||
}
|
||||
|
||||
@autobind
|
||||
toggleAll() {
|
||||
const {value, onChange, option2value, options} = this.props;
|
||||
|
||||
let valueArray: Array<Option> = [];
|
||||
|
||||
const availableOptions = this.getAvailableOptions();
|
||||
const intersectOptions = this.intersectArray(value, availableOptions);
|
||||
|
||||
if (!Array.isArray(value)) {
|
||||
valueArray = availableOptions;
|
||||
} else if (intersectOptions.length < availableOptions.length) {
|
||||
valueArray = Array.from(new Set([...value, ...availableOptions]));
|
||||
} else {
|
||||
valueArray = value.filter(
|
||||
(item: Option) => !availableOptions.includes(item)
|
||||
);
|
||||
}
|
||||
|
||||
let newValue: string | Array<Option> = option2value
|
||||
? valueArray.map(item => option2value(item))
|
||||
: valueArray;
|
||||
|
||||
onChange && onChange(newValue);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
value,
|
||||
options,
|
||||
className,
|
||||
placeholder,
|
||||
inline,
|
||||
labelClassName,
|
||||
disabled,
|
||||
classnames: cx,
|
||||
option2value,
|
||||
itemClassName,
|
||||
itemRender,
|
||||
multiple,
|
||||
labelField,
|
||||
valueField,
|
||||
onClick,
|
||||
testIdBuilder
|
||||
} = this.props;
|
||||
|
||||
const __ = this.props.translate;
|
||||
|
||||
let valueArray = BaseSelection.value2array(
|
||||
value,
|
||||
options,
|
||||
option2value,
|
||||
valueField
|
||||
);
|
||||
let body: Array<React.ReactNode> = [];
|
||||
|
||||
if (Array.isArray(options) && options.length) {
|
||||
body = options.map((option, key) => (
|
||||
<Checkbox
|
||||
type={multiple ? 'checkbox' : 'radio'}
|
||||
className={cx(itemClassName, option.className)}
|
||||
key={key}
|
||||
onChange={() => this.toggleOption(option)}
|
||||
checked={!!~valueArray.indexOf(option)}
|
||||
disabled={disabled || option.disabled}
|
||||
labelClassName={labelClassName}
|
||||
description={option.description}
|
||||
>
|
||||
{itemRender(option, {
|
||||
index: key,
|
||||
multiple: multiple,
|
||||
checked: !!~valueArray.indexOf(option),
|
||||
onChange: () => this.toggleOption(option),
|
||||
labelField,
|
||||
classnames: cx,
|
||||
disabled: disabled || option.disabled,
|
||||
testIdBuilder: testIdBuilder?.getChild(key)
|
||||
})}
|
||||
</Checkbox>
|
||||
));
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx(
|
||||
'Selection',
|
||||
className,
|
||||
inline ? 'Selection--inline' : ''
|
||||
)}
|
||||
onClick={onClick}
|
||||
>
|
||||
{body && body.length ? body : <div>{__(placeholder)}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export class Selection extends BaseSelection {}
|
||||
|
||||
export default themeable(
|
||||
localeable(
|
||||
uncontrollable(Selection, {
|
||||
value: 'onChange'
|
||||
})
|
||||
)
|
||||
);
|
||||
631
packages/amis-ui/src/components/Shape.tsx
Normal file
631
packages/amis-ui/src/components/Shape.tsx
Normal file
@@ -0,0 +1,631 @@
|
||||
/**
|
||||
* @file Shape.tsx 图形组件
|
||||
*
|
||||
* @author allenve(yupeng12@baidu.com)
|
||||
* @created: 2024/12/12
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import {themeable, ThemeProps} from 'amis-core';
|
||||
import {radiusStartEndPoint} from '../utils/vectorComputed';
|
||||
|
||||
export type IShapeType =
|
||||
| 'square'
|
||||
| 'triangle'
|
||||
| 'right-triangle'
|
||||
| 'rectangle'
|
||||
| 'convex-arc-rectangle'
|
||||
| 'concave-arc-rectangle'
|
||||
| 'double-convex-arc-rectangle'
|
||||
| 'double-concave-arc-rectangle'
|
||||
| 'barrel-rectangle' // 桶形矩形
|
||||
| 'rhombus' // 菱形
|
||||
| 'parallelogram' // 平行四边形
|
||||
| 'rectangle-1' // 矩形类型1
|
||||
| 'rectangle-2' // 矩形类型2
|
||||
| 'rectangle-3' // 矩形类型3
|
||||
| 'pentagon' // 五边形
|
||||
| 'hexagon' // 六边形
|
||||
| 'octagon' // 八边形
|
||||
| 'hexagon-star' // 六角星
|
||||
| 'star'
|
||||
| 'heart'
|
||||
| 'circle'
|
||||
| 'arrow'
|
||||
| 'leaf';
|
||||
|
||||
export type IShapeCustomType = 'custom';
|
||||
export type ISHapeStrokeType = 'line' | 'dash' | 'dot';
|
||||
|
||||
export interface IShapeProps extends ThemeProps {
|
||||
shapeType: IShapeType | IShapeCustomType;
|
||||
radius: number;
|
||||
width?: number;
|
||||
height?: number;
|
||||
color?: string;
|
||||
stroke?: string;
|
||||
strokeWidth?: number;
|
||||
strokeType?: 'line' | 'dash' | 'dot';
|
||||
paths?: string[];
|
||||
onClick?: (event: React.MouseEvent) => void;
|
||||
}
|
||||
|
||||
class SvgPathGenerator {
|
||||
constructor(readonly size: number) {}
|
||||
|
||||
static getPath(
|
||||
type: IShapeType | IShapeCustomType,
|
||||
props: Pick<IShapeProps, 'radius' | 'paths'>
|
||||
) {
|
||||
const {radius, paths} = props;
|
||||
const generator = new SvgPathGenerator(200);
|
||||
if (type === 'custom') {
|
||||
return this.getCustomPath(paths);
|
||||
}
|
||||
|
||||
const genFun = generator.getGenerage(type);
|
||||
if (!genFun) {
|
||||
return [];
|
||||
}
|
||||
return genFun(radius * 10);
|
||||
}
|
||||
|
||||
static getStrokeProps(
|
||||
stroke: string,
|
||||
strokeWidth: number,
|
||||
strokeType: ISHapeStrokeType
|
||||
): any {
|
||||
if (strokeType === 'line') {
|
||||
return {
|
||||
stroke,
|
||||
strokeWidth
|
||||
};
|
||||
} else if (strokeType === 'dash') {
|
||||
return {
|
||||
stroke,
|
||||
strokeWidth,
|
||||
strokeDasharray: `${strokeWidth * 2},${strokeWidth}`
|
||||
};
|
||||
} else if (strokeType === 'dot') {
|
||||
return {
|
||||
stroke,
|
||||
strokeWidth,
|
||||
strokeDasharray: `1,${strokeWidth * 2}`,
|
||||
strokeLinecap: 'round',
|
||||
strokeLinejoin: 'miter'
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
toRadians(degrees: number) {
|
||||
return degrees * (Math.PI / 180);
|
||||
}
|
||||
|
||||
getGenerage(type: IShapeType) {
|
||||
const ShapeConfig: {
|
||||
[key in IShapeType]: (radius: number) => string[];
|
||||
} = {
|
||||
'square': this.getSquarePath.bind(this),
|
||||
'triangle': this.getTrianglePath.bind(this),
|
||||
'right-triangle': this.getRightTrianglePath.bind(this),
|
||||
'rectangle': this.getRectanglePath.bind(this),
|
||||
'convex-arc-rectangle': this.getConvexArcRectangle.bind(this),
|
||||
'concave-arc-rectangle': this.getConcaveArcRectangle.bind(this),
|
||||
'double-convex-arc-rectangle': this.getDConvexArcRectangle.bind(this),
|
||||
'double-concave-arc-rectangle': this.getDConcaveArcRectangle.bind(this),
|
||||
'barrel-rectangle': this.getBarrelRectangle.bind(this),
|
||||
'rhombus': this.getRhombusPath.bind(this),
|
||||
'parallelogram': this.getParallelogramPath.bind(this),
|
||||
'rectangle-1': this.getRectangleType1Path.bind(this),
|
||||
'rectangle-2': this.getRectangleType2Path.bind(this),
|
||||
'rectangle-3': this.getRectangleType3Path.bind(this),
|
||||
'pentagon': this.getPentagon.bind(this),
|
||||
'hexagon': this.getHexagon.bind(this),
|
||||
'octagon': this.getOctagonPath.bind(this),
|
||||
'hexagon-star': this.getHexagonStar.bind(this),
|
||||
'star': this.getStar.bind(this),
|
||||
'heart': this.getHeart.bind(this),
|
||||
'circle': this.getCirclePath.bind(this),
|
||||
'arrow': this.getArrowPath.bind(this),
|
||||
'leaf': this.getLeafPath.bind(this)
|
||||
};
|
||||
|
||||
return ShapeConfig[type];
|
||||
}
|
||||
|
||||
radiusPath(
|
||||
radius: number,
|
||||
[endX1, endY1]: [number, number],
|
||||
[startX, startY]: [number, number],
|
||||
[endX2, endY2]: [number, number]
|
||||
) {
|
||||
let flag = true;
|
||||
if (radius < 0) {
|
||||
radius = radius * -1;
|
||||
// 圆角向内
|
||||
flag = false;
|
||||
}
|
||||
const {
|
||||
start,
|
||||
end,
|
||||
radius: mxRadius,
|
||||
sweepFlag
|
||||
} = radiusStartEndPoint(
|
||||
[startX, startY, endX1, endY1],
|
||||
[startX, startY, endX2, endY2],
|
||||
radius
|
||||
);
|
||||
return [
|
||||
`${start[0]},${start[1]}`,
|
||||
`${mxRadius} ${mxRadius} ${0} ${0} ${flag ? sweepFlag : sweepFlag ^ 1}
|
||||
${end[0]},${end[1]}`
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 SVG 路径的每个角添加圆角
|
||||
*
|
||||
* @param {string[]} path
|
||||
* @param {number} radius
|
||||
* @returns
|
||||
* @memberof SvgPathGenerator
|
||||
*/
|
||||
addRoundCornersToPath(points: Array<[number, number]>, radius: number) {
|
||||
const newPath = [];
|
||||
for (let i = 0; i < points.length; i++) {
|
||||
const nextItem = points[i + 1] || points[0];
|
||||
const preItem = points[i - 1] || points[points.length - 1];
|
||||
const [startX, startY] = points[i];
|
||||
const [endX1, endY1] = nextItem;
|
||||
const [endX2, endY2] = preItem;
|
||||
if (!radius) {
|
||||
newPath.push(`${i === 0 ? 'M' : 'L'}${startX},${startY}`);
|
||||
continue;
|
||||
}
|
||||
const [start, A] = this.radiusPath(
|
||||
radius,
|
||||
[endX2, endY2],
|
||||
[startX, startY],
|
||||
[endX1, endY1]
|
||||
);
|
||||
newPath.push(`${i === 0 ? 'M' : 'L'}${start}`, `A${A}`);
|
||||
}
|
||||
newPath.push('Z');
|
||||
|
||||
return newPath;
|
||||
}
|
||||
|
||||
// 正方形
|
||||
getSquarePath(radius: number) {
|
||||
const S = this.size;
|
||||
const ponits1: Array<[number, number]> = [
|
||||
[0, 0],
|
||||
[S, 0],
|
||||
[S, S],
|
||||
[0, S]
|
||||
];
|
||||
const path1 = this.addRoundCornersToPath(ponits1, radius);
|
||||
return [path1];
|
||||
}
|
||||
|
||||
// 等边三角形
|
||||
getTrianglePath(radius: number) {
|
||||
const S = this.size;
|
||||
const height = Math.sin(this.toRadians(60)) * S;
|
||||
// 内切圆为最大圆角,其半径是高度的1/3
|
||||
const maxRadius = Math.min(radius, height / 3) || 0;
|
||||
// sin30度,所以斜边是R的2倍,斜边减去R就是高度移动的距离
|
||||
const dy = (S - height - maxRadius) / 2;
|
||||
|
||||
const points1: Array<[number, number]> = [
|
||||
[0, height + dy],
|
||||
[S / 2, dy],
|
||||
[S, height + dy]
|
||||
];
|
||||
|
||||
const path1 = this.addRoundCornersToPath(points1, radius);
|
||||
|
||||
return [path1];
|
||||
}
|
||||
|
||||
// 直角三角形
|
||||
getRightTrianglePath(radius: number) {
|
||||
const points1: Array<[number, number]> = [
|
||||
[0, 0],
|
||||
[200, 200],
|
||||
[0, 200]
|
||||
];
|
||||
const path1 = this.addRoundCornersToPath(points1, radius);
|
||||
return [path1];
|
||||
}
|
||||
|
||||
// 矩形
|
||||
getRectanglePath(radius: number) {
|
||||
const S = this.size;
|
||||
const points1: Array<[number, number]> = [
|
||||
[0, S / 4],
|
||||
[S, S / 4],
|
||||
[S, (S / 4) * 3],
|
||||
[0, (S / 4) * 3]
|
||||
];
|
||||
const path1 = this.addRoundCornersToPath(points1, radius);
|
||||
return [path1];
|
||||
}
|
||||
|
||||
// 凸弧矩形
|
||||
getConvexArcRectangle(radius: number) {
|
||||
const S = this.size;
|
||||
const w = S;
|
||||
const h = (S / 3) * 2;
|
||||
const x = (S - h) / 2 - radius / 4;
|
||||
const path1 = `
|
||||
M 0 ${h + x}
|
||||
L 0 ${radius + x}
|
||||
Q ${w / 2} ${x} ${w} ${radius + x}
|
||||
L ${w} ${h + x}
|
||||
Z
|
||||
`;
|
||||
|
||||
return [path1];
|
||||
}
|
||||
|
||||
// 凹弧矩形
|
||||
getConcaveArcRectangle(radius: number) {
|
||||
const S = this.size;
|
||||
const w = S;
|
||||
const h = S / 2;
|
||||
const x = (S - h) / 2;
|
||||
const path1 = `
|
||||
M 0 ${h + x}
|
||||
L 0 ${x}
|
||||
Q ${w / 2} ${radius + x} ${w} ${x}
|
||||
L ${w} ${h + x}
|
||||
Z
|
||||
`;
|
||||
|
||||
return [path1];
|
||||
}
|
||||
|
||||
// 双凸弧矩形
|
||||
getDConvexArcRectangle(radius: number) {
|
||||
const S = this.size;
|
||||
const dx = radius;
|
||||
const path1 = `
|
||||
M 0 ${S / 4}
|
||||
Q ${S / 2} ${S / 4 - dx} ${S} ${S / 4}
|
||||
L ${S} ${(S / 4) * 3}
|
||||
Q ${S / 2} ${(S / 4) * 3 + dx} 0 ${(S / 4) * 3}
|
||||
Z
|
||||
`;
|
||||
return [path1];
|
||||
}
|
||||
// 双凹弧矩形
|
||||
getDConcaveArcRectangle(radius: number) {
|
||||
const S = this.size;
|
||||
const dx = radius;
|
||||
const path1 = `
|
||||
M 0 ${S / 4}
|
||||
Q ${S / 2} ${S / 4 + dx} ${S} ${S / 4}
|
||||
L ${S} ${(S / 4) * 3}
|
||||
Q ${S / 2} ${(S / 4) * 3 - dx} 0 ${(S / 4) * 3}
|
||||
Z
|
||||
`;
|
||||
return [path1];
|
||||
}
|
||||
|
||||
// 桶形矩形
|
||||
getBarrelRectangle(radius: number) {
|
||||
const S = this.size;
|
||||
const R = radius;
|
||||
const dx = R / 4;
|
||||
const path1 = `
|
||||
M 0 ${S / 4 - dx}
|
||||
Q ${S / 2} ${S / 4 + R - dx} ${S} ${S / 4 - dx}
|
||||
L ${S} ${(S / 4) * 3 - dx}
|
||||
Q ${S / 2} ${(S / 4) * 3 + R - dx} 0 ${(S / 4) * 3 - dx}
|
||||
Z
|
||||
`;
|
||||
return [path1];
|
||||
}
|
||||
|
||||
// 菱形
|
||||
getRhombusPath(radius: number) {
|
||||
const ponits1: Array<[number, number]> = [
|
||||
[100, 0],
|
||||
[200, 100],
|
||||
[100, 200],
|
||||
[0, 100]
|
||||
];
|
||||
const path1 = this.addRoundCornersToPath(ponits1, radius);
|
||||
|
||||
return [path1];
|
||||
}
|
||||
|
||||
// 平行四边形
|
||||
getParallelogramPath(radius: number) {
|
||||
const points1: Array<[number, number]> = [
|
||||
[50, 0],
|
||||
[200, 0],
|
||||
[150, 200],
|
||||
[0, 200]
|
||||
];
|
||||
|
||||
const path1 = this.addRoundCornersToPath(points1, radius);
|
||||
return [path1];
|
||||
}
|
||||
|
||||
// 矩形-类型1
|
||||
getRectangleType1Path() {
|
||||
const S = this.size;
|
||||
const x = 20;
|
||||
const points: Array<[number, number]> = [
|
||||
[x, 0],
|
||||
[S - x, 0],
|
||||
[S - x, x],
|
||||
[S, x],
|
||||
[S, S - x],
|
||||
[S - x, S - x],
|
||||
[S - x, S],
|
||||
[x, S],
|
||||
[x, S - x],
|
||||
[0, S - x],
|
||||
[0, x],
|
||||
[x, x]
|
||||
];
|
||||
|
||||
const path = this.addRoundCornersToPath(points, 0);
|
||||
return [path];
|
||||
}
|
||||
|
||||
// 矩形-类型2
|
||||
getRectangleType2Path(radius: number) {
|
||||
const S = this.size;
|
||||
const dx = 35;
|
||||
const points: Array<[number, number]> = [
|
||||
[0, 0],
|
||||
[S - dx, 0],
|
||||
[S, S / 2],
|
||||
[S - dx, S],
|
||||
[0, S],
|
||||
[dx, S / 2]
|
||||
];
|
||||
const path = this.addRoundCornersToPath(points, radius);
|
||||
return [path];
|
||||
}
|
||||
|
||||
// 矩形-类型3
|
||||
getRectangleType3Path(radius: number) {
|
||||
const S = this.size;
|
||||
const dx = 35;
|
||||
const points: Array<[number, number]> = [
|
||||
[0, 0],
|
||||
[S - dx, 0],
|
||||
[S, S / 2],
|
||||
[S - dx, S],
|
||||
[0, S]
|
||||
];
|
||||
const path = this.addRoundCornersToPath(points, radius);
|
||||
return [path];
|
||||
}
|
||||
|
||||
// 星形
|
||||
getStar(radius: number) {
|
||||
const points: Array<[number, number]> = [
|
||||
[100, 11.1297757],
|
||||
[129.05723, 70.0061542],
|
||||
[194.031171, 79.4474205],
|
||||
[147.015586, 125.27629],
|
||||
[158.11446, 189.987692],
|
||||
[100, 159.435112],
|
||||
[41.8855403, 189.987692],
|
||||
[52.9844145, 125.27629],
|
||||
[5.96882894, 79.4474205],
|
||||
[70.9427701, 70.0061542]
|
||||
];
|
||||
|
||||
const path = this.addRoundCornersToPath(points, radius);
|
||||
return [path];
|
||||
}
|
||||
|
||||
// 心形
|
||||
getHeart() {
|
||||
const path = `
|
||||
M143.526375,12
|
||||
C132.21418,12 124.346417,16.1423074 111.598905,27.0093876
|
||||
C111.007635,27.5125184 107.668026,30.3835001 106.701139,31.2037806
|
||||
C103.410893,33.9868624 98.5891073,33.9868624 95.2988609,31.2037806
|
||||
C94.331974,30.3807731 90.9923649,27.5125184 90.4010952,27.0093876
|
||||
C77.653583,16.1423074 69.78582,12 58.4736246,12
|
||||
C24.0713382,12 2,39.4823959 2,79.1438299
|
||||
C2,109.386491 32.9900653,146.921686 95.9859458,190.440184
|
||||
C99.0044944,192.519939 102.995506,192.519939 106.014054,190.440184
|
||||
C169.009935,146.924413 200,109.386491 200,79.1438299
|
||||
C200,39.4823959 177.928662,12 143.526375,12
|
||||
Z`;
|
||||
return [path];
|
||||
}
|
||||
|
||||
// 五边形
|
||||
getPentagon(radius: number) {
|
||||
const S = this.size;
|
||||
const a = S / (Math.tan(this.toRadians(54)) * 2);
|
||||
const b = S / 2;
|
||||
const c = Math.sqrt(a * a + b * b);
|
||||
const x1 = Math.sin(this.toRadians(18)) * c;
|
||||
const x2 = Math.cos(this.toRadians(18)) * c;
|
||||
const dx = (S - (a + x2)) / 2;
|
||||
const points1: Array<[number, number]> = [
|
||||
[S, a + dx],
|
||||
[S - x1, a + x2 + dx],
|
||||
[x1, a + x2 + dx],
|
||||
[0, a + dx],
|
||||
[b, dx]
|
||||
];
|
||||
const path1 = this.addRoundCornersToPath(points1, radius);
|
||||
|
||||
return [path1];
|
||||
}
|
||||
|
||||
// 六边形
|
||||
getHexagon(radius: number) {
|
||||
const points1: Array<[number, number]> = [
|
||||
[100, 0.577350269],
|
||||
[186.10254, 50.2886751],
|
||||
[186.10254, 149.711325],
|
||||
[100, 199.42265],
|
||||
[13.8974596, 149.711325],
|
||||
[13.8974596, 50.2886751]
|
||||
];
|
||||
|
||||
const path1 = this.addRoundCornersToPath(points1, radius);
|
||||
return [path1];
|
||||
}
|
||||
|
||||
// 正八边形
|
||||
getOctagonPath(radius: number) {
|
||||
const S = this.size;
|
||||
const x = S / (2 + Math.sqrt(2));
|
||||
const points1: Array<[number, number]> = [
|
||||
[x, 0],
|
||||
[S - x, 0],
|
||||
[S, x],
|
||||
[S, S - x],
|
||||
[S - x, S],
|
||||
[x, S],
|
||||
[0, S - x],
|
||||
[0, x]
|
||||
];
|
||||
const points2: Array<[number, number]> = [
|
||||
[S - x, S],
|
||||
[S, S - x],
|
||||
[S, x],
|
||||
[S - x, 0],
|
||||
[x, 0],
|
||||
[0, x],
|
||||
[0, S - x],
|
||||
[x, S]
|
||||
];
|
||||
const path1 = this.addRoundCornersToPath(points1, radius);
|
||||
return [path1];
|
||||
}
|
||||
|
||||
// 六角星
|
||||
getHexagonStar(radius: number) {
|
||||
const points1: Array<[number, number]> = [
|
||||
[149.380343, 14.4707367],
|
||||
[142.764632, 75.3098284],
|
||||
[198.760686, 100],
|
||||
[142.764632, 124.690172],
|
||||
[149.380343, 185.529263],
|
||||
[100, 149.380343],
|
||||
[50.6196568, 185.529263],
|
||||
[57.2353684, 124.690172],
|
||||
[1.23931367, 100],
|
||||
[57.2353684, 75.3098284],
|
||||
[50.6196568, 14.4707367],
|
||||
[100, 50.6196568]
|
||||
];
|
||||
|
||||
const path1 = this.addRoundCornersToPath(points1, radius);
|
||||
|
||||
return [path1];
|
||||
}
|
||||
|
||||
// 圆
|
||||
getCirclePath() {
|
||||
const path = `
|
||||
M 100 0
|
||||
A 100 100 0 0 1 100 200
|
||||
A 100 100 0 0 1 100 0
|
||||
Z
|
||||
`;
|
||||
return [path];
|
||||
}
|
||||
|
||||
// 箭头
|
||||
getArrowPath(radius: number) {
|
||||
const points: Array<[number, number]> = [
|
||||
[0, 75],
|
||||
[110, 75],
|
||||
[110, 30],
|
||||
[200, 100],
|
||||
[110, 170],
|
||||
[110, 125],
|
||||
[0, 125]
|
||||
];
|
||||
|
||||
return [this.addRoundCornersToPath(points, radius)];
|
||||
}
|
||||
|
||||
// 树叶形状
|
||||
getLeafPath() {
|
||||
const path = `
|
||||
M 0 140
|
||||
Q 0 60 80 60
|
||||
L 200 60
|
||||
Q 200 140 120 140
|
||||
Z
|
||||
`;
|
||||
return [path];
|
||||
}
|
||||
|
||||
static getCustomPath(paths?: string[]) {
|
||||
return paths || [];
|
||||
}
|
||||
}
|
||||
|
||||
const Shape: React.FC<IShapeProps> = props => {
|
||||
const BASE_SIZE = 200;
|
||||
const {
|
||||
classnames: cx,
|
||||
className,
|
||||
shapeType,
|
||||
color,
|
||||
stroke = 'currentColor',
|
||||
strokeWidth = 0,
|
||||
strokeType = 'line',
|
||||
width = BASE_SIZE,
|
||||
height = BASE_SIZE
|
||||
} = props;
|
||||
const paths = SvgPathGenerator.getPath(shapeType, props);
|
||||
const strokeProps = SvgPathGenerator.getStrokeProps(
|
||||
stroke,
|
||||
strokeWidth,
|
||||
strokeType
|
||||
);
|
||||
const getStyle = React.useCallback(
|
||||
() => [
|
||||
{
|
||||
width: width + 'px',
|
||||
height: height + 'px'
|
||||
},
|
||||
{
|
||||
transform: `scale(${width / BASE_SIZE}, ${height / BASE_SIZE})`
|
||||
}
|
||||
],
|
||||
[width, height]
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx('Shape', className)}
|
||||
style={getStyle()[0]}
|
||||
onClick={props.onClick}
|
||||
>
|
||||
<svg
|
||||
className={cx('Shape-svg')}
|
||||
width={BASE_SIZE}
|
||||
height={BASE_SIZE}
|
||||
style={getStyle()[1]}
|
||||
fill={color ? color : 'currentColor'}
|
||||
viewBox={`0 0 ${BASE_SIZE} ${BASE_SIZE}`}
|
||||
>
|
||||
{paths.map((path, index) => (
|
||||
<path {...strokeProps} key={index} d={path} />
|
||||
))}
|
||||
</svg>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default themeable(Shape);
|
||||
313
packages/amis-ui/src/components/Signature.tsx
Normal file
313
packages/amis-ui/src/components/Signature.tsx
Normal file
@@ -0,0 +1,313 @@
|
||||
/**
|
||||
* @file Signature.tsx 签名组件
|
||||
*
|
||||
* @created: 2024/03/04
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import {
|
||||
themeable,
|
||||
ThemeProps,
|
||||
isMobileDevice,
|
||||
LocaleProps,
|
||||
localeable,
|
||||
resizeSensor
|
||||
} from 'amis-core';
|
||||
import SmoothSignature from 'smooth-signature';
|
||||
import Button from './Button';
|
||||
import {Icon} from '../index';
|
||||
import Modal from './Modal';
|
||||
import Spinner from './Spinner';
|
||||
|
||||
export interface ISignatureProps extends LocaleProps, ThemeProps {
|
||||
value?: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
color?: string;
|
||||
bgColor?: string;
|
||||
clearBtnLabel?: string;
|
||||
clearBtnIcon?: string;
|
||||
undoBtnLabel?: string;
|
||||
undoBtnIcon?: string;
|
||||
confirmBtnLabel?: string;
|
||||
confirmBtnIcon?: string;
|
||||
embed?: boolean;
|
||||
embedConfirmLabel?: string;
|
||||
embedConfirmIcon?: string;
|
||||
ebmedCancelLabel?: string;
|
||||
ebmedCancelIcon?: string;
|
||||
embedBtnIcon?: string;
|
||||
embedBtnLabel?: string;
|
||||
onChange?: (value?: string) => Promise<void>;
|
||||
}
|
||||
|
||||
const Signature: React.FC<ISignatureProps> = props => {
|
||||
const {translate: __, classnames: cx, className, width, height} = props;
|
||||
const embedMobile =
|
||||
props.embed && isMobileDevice() && window.innerWidth < 768;
|
||||
|
||||
const [sign, setSign] = React.useState<SmoothSignature | null>(null);
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const [uploading, setUploading] = React.useState(false);
|
||||
const [fullScreen, setFullScreen] = React.useState(!!embedMobile);
|
||||
const [embed, setEmbed] = React.useState(props.embed || false);
|
||||
const [data, setData] = React.useState<string | undefined>(props.value);
|
||||
const wrapper = React.useRef<HTMLDivElement>(null);
|
||||
React.useEffect(() => {
|
||||
if (!wrapper.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
const unSensor = resizeSensor(wrapper.current, resize);
|
||||
|
||||
return () => {
|
||||
setSign(null);
|
||||
unSensor();
|
||||
};
|
||||
}, []);
|
||||
|
||||
React.useEffect(() => setData(props.value), [props.value]);
|
||||
|
||||
React.useEffect(() => setEmbed(props.embed || false), [props.embed]);
|
||||
|
||||
const clear = React.useCallback(() => {
|
||||
if (sign) {
|
||||
sign.clear();
|
||||
}
|
||||
props.onChange?.(undefined);
|
||||
}, [sign]);
|
||||
const undo = React.useCallback(() => {
|
||||
if (sign) {
|
||||
sign.undo();
|
||||
}
|
||||
}, [sign]);
|
||||
|
||||
const confirm = React.useCallback(() => {
|
||||
if (!sign) {
|
||||
return;
|
||||
}
|
||||
|
||||
const base64 = fullScreen
|
||||
? sign.getRotateCanvas(-90).toDataURL()
|
||||
: sign.toDataURL();
|
||||
|
||||
setData(base64);
|
||||
setUploading(true);
|
||||
props.onChange?.(base64).then(() => {
|
||||
setUploading(false);
|
||||
});
|
||||
}, [sign]);
|
||||
const resize = React.useCallback(() => {
|
||||
setSign(null);
|
||||
}, []);
|
||||
const handleFullScreen = React.useCallback(() => {
|
||||
setFullScreen(true);
|
||||
setSign(null);
|
||||
}, []);
|
||||
const handleUnFullScreen = React.useCallback(() => {
|
||||
setFullScreen(false);
|
||||
setSign(null);
|
||||
}, []);
|
||||
const handleCloseModal = React.useCallback(() => {
|
||||
setOpen(false);
|
||||
setFullScreen(!!embedMobile);
|
||||
setSign(null);
|
||||
}, []);
|
||||
const handleConfirmModal = React.useCallback(() => {
|
||||
confirm();
|
||||
handleCloseModal();
|
||||
}, [sign]);
|
||||
const initCanvas = React.useCallback(
|
||||
(element: HTMLCanvasElement) => {
|
||||
const {width, height} = props;
|
||||
const clientWidth = element.parentElement!.clientWidth;
|
||||
const clientHeight = element.parentElement!.clientHeight;
|
||||
const defaultWidth = width || clientWidth - (fullScreen ? 40 : 0);
|
||||
const defaultHeight = fullScreen
|
||||
? clientHeight
|
||||
: Math.min(height || clientWidth / 2 - 40, clientHeight - 40);
|
||||
const signature = new SmoothSignature(element, {
|
||||
width: Math.max(defaultWidth, 200),
|
||||
height: Math.max(defaultHeight, 160),
|
||||
color: props.color || '#000',
|
||||
bgColor: props.bgColor || '#efefef'
|
||||
});
|
||||
setSign(signature);
|
||||
},
|
||||
[width, height, fullScreen]
|
||||
);
|
||||
|
||||
function embedCanvasRef(ref: HTMLCanvasElement) {
|
||||
if (open && ref && !sign) {
|
||||
initCanvas(ref);
|
||||
}
|
||||
}
|
||||
|
||||
function canvasRef(ref: HTMLCanvasElement) {
|
||||
if (ref && !sign) {
|
||||
initCanvas(ref);
|
||||
}
|
||||
}
|
||||
|
||||
function renderTool(right: boolean = true) {
|
||||
const {
|
||||
clearBtnLabel,
|
||||
clearBtnIcon,
|
||||
undoBtnLabel,
|
||||
undoBtnIcon,
|
||||
confirmBtnLabel,
|
||||
confirmBtnIcon,
|
||||
embedConfirmLabel,
|
||||
embedConfirmIcon,
|
||||
ebmedCancelLabel,
|
||||
ebmedCancelIcon
|
||||
} = props;
|
||||
|
||||
return (
|
||||
<div className={cx('Signature-Tool')}>
|
||||
<div className="actions">
|
||||
<div className="left-actions">
|
||||
<Button
|
||||
onClick={clear}
|
||||
tooltip={clearBtnLabel || __('Signature.clear')}
|
||||
>
|
||||
{clearBtnLabel}
|
||||
<Icon
|
||||
icon={clearBtnIcon || 'close'}
|
||||
className={cx('icon', {'ml-1': clearBtnLabel})}
|
||||
/>
|
||||
</Button>
|
||||
<Button
|
||||
onClick={undo}
|
||||
tooltip={undoBtnLabel || __('Signature.undo')}
|
||||
>
|
||||
{undoBtnLabel}
|
||||
<Icon
|
||||
icon={undoBtnIcon || 'undo-normal'}
|
||||
className={cx('icon', {'ml-1': undoBtnLabel})}
|
||||
/>
|
||||
</Button>
|
||||
{embedMobile ? null : fullScreen ? (
|
||||
<Button onClick={handleUnFullScreen}>
|
||||
<Icon icon="un-fullscreen" className="icon" />
|
||||
</Button>
|
||||
) : (
|
||||
<Button onClick={handleFullScreen}>
|
||||
<Icon icon="full-screen" className="icon" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{right ? (
|
||||
<div className="right-actions">
|
||||
{embed ? (
|
||||
<>
|
||||
<Button onClick={handleCloseModal}>
|
||||
{ebmedCancelLabel || __('Signature.cancel')}
|
||||
<Icon icon={ebmedCancelIcon} className="icon ml-1" />
|
||||
</Button>
|
||||
<Button onClick={handleConfirmModal} level="primary">
|
||||
{embedConfirmLabel || __('Signature.confirm')}
|
||||
<Icon icon={embedConfirmIcon} className="icon ml-1" />
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Button onClick={confirm} level="primary">
|
||||
{confirmBtnLabel || __('Signature.confirm')}
|
||||
<Icon icon={confirmBtnIcon} className="icon ml-1" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function renderEmbedSignature() {
|
||||
const {
|
||||
embedConfirmLabel,
|
||||
ebmedCancelLabel,
|
||||
embedBtnIcon: icon,
|
||||
embedBtnLabel,
|
||||
embedConfirmIcon,
|
||||
ebmedCancelIcon
|
||||
} = props;
|
||||
return (
|
||||
<div className={cx('Signature-Embed')}>
|
||||
<Button onClick={() => setOpen(true)}>
|
||||
<Icon className="icon mr-1" icon={icon || 'fas fa-pen'}></Icon>
|
||||
{embedBtnLabel || data
|
||||
? __('Signature.embedUpdateLabel')
|
||||
: __('Signature.embedLabel')}
|
||||
</Button>
|
||||
{data ? (
|
||||
<div className={cx('Signature-Embed-Preview')}>
|
||||
{uploading ? (
|
||||
<Spinner show={uploading} />
|
||||
) : (
|
||||
<>
|
||||
<img src={data} />
|
||||
<Icon
|
||||
className="preview-close icon"
|
||||
icon="close"
|
||||
onClick={clear}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
) : uploading ? (
|
||||
<div className={cx('Signature-Embed-Preview')}>
|
||||
<Spinner show={uploading} />
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<Modal show={open} onHide={handleCloseModal} size="full">
|
||||
<Modal.Body>
|
||||
<div
|
||||
className={cx('Signature-Embed-Body', {
|
||||
'is-fullScreen': fullScreen
|
||||
})}
|
||||
>
|
||||
<canvas className={cx('Signature-canvas')} ref={embedCanvasRef} />
|
||||
{renderTool(fullScreen)}
|
||||
</div>
|
||||
</Modal.Body>
|
||||
{fullScreen ? null : (
|
||||
<Modal.Footer>
|
||||
<Button onClick={handleCloseModal}>
|
||||
{ebmedCancelLabel || __('Signature.cancel')}
|
||||
<Icon icon={ebmedCancelIcon} className="icon ml-1" />
|
||||
</Button>
|
||||
<Button onClick={handleConfirmModal} level="primary">
|
||||
{embedConfirmLabel || __('Signature.confirm')}
|
||||
<Icon icon={embedConfirmIcon} className="icon ml-1" />
|
||||
</Button>
|
||||
</Modal.Footer>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cx(className)}>
|
||||
<div
|
||||
className={cx('Signature', {
|
||||
'is-fullScreen': fullScreen
|
||||
})}
|
||||
ref={wrapper}
|
||||
>
|
||||
{embed ? (
|
||||
renderEmbedSignature()
|
||||
) : (
|
||||
<>
|
||||
<canvas className={cx('Signature-canvas')} ref={canvasRef} />
|
||||
{renderTool()}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default themeable(localeable(Signature));
|
||||
221
packages/amis-ui/src/components/Slider.tsx
Normal file
221
packages/amis-ui/src/components/Slider.tsx
Normal file
@@ -0,0 +1,221 @@
|
||||
/**
|
||||
* @file Slider 滑动条
|
||||
* @author qhy
|
||||
* @date 2025/01/21
|
||||
*/
|
||||
|
||||
import React, {useCallback, useEffect, useMemo} from 'react';
|
||||
import {themeable, ThemeProps} from 'amis-core';
|
||||
import useClickAway from '../hooks/use-click-away';
|
||||
|
||||
interface SliderProps extends ThemeProps {
|
||||
body: React.ReactElement;
|
||||
left?: React.ReactElement;
|
||||
right?: React.ReactElement;
|
||||
bodyWidth?: string;
|
||||
showLeft?: boolean;
|
||||
showRight?: boolean;
|
||||
canSwitch?: boolean;
|
||||
onLeftShow?: () => void;
|
||||
onRightShow?: () => void;
|
||||
onLeftHide?: () => void;
|
||||
onRightHide?: () => void;
|
||||
}
|
||||
|
||||
function Slider(props: SliderProps) {
|
||||
const {
|
||||
classnames: cx,
|
||||
mobileUI,
|
||||
bodyWidth,
|
||||
showLeft,
|
||||
showRight,
|
||||
canSwitch = true,
|
||||
onLeftShow,
|
||||
onRightShow,
|
||||
onLeftHide,
|
||||
onRightHide
|
||||
} = props;
|
||||
const sliderRef = React.useRef<HTMLDivElement>(null);
|
||||
const leftRef = React.useRef<HTMLDivElement>(null);
|
||||
const rightRef = React.useRef<HTMLDivElement>(null);
|
||||
const leftShow = React.useRef(false);
|
||||
const rightShow = React.useRef(false);
|
||||
|
||||
const isMouseDown = React.useRef(false);
|
||||
const direction = React.useRef<'left' | 'right' | null>(null);
|
||||
const startX = React.useRef(0);
|
||||
const doc = React.useRef(document);
|
||||
|
||||
const leftRightDefaultWidth = useMemo(
|
||||
() => (100 - parseInt(bodyWidth || '60')) / 2,
|
||||
[bodyWidth]
|
||||
);
|
||||
|
||||
function handleStart(e: React.MouseEvent | React.TouchEvent) {
|
||||
if (mobileUI && canSwitch && !showLeft && !showRight) {
|
||||
isMouseDown.current = true;
|
||||
if ((e as any).touches?.[0]) {
|
||||
startX.current = (e as React.TouchEvent).touches[0].clientX;
|
||||
doc.current.addEventListener('touchend', handleUp);
|
||||
} else {
|
||||
startX.current = (e as React.MouseEvent).clientX;
|
||||
doc.current.addEventListener('mouseup', handleUp);
|
||||
}
|
||||
}
|
||||
}
|
||||
function handleMove(e: React.MouseEvent | React.TouchEvent) {
|
||||
if (!isMouseDown.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
let currentX = 0;
|
||||
if ((e as any).changedTouches?.[0]) {
|
||||
currentX = (e as React.TouchEvent).changedTouches[0].clientX;
|
||||
} else {
|
||||
currentX = (e as React.MouseEvent).clientX;
|
||||
}
|
||||
|
||||
const currentDirection = currentX < startX.current ? 'left' : 'right';
|
||||
|
||||
let leftWidth = Number(leftRef.current?.style.width.replace('%', '') || 0);
|
||||
let rightWidth = Number(
|
||||
rightRef.current?.style.width.replace('%', '') || 0
|
||||
);
|
||||
if (currentDirection === 'right') {
|
||||
leftWidth = Math.min(leftWidth + 1, leftRightDefaultWidth);
|
||||
if (rightWidth > 0) {
|
||||
rightWidth = Math.max(rightWidth - 1, 0);
|
||||
}
|
||||
} else {
|
||||
rightWidth = Math.min(rightWidth + 1, leftRightDefaultWidth);
|
||||
if (leftWidth > 0) {
|
||||
leftWidth = Math.max(leftWidth - 1, 0);
|
||||
}
|
||||
}
|
||||
|
||||
direction.current = currentDirection;
|
||||
|
||||
leftRef.current?.style.setProperty('width', leftWidth + '%');
|
||||
rightRef.current?.style.setProperty('width', rightWidth + '%');
|
||||
}
|
||||
|
||||
function handleUp(e: MouseEvent | TouchEvent) {
|
||||
if (!mobileUI || !isMouseDown.current) {
|
||||
return;
|
||||
}
|
||||
isMouseDown.current = false;
|
||||
let currentX = 0;
|
||||
if ((e as any).changedTouches?.[0]) {
|
||||
currentX = (e as TouchEvent).changedTouches[0].clientX;
|
||||
doc.current.removeEventListener('touchend', handleUp);
|
||||
} else {
|
||||
currentX = (e as MouseEvent).clientX;
|
||||
doc.current.removeEventListener('mouseup', handleUp);
|
||||
}
|
||||
|
||||
const isMove = Math.abs(currentX - startX.current) > 10;
|
||||
let leftWidth =
|
||||
isMove && direction.current === 'right' ? leftRightDefaultWidth : 0;
|
||||
let rightWidth =
|
||||
isMove && direction.current === 'left' ? leftRightDefaultWidth : 0;
|
||||
|
||||
setWidth(leftWidth, rightWidth);
|
||||
}
|
||||
|
||||
function setWidth(left: number, right: number) {
|
||||
if (left === 0 && leftShow.current) {
|
||||
leftShow.current = false;
|
||||
onLeftHide && onLeftHide();
|
||||
}
|
||||
if (right === 0 && rightShow.current) {
|
||||
rightShow.current = false;
|
||||
onRightHide && onRightHide();
|
||||
}
|
||||
if (left === leftRightDefaultWidth) {
|
||||
leftShow.current = true;
|
||||
onLeftShow && onLeftShow();
|
||||
}
|
||||
if (right === leftRightDefaultWidth) {
|
||||
rightShow.current = true;
|
||||
onRightShow && onRightShow();
|
||||
}
|
||||
|
||||
leftRef.current?.style.setProperty('width', left + '%');
|
||||
rightRef.current?.style.setProperty('width', right + '%');
|
||||
}
|
||||
|
||||
const reset = useCallback((e: MouseEvent) => {
|
||||
if (!sliderRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
!sliderRef.current.contains(e.target as HTMLElement) &&
|
||||
(leftShow.current || rightShow.current)
|
||||
) {
|
||||
setWidth(0, 0);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 点击外部时,重置滑动条
|
||||
useClickAway(sliderRef, reset, doc.current, ['mouseup', 'touchend']);
|
||||
|
||||
return (
|
||||
<div className={cx('Slider')} ref={sliderRef}>
|
||||
{mobileUI ? (
|
||||
<>
|
||||
{props.left && (
|
||||
<div
|
||||
className={cx('Slider-LeftContainer')}
|
||||
ref={leftRef}
|
||||
style={{
|
||||
width: showLeft ? leftRightDefaultWidth + '%' : '0%'
|
||||
}}
|
||||
>
|
||||
{props.left}
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
className={cx('Slider-BodyContainer')}
|
||||
onMouseDown={handleStart}
|
||||
onMouseMove={handleMove}
|
||||
onTouchStart={handleStart}
|
||||
onTouchMove={handleMove}
|
||||
>
|
||||
{props.body}
|
||||
</div>
|
||||
{props.right && (
|
||||
<div
|
||||
className={cx('Slider-RightContainer')}
|
||||
ref={rightRef}
|
||||
style={{
|
||||
width: showRight ? leftRightDefaultWidth + '%' : '0%'
|
||||
}}
|
||||
>
|
||||
{props.right}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div
|
||||
className={cx('Slider-BodyContainer')}
|
||||
style={{
|
||||
width: bodyWidth ? bodyWidth : '60%'
|
||||
}}
|
||||
>
|
||||
{props.body}
|
||||
</div>
|
||||
{props.left && (
|
||||
<div className={cx('Slider-LeftContainer')}>{props.left}</div>
|
||||
)}
|
||||
{props.right && (
|
||||
<div className={cx('Slider-RightContainer')}>{props.right}</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default themeable(Slider);
|
||||
137
packages/amis-ui/src/components/SparkLine.tsx
Normal file
137
packages/amis-ui/src/components/SparkLine.tsx
Normal file
@@ -0,0 +1,137 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
localeable,
|
||||
LocaleProps,
|
||||
RendererProps,
|
||||
themeable,
|
||||
ThemeProps,
|
||||
setThemeClassName
|
||||
} from 'amis-core';
|
||||
import type {PlainObject} from 'amis-core';
|
||||
|
||||
export interface SparkLineProps extends ThemeProps, LocaleProps {
|
||||
className?: string;
|
||||
width: number;
|
||||
height: number;
|
||||
value?: Array<
|
||||
| number
|
||||
| {
|
||||
value: number;
|
||||
label?: string;
|
||||
}
|
||||
>;
|
||||
placeholder?: string;
|
||||
onClick?: (e: React.MouseEvent, value?: PlainObject) => void;
|
||||
id?: string;
|
||||
wrapperCustomStyle?: any;
|
||||
themeCss?: any;
|
||||
}
|
||||
|
||||
export class SparkLine extends React.Component<SparkLineProps> {
|
||||
static defaultProps = {
|
||||
width: 100,
|
||||
height: 50
|
||||
};
|
||||
|
||||
normalizeValue(item: any): number {
|
||||
if (typeof item === 'number') {
|
||||
return item;
|
||||
} else if (item && typeof item.value === 'number') {
|
||||
return item.value;
|
||||
} else {
|
||||
return Number(item) || 0;
|
||||
}
|
||||
}
|
||||
|
||||
renderLines() {
|
||||
const {width, height, value, classnames: cx} = this.props;
|
||||
|
||||
const values = value!.map(item => this.normalizeValue(item));
|
||||
const max = Math.max(...values);
|
||||
const min = Math.min(...values);
|
||||
const duration = max - min || 1;
|
||||
|
||||
const gap = width / (values.length - 1);
|
||||
const points: Array<{
|
||||
x: number;
|
||||
y: number;
|
||||
}> = [];
|
||||
|
||||
values.forEach((value, index) => {
|
||||
points.push({
|
||||
x: index * gap,
|
||||
y: height - ((value - min) * height) / duration
|
||||
});
|
||||
});
|
||||
|
||||
const lineD = points
|
||||
.map((value, index) => `${index === 0 ? 'M' : 'L'} ${value.x} ${value.y}`)
|
||||
.join(' ');
|
||||
const areaD = `${lineD} V ${height} L 0 ${height} Z`;
|
||||
|
||||
// todo 支持鼠标 hover 显示对应数据。
|
||||
|
||||
return (
|
||||
<g>
|
||||
<path className={cx(`Sparkline-area`)} d={areaD} stroke="none" />
|
||||
<path className={cx(`Sparkline-line`)} d={lineD} fill="none" />
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
classnames: cx,
|
||||
className,
|
||||
style,
|
||||
value,
|
||||
width,
|
||||
height,
|
||||
placeholder,
|
||||
translate: __,
|
||||
onClick,
|
||||
id,
|
||||
wrapperCustomStyle,
|
||||
themeCss
|
||||
} = this.props;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx(
|
||||
'Sparkline',
|
||||
className,
|
||||
onClick ? 'Sparkline--clickable' : '',
|
||||
setThemeClassName({
|
||||
...this.props,
|
||||
name: 'baseControlClassName',
|
||||
id,
|
||||
themeCss
|
||||
}),
|
||||
setThemeClassName({
|
||||
...this.props,
|
||||
name: 'wrapperCustomStyle',
|
||||
id,
|
||||
themeCss: wrapperCustomStyle
|
||||
})
|
||||
)}
|
||||
style={style}
|
||||
onClick={onClick}
|
||||
>
|
||||
{Array.isArray(value) && value.length > 1 ? (
|
||||
<svg
|
||||
className={cx('Sparkline-svg')}
|
||||
width={width}
|
||||
height={height}
|
||||
viewBox={`0 0 ${width} ${height}`}
|
||||
>
|
||||
{this.renderLines()}
|
||||
</svg>
|
||||
) : (
|
||||
placeholder ?? __('placeholder.empty')
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(localeable(SparkLine));
|
||||
301
packages/amis-ui/src/components/Spinner.tsx
Normal file
301
packages/amis-ui/src/components/Spinner.tsx
Normal file
@@ -0,0 +1,301 @@
|
||||
/**
|
||||
* @file Spinner
|
||||
* @description
|
||||
* @author fex
|
||||
* @date 2017-11-07
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import {themeable, ThemeProps} from 'amis-core';
|
||||
import Transition, {ENTERED, ENTERING} from 'react-transition-group/Transition';
|
||||
import {Icon, hasIcon} from './icons';
|
||||
import {types} from 'mobx-state-tree';
|
||||
import {observable, reaction} from 'mobx';
|
||||
|
||||
const fadeStyles: {
|
||||
[propName: string]: string;
|
||||
} = {
|
||||
[ENTERED]: 'in',
|
||||
[ENTERING]: 'in'
|
||||
};
|
||||
|
||||
// Spinner Props
|
||||
export interface SpinnerProps extends ThemeProps, SpinnerExtraProps {
|
||||
show?: boolean; // 控制Spinner显示与隐藏
|
||||
className?: string; // 自定义最外层元素class
|
||||
spinnerClassName?: string; // spin图标位置包裹元素的自定义class
|
||||
/**
|
||||
* @deprecated 已废弃,没有作用
|
||||
*/
|
||||
mode?: string;
|
||||
size?: 'sm' | 'lg' | ''; // spinner Icon 大小
|
||||
icon?: string | React.ReactNode; // 自定义icon
|
||||
tip?: string; // spinner文案
|
||||
tipPlacement?: 'top' | 'right' | 'bottom' | 'left'; // spinner文案位置
|
||||
delay?: number; // 延迟显示
|
||||
overlay?: boolean; // 是否显示遮罩层,有children属性才生效
|
||||
/** 是否处于禁用状态 */
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export interface SpinnerExtraProps {
|
||||
loadingConfig?: {
|
||||
root?: string;
|
||||
show?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
const SpinnerSharedStore = types
|
||||
.model('SpinnerSharedStore', {})
|
||||
.volatile(self => {
|
||||
return {
|
||||
// 保存所有可以进入 loading 状态(props.show = true)的 Spinner 的父级容器
|
||||
spinningContainers: observable.set([] as HTMLElement[], {
|
||||
deep: false
|
||||
})
|
||||
};
|
||||
})
|
||||
.actions(self => {
|
||||
return {
|
||||
push: (spinnerContainer: HTMLElement) => {
|
||||
if (self.spinningContainers.has(spinnerContainer)) {
|
||||
return;
|
||||
}
|
||||
self.spinningContainers.add(spinnerContainer);
|
||||
},
|
||||
remove: (spinnerContainer: HTMLElement) => {
|
||||
if (self.spinningContainers.has(spinnerContainer)) {
|
||||
self.spinningContainers.delete(spinnerContainer);
|
||||
}
|
||||
},
|
||||
/**
|
||||
* 判断当前 Spinner 是否可以进入 loading 状态
|
||||
* @param spinnerContainerWillCheck 待检查的 Spinner 父容器
|
||||
* @returns {boolean} 是否可以进入 loading
|
||||
*/
|
||||
checkLoading: (spinnerContainerWillCheck: HTMLElement | null) => {
|
||||
if (self.spinningContainers.has(spinnerContainerWillCheck)) {
|
||||
if (!self.spinningContainers.size) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let loading = true;
|
||||
|
||||
// 检查缓存的容器中是否有当前容器的父级元素
|
||||
self.spinningContainers.forEach(container => {
|
||||
if (
|
||||
container.contains(spinnerContainerWillCheck) &&
|
||||
container !== spinnerContainerWillCheck
|
||||
) {
|
||||
loading = false;
|
||||
}
|
||||
});
|
||||
|
||||
return loading;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
const store = SpinnerSharedStore.create({});
|
||||
|
||||
export class Spinner extends React.Component<
|
||||
SpinnerProps,
|
||||
{spinning: boolean; showMarker: boolean; idDarkBg: boolean}
|
||||
> {
|
||||
static defaultProps = {
|
||||
show: true,
|
||||
className: '',
|
||||
spinnerClassName: '',
|
||||
size: '' as '',
|
||||
icon: '',
|
||||
tip: '',
|
||||
tipPlacement: 'bottom' as 'bottom',
|
||||
delay: 0,
|
||||
overlay: false,
|
||||
loadingConfig: {},
|
||||
disabled: false
|
||||
};
|
||||
|
||||
state = {
|
||||
spinning: false,
|
||||
showMarker: true,
|
||||
idDarkBg: false
|
||||
};
|
||||
|
||||
parent: HTMLElement | null = null;
|
||||
|
||||
/**
|
||||
* 解决同级(same parent node) spinner 的 show 不全为 true 时
|
||||
* 标记 loading 是由当前组件触发的
|
||||
*/
|
||||
loadingTriggered: boolean = false;
|
||||
|
||||
spinnerRef = (dom: HTMLElement) => {
|
||||
if (dom) {
|
||||
this.parent = dom.parentNode as HTMLElement;
|
||||
}
|
||||
};
|
||||
|
||||
componentDidUpdate() {
|
||||
const showLoading =
|
||||
this.props.loadingConfig?.show === true ||
|
||||
typeof this.props.loadingConfig?.show === 'undefined';
|
||||
|
||||
if (this.parent && showLoading) {
|
||||
if (this.props.show) {
|
||||
this.loadingTriggered = true;
|
||||
store.push(this.parent);
|
||||
} else if (this.state.spinning && this.loadingTriggered) {
|
||||
this.loadingTriggered = false;
|
||||
store.remove(this.parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
if (this.parent && this.state.showMarker) {
|
||||
this.setState({showMarker: false});
|
||||
}
|
||||
if (this.parent) {
|
||||
const backgroundColor = getComputedStyle(this.parent).getPropertyValue(
|
||||
'background-color'
|
||||
);
|
||||
const rgba = backgroundColor.match(/\d+/g)?.map(Number) || [];
|
||||
|
||||
const brightness = (rgba[0] * 299 + rgba[1] * 587 + rgba[2] * 114) / 1000;
|
||||
rgba[3] = rgba[3] ?? 1; // 没有设置颜色时取到的是 rgba(0, 0, 0, 0)
|
||||
|
||||
if (brightness < 200 && rgba[3] > 0.4) {
|
||||
this.setState({idDarkBg: true});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
// 卸载 reaction
|
||||
this.loadingChecker();
|
||||
// 删除 当前 parent 元素
|
||||
store.remove(this.parent!);
|
||||
}
|
||||
|
||||
/**
|
||||
* 监控着 spinningContainers 的变化
|
||||
*/
|
||||
loadingChecker = reaction(
|
||||
() => store.spinningContainers.size,
|
||||
() => {
|
||||
if (this.parent) {
|
||||
this.setState({
|
||||
spinning: store.checkLoading(this.parent) && this.loadingTriggered
|
||||
});
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
renderBody() {
|
||||
const {
|
||||
classnames: cx,
|
||||
className,
|
||||
spinnerClassName,
|
||||
size = '',
|
||||
overlay,
|
||||
delay,
|
||||
icon: iconConfig,
|
||||
tip,
|
||||
tipPlacement = '',
|
||||
loadingConfig,
|
||||
disabled
|
||||
} = this.props;
|
||||
// 定义了挂载位置时只能使用默认icon
|
||||
const icon = loadingConfig?.root ? undefined : iconConfig;
|
||||
const isCustomIcon = icon && React.isValidElement(icon);
|
||||
const timeout = {enter: delay, exit: 0};
|
||||
|
||||
const showOverlay = loadingConfig?.root || overlay;
|
||||
|
||||
return (
|
||||
<>
|
||||
{this.state.showMarker && (
|
||||
<span className={cx('Spinner-mark')} ref={this.spinnerRef as any} />
|
||||
)}
|
||||
<Transition
|
||||
mountOnEnter
|
||||
unmountOnExit
|
||||
in={this.state.spinning}
|
||||
timeout={timeout}
|
||||
>
|
||||
{(status: string) => {
|
||||
return (
|
||||
<>
|
||||
{/* 遮罩层 */}
|
||||
{showOverlay ? (
|
||||
<div className={cx(`Spinner-overlay`, fadeStyles[status])} />
|
||||
) : null}
|
||||
|
||||
{/* spinner图标和文案 */}
|
||||
<div
|
||||
data-testid="spinner"
|
||||
className={cx(
|
||||
`Spinner`,
|
||||
tip && {
|
||||
[`Spinner-tip--${tipPlacement}`]: [
|
||||
'top',
|
||||
'right',
|
||||
'bottom',
|
||||
'left'
|
||||
].includes(tipPlacement)
|
||||
},
|
||||
{[`Spinner--overlay`]: showOverlay},
|
||||
fadeStyles[status],
|
||||
className
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={cx(
|
||||
`Spinner-icon`,
|
||||
{
|
||||
[`Spinner-icon--${size}`]: ['lg', 'sm'].includes(size),
|
||||
'Spinner-icon--default': !icon,
|
||||
'Spinner-icon--simple': !isCustomIcon && icon,
|
||||
'Spinner-icon--custom': isCustomIcon,
|
||||
'Spinner-icon--disabled': disabled
|
||||
},
|
||||
spinnerClassName,
|
||||
this.state.idDarkBg && 'Spinner-icon--darkBg'
|
||||
)}
|
||||
>
|
||||
{icon ? (
|
||||
<Icon cx={cx} icon={icon} className="icon" />
|
||||
) : null}
|
||||
</div>
|
||||
{tip ? <span className={cx(`Spinner-tip`)}>{tip}</span> : ''}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}}
|
||||
</Transition>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {loadingConfig} = this.props;
|
||||
|
||||
const spinnerBody = this.renderBody();
|
||||
const root = loadingConfig?.root;
|
||||
const dom = root ? document.querySelector(root) : null;
|
||||
|
||||
if (dom) {
|
||||
// TODO: 找到准确的 元素
|
||||
return ReactDOM.createPortal(spinnerBody, dom);
|
||||
}
|
||||
|
||||
return spinnerBody;
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(Spinner);
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user