UNPKG

2.48 kBJavaScriptView Raw
1import { __awaiter } from "tslib";
2import React, { forwardRef, useImperativeHandle, useRef, useState } from 'react';
3import classNames from 'classnames';
4import DotLoading from '../dot-loading';
5import { mergeProps } from '../../utils/with-default-props';
6import { withNativeProps } from '../../utils/native-props';
7import { isPromise } from '../../utils/validate';
8const classPrefix = `adm-button`;
9const defaultProps = {
10 color: 'default',
11 fill: 'solid',
12 block: false,
13 loading: false,
14 loadingIcon: React.createElement(DotLoading, {
15 color: 'currentColor'
16 }),
17 type: 'button',
18 shape: 'default',
19 size: 'middle'
20};
21export const Button = forwardRef((p, ref) => {
22 const props = mergeProps(defaultProps, p);
23 const [innerLoading, setInnerLoading] = useState(false);
24 const nativeButtonRef = useRef(null);
25 const loading = props.loading === 'auto' ? innerLoading : props.loading;
26 const disabled = props.disabled || loading;
27 useImperativeHandle(ref, () => ({
28 get nativeElement() {
29 return nativeButtonRef.current;
30 }
31 }));
32 const handleClick = e => __awaiter(void 0, void 0, void 0, function* () {
33 if (!props.onClick) return;
34 const promise = props.onClick(e);
35 if (isPromise(promise)) {
36 try {
37 setInnerLoading(true);
38 yield promise;
39 setInnerLoading(false);
40 } catch (e) {
41 setInnerLoading(false);
42 throw e;
43 }
44 }
45 });
46 return withNativeProps(props, React.createElement("button", {
47 ref: nativeButtonRef,
48 type: props.type,
49 onClick: handleClick,
50 className: classNames(classPrefix, {
51 [`${classPrefix}-${props.color}`]: props.color,
52 [`${classPrefix}-block`]: props.block,
53 [`${classPrefix}-disabled`]: disabled,
54 [`${classPrefix}-fill-outline`]: props.fill === 'outline',
55 [`${classPrefix}-fill-none`]: props.fill === 'none',
56 [`${classPrefix}-mini`]: props.size === 'mini',
57 [`${classPrefix}-small`]: props.size === 'small',
58 [`${classPrefix}-large`]: props.size === 'large',
59 [`${classPrefix}-loading`]: loading
60 }, `${classPrefix}-shape-${props.shape}`),
61 disabled: disabled,
62 onMouseDown: props.onMouseDown,
63 onMouseUp: props.onMouseUp,
64 onTouchStart: props.onTouchStart,
65 onTouchEnd: props.onTouchEnd
66 }, loading ? React.createElement("div", {
67 className: `${classPrefix}-loading-wrapper`
68 }, props.loadingIcon, props.loadingText) : React.createElement("span", null, props.children)));
69});
\No newline at end of file