ant-design/components/button/button.tsx

315 lines
9.1 KiB
TypeScript
Raw Normal View History

2019-08-05 18:38:10 +08:00
/* eslint-disable react/button-has-type */
import React, { Children, createRef, useContext, useEffect, useMemo, useState } from 'react';
import classNames from 'classnames';
import omit from 'rc-util/lib/omit';
import { composeRef } from 'rc-util/lib/ref';
import { devUseWarning } from '../_util/warning';
import Wave from '../_util/wave';
import { ConfigContext } from '../config-provider';
import DisabledContext from '../config-provider/DisabledContext';
import useSize from '../config-provider/hooks/useSize';
import type { SizeType } from '../config-provider/SizeContext';
feat: add Space.Compact (#37652) * feat: add Space.Compact * feat: update input style * feat: add CompactItem for context memoize * feat: add demo * feat: update button style * feat: update input style * feat: 提取 getCompactClassNames 公用方法 * feat: update button style * feat: update picker * feat: add block prop for Space.Compact * feat: use Space.Compact for Input#addonBefore/After * feat: update addon * refactor: compact * feat: update * feat: update * feat: migrate styles to compact for new Input/Input.Search * feat: organize input demo * feat: add more button compact demo * feat: resolve select border collapse * feat: fix input addon select style * feat: add input addon demo in Space * feat: add useCompactItemContext hook * feat: update compact-item style * feat: rollback input#addon implements * feat: rollback input#addon and input.search style * feat: select border collapse * feat: add Space.Compact demo * feat: Space.Compact vertical for Button * refactor: useCompactItemContext * feat: update Button vertical demo * feat: rtl for compact mixin * feat: rtl for compact button * feat: input rtl * feat: add docs for Space.Compact * test: add some tests for Space.Compact * test: add tests * feat: select style * feat: handle select focus style * feat: add useCompactItemContext for Picker and Cascader * style: add compact-item style for cascader * feat: support nested Space.Compact * style: Input.Search in Space.Compact * chore: clean * feat: add useCompactItemContext for TreeSelect * fix: lint issues * fix: style lint * docs: update demos for Space.Compact * docs: update demo * fix: add deps-lint-skip for space * fix: add deps-lint-skip for space * fix: handle edge case for useCompactItemContext * test: add search test case * chore: + bundlesize * style: merge button compact style into one file * style: improve style for nested compact * fix: stylelint * docs: update Space.Compact docs * test: update demo snapshot * test: update input debug test snapshot * docs: update doccs for Space.Compact * test: improve test cases for Compact * docs: clean demos for Compact * refactor: improve Space.Compact * fix: add useCompactItemContext for Input.Search * style: improve compact border-radius implementation * refactor: use context to make nested compact works * fix: input-number focused style * refactor: remove useless style * refactor: improve style for vertical compact * test: update snapshot * test: update snapshot for input * refactor: improve compact-item-border-radius * fix: search group in RTL * style: improve style for button compact * style: use after * fix: stylelint * chore: update snapshot * style: improve button compact * refactor: improve btn-icon-only style in compact
2022-10-18 16:23:10 +08:00
import { useCompactItemContext } from '../space/Compact';
import Group, { GroupSizeContext } from './button-group';
import type { ButtonHTMLType, ButtonShape, ButtonType } from './buttonHelpers';
import { isTwoCNChar, isUnBorderedButtonType, spaceChildren } from './buttonHelpers';
import IconWrapper from './IconWrapper';
import LoadingIcon from './LoadingIcon';
import useStyle from './style';
import CompactCmp from './style/compactCmp';
export type LegacyButtonType = ButtonType | 'danger';
2018-05-18 18:22:33 +08:00
export interface BaseButtonProps {
2016-07-14 13:29:50 +08:00
type?: ButtonType;
use ant design icons 4.0 (#18217) * feat: use @ant-design/icons@4.0 * feat: use createFromIconfontCN to make site works * feat: update doc for Icon * feat: use icon in component Alert * feat: use icon in component Avatar * feat: use icon in component Breadcrumb * feat: use icon in component Button * feat: use icon in component Cascader * feat: use icon in component Collapse * feat: use icon in component Datepicker * feat: use icon in component Dropdown * feat: use icon in component Form * feat: use icon in component Input * feat: use icon in component InputNumber * feat: use icon in component Layout * feat: use icon in component Mention * feat: use icon in component Message * feat: use icon in component Modal * feat: use icon in component Notification * feat: use icon in component PageHeader * feat: use icon in component Pagination * feat: use icon in component Popconfirm * feat: use icon in component Progress * feat: use icon in component Rate * feat: use icon in component Result * feat: use icon in component Select * feat: use icon in component Step * feat: use icon in component Switch * feat: use icon in component Table * feat: use icon in component Tab * feat: use icon in component Tag * feat: handle rest component which using Icon * fix: remove unused vars * feat: use latest alpha ant design icons * fix: failed test in uploadlist.test.js * test: update snapshot for icons * doc: add Icon for site * doc: use @ant-design/icons in site * chore: use latest icons * fix: tslint issue * fix: test cases * fix: types for react * fix: lint rules for import orders * fix: use @ant-design/icons@4.0.0-alpha.5 to avoid insert css in server render * fix: eslint error in demo/**.md * inject antd icons * update snapshot * fix site * doc: update docs * fix: code snippets icon in site * feat: use latest @ant-design/icons * fix: icon props in message
2019-08-13 14:07:17 +08:00
icon?: React.ReactNode;
feat: Support iconPosition with button icon (#47791) * feat: button support iconPosition * fix: iconPosition compatible LoadingIcon * docs(Button): update Button with iconPosition demo * fix: delete debug type * fix: iconPosition for InnerLoadingIcon with not existIcon * chore: update button snapshots * fix: fixed loading-icon-end style * chore: refactor buttonContent with genButtonContent * fix: iconPosition compatible with rtl * docs(Button): update button with iconPosition demo * chore: update test * fix: iconPosition compatible with rtl * docs(Buttob): add icon-position demo * restore icon demo * update snapshots * docs: update icon button demo * docs: update iconPosition button demo * Update components/button/index.zh-CN.md Co-authored-by: kiner-tang <1127031143@qq.com> Signed-off-by: George H <default_hyn@163.com> * Update components/button/index.zh-CN.md Co-authored-by: kiner-tang <1127031143@qq.com> Signed-off-by: George H <default_hyn@163.com> * Update components/button/demo/icon-position.md Co-authored-by: afc163 <afc163@gmail.com> Signed-off-by: George H <default_hyn@163.com> * Update components/button/index.en-US.md Co-authored-by: afc163 <afc163@gmail.com> Signed-off-by: George H <default_hyn@163.com> * Update components/button/index.en-US.md Co-authored-by: afc163 <afc163@gmail.com> Signed-off-by: George H <default_hyn@163.com> --------- Signed-off-by: George H <default_hyn@163.com> Co-authored-by: kiner-tang <1127031143@qq.com> Co-authored-by: afc163 <afc163@gmail.com>
2024-04-07 22:42:20 +08:00
iconPosition?: 'start' | 'end';
2016-07-14 13:29:50 +08:00
shape?: ButtonShape;
size?: SizeType;
disabled?: boolean;
loading?: boolean | { delay?: number };
2016-07-14 13:29:50 +08:00
prefixCls?: string;
className?: string;
rootClassName?: string;
ghost?: boolean;
2019-11-22 15:32:11 +08:00
danger?: boolean;
block?: boolean;
children?: React.ReactNode;
[key: `data-${string}`]: string;
classNames?: { icon: string };
styles?: { icon: React.CSSProperties };
2016-07-14 13:29:50 +08:00
}
type MergedHTMLAttributes = Omit<
2023-07-21 23:36:11 +08:00
React.HTMLAttributes<HTMLElement> &
React.ButtonHTMLAttributes<HTMLElement> &
React.AnchorHTMLAttributes<HTMLElement>,
'type'
>;
2023-07-18 23:59:53 +08:00
export interface ButtonProps extends BaseButtonProps, MergedHTMLAttributes {
href?: string;
htmlType?: ButtonHTMLType;
autoInsertSpace?: boolean;
}
type LoadingConfigType = {
loading: boolean;
delay: number;
};
function getLoadingConfig(loading: BaseButtonProps['loading']): LoadingConfigType {
if (typeof loading === 'object' && loading) {
let delay = loading?.delay;
delay = !Number.isNaN(delay) && typeof delay === 'number' ? delay : 0;
return {
loading: delay <= 0,
delay,
};
}
return {
loading: !!loading,
delay: 0,
};
}
const InternalCompoundedButton = React.forwardRef<
HTMLButtonElement | HTMLAnchorElement,
ButtonProps
>((props, ref) => {
2020-06-02 12:54:22 +08:00
const {
loading = false,
2020-06-02 12:54:22 +08:00
prefixCls: customizePrefixCls,
2024-02-27 19:11:46 +08:00
type,
danger = false,
shape = 'default',
2020-06-02 12:54:22 +08:00
size: customizeSize,
styles,
disabled: customDisabled,
2020-06-02 12:54:22 +08:00
className,
rootClassName,
2020-06-02 12:54:22 +08:00
children,
icon,
feat: Support iconPosition with button icon (#47791) * feat: button support iconPosition * fix: iconPosition compatible LoadingIcon * docs(Button): update Button with iconPosition demo * fix: delete debug type * fix: iconPosition for InnerLoadingIcon with not existIcon * chore: update button snapshots * fix: fixed loading-icon-end style * chore: refactor buttonContent with genButtonContent * fix: iconPosition compatible with rtl * docs(Button): update button with iconPosition demo * chore: update test * fix: iconPosition compatible with rtl * docs(Buttob): add icon-position demo * restore icon demo * update snapshots * docs: update icon button demo * docs: update iconPosition button demo * Update components/button/index.zh-CN.md Co-authored-by: kiner-tang <1127031143@qq.com> Signed-off-by: George H <default_hyn@163.com> * Update components/button/index.zh-CN.md Co-authored-by: kiner-tang <1127031143@qq.com> Signed-off-by: George H <default_hyn@163.com> * Update components/button/demo/icon-position.md Co-authored-by: afc163 <afc163@gmail.com> Signed-off-by: George H <default_hyn@163.com> * Update components/button/index.en-US.md Co-authored-by: afc163 <afc163@gmail.com> Signed-off-by: George H <default_hyn@163.com> * Update components/button/index.en-US.md Co-authored-by: afc163 <afc163@gmail.com> Signed-off-by: George H <default_hyn@163.com> --------- Signed-off-by: George H <default_hyn@163.com> Co-authored-by: kiner-tang <1127031143@qq.com> Co-authored-by: afc163 <afc163@gmail.com>
2024-04-07 22:42:20 +08:00
iconPosition = 'start',
ghost = false,
block = false,
// React does not recognize the `htmlType` prop on a DOM element. Here we pick it out of `rest`.
htmlType = 'button',
classNames: customClassNames,
style: customStyle = {},
autoInsertSpace,
2020-06-02 12:54:22 +08:00
...rest
} = props;
2020-06-02 12:54:22 +08:00
2024-02-27 19:11:46 +08:00
// https://github.com/ant-design/ant-design/issues/47605
// Compatible with original `type` behavior
const mergedType = type || 'default';
const { getPrefixCls, direction, button } = useContext(ConfigContext);
const mergedInsertSpace = autoInsertSpace ?? button?.autoInsertSpace ?? true;
const prefixCls = getPrefixCls('btn', customizePrefixCls);
const [wrapCSSVar, hashId, cssVarCls] = useStyle(prefixCls);
const disabled = useContext(DisabledContext);
const mergedDisabled = customDisabled ?? disabled;
const groupSize = useContext(GroupSizeContext);
2023-04-26 14:52:21 +08:00
const loadingOrDelay = useMemo<LoadingConfigType>(() => getLoadingConfig(loading), [loading]);
2023-04-26 14:52:21 +08:00
const [innerLoading, setLoading] = useState<boolean>(loadingOrDelay.loading);
const [hasTwoCNChar, setHasTwoCNChar] = useState<boolean>(false);
const internalRef = createRef<HTMLButtonElement | HTMLAnchorElement>();
2016-07-14 13:29:50 +08:00
const buttonRef = composeRef(ref, internalRef);
2024-02-27 19:11:46 +08:00
const needInserted =
Children.count(children) === 1 && !icon && !isUnBorderedButtonType(mergedType);
useEffect(() => {
let delayTimer: ReturnType<typeof setTimeout> | null = null;
if (loadingOrDelay.delay > 0) {
2023-04-26 14:52:21 +08:00
delayTimer = setTimeout(() => {
delayTimer = null;
setLoading(true);
}, loadingOrDelay.delay);
2020-06-02 12:54:22 +08:00
} else {
setLoading(loadingOrDelay.loading);
}
function cleanupTimer() {
if (delayTimer) {
2023-04-26 14:52:21 +08:00
clearTimeout(delayTimer);
delayTimer = null;
}
}
return cleanupTimer;
2020-06-03 21:59:54 +08:00
}, [loadingOrDelay]);
2016-05-28 15:31:39 +08:00
useEffect(() => {
// FIXME: for HOC usage like <FormatMessage />
if (!buttonRef || !(buttonRef as any).current || !mergedInsertSpace) {
return;
}
const buttonText = (buttonRef as any).current.textContent;
if (needInserted && isTwoCNChar(buttonText)) {
if (!hasTwoCNChar) {
setHasTwoCNChar(true);
}
} else if (hasTwoCNChar) {
setHasTwoCNChar(false);
}
}, [buttonRef]);
2018-10-30 16:08:55 +08:00
const handleClick = (e: React.MouseEvent<HTMLButtonElement | HTMLAnchorElement, MouseEvent>) => {
const { onClick } = props;
// FIXME: https://github.com/ant-design/ant-design/issues/30207
if (innerLoading || mergedDisabled) {
e.preventDefault();
2019-08-05 18:38:10 +08:00
return;
}
(onClick as React.MouseEventHandler<HTMLButtonElement | HTMLAnchorElement>)?.(e);
2019-08-05 18:38:10 +08:00
};
if (process.env.NODE_ENV !== 'production') {
const warning = devUseWarning('Button');
warning(
!(typeof icon === 'string' && icon.length > 2),
'breaking',
`\`icon\` is using ReactNode instead of string naming in v4. Please check \`${icon}\` at https://ant.design/components/icon`,
);
warning(
2024-02-27 19:11:46 +08:00
!(ghost && isUnBorderedButtonType(mergedType)),
'usage',
"`link` or `text` button can't be a `ghost` button.",
);
}
feat: add Space.Compact (#37652) * feat: add Space.Compact * feat: update input style * feat: add CompactItem for context memoize * feat: add demo * feat: update button style * feat: update input style * feat: 提取 getCompactClassNames 公用方法 * feat: update button style * feat: update picker * feat: add block prop for Space.Compact * feat: use Space.Compact for Input#addonBefore/After * feat: update addon * refactor: compact * feat: update * feat: update * feat: migrate styles to compact for new Input/Input.Search * feat: organize input demo * feat: add more button compact demo * feat: resolve select border collapse * feat: fix input addon select style * feat: add input addon demo in Space * feat: add useCompactItemContext hook * feat: update compact-item style * feat: rollback input#addon implements * feat: rollback input#addon and input.search style * feat: select border collapse * feat: add Space.Compact demo * feat: Space.Compact vertical for Button * refactor: useCompactItemContext * feat: update Button vertical demo * feat: rtl for compact mixin * feat: rtl for compact button * feat: input rtl * feat: add docs for Space.Compact * test: add some tests for Space.Compact * test: add tests * feat: select style * feat: handle select focus style * feat: add useCompactItemContext for Picker and Cascader * style: add compact-item style for cascader * feat: support nested Space.Compact * style: Input.Search in Space.Compact * chore: clean * feat: add useCompactItemContext for TreeSelect * fix: lint issues * fix: style lint * docs: update demos for Space.Compact * docs: update demo * fix: add deps-lint-skip for space * fix: add deps-lint-skip for space * fix: handle edge case for useCompactItemContext * test: add search test case * chore: + bundlesize * style: merge button compact style into one file * style: improve style for nested compact * fix: stylelint * docs: update Space.Compact docs * test: update demo snapshot * test: update input debug test snapshot * docs: update doccs for Space.Compact * test: improve test cases for Compact * docs: clean demos for Compact * refactor: improve Space.Compact * fix: add useCompactItemContext for Input.Search * style: improve compact border-radius implementation * refactor: use context to make nested compact works * fix: input-number focused style * refactor: remove useless style * refactor: improve style for vertical compact * test: update snapshot * test: update snapshot for input * refactor: improve compact-item-border-radius * fix: search group in RTL * style: improve style for button compact * style: use after * fix: stylelint * chore: update snapshot * style: improve button compact * refactor: improve btn-icon-only style in compact
2022-10-18 16:23:10 +08:00
const { compactSize, compactItemClassnames } = useCompactItemContext(prefixCls, direction);
const sizeClassNameMap = { large: 'lg', small: 'sm', middle: undefined };
const sizeFullName = useSize((ctxSize) => customizeSize ?? compactSize ?? groupSize ?? ctxSize);
const sizeCls = sizeFullName ? sizeClassNameMap[sizeFullName] || '' : '';
2020-06-02 12:54:22 +08:00
const iconType = innerLoading ? 'loading' : icon;
const linkButtonRestProps = omit(rest as ButtonProps & { navigate: any }, ['navigate']);
const classes = classNames(
prefixCls,
hashId,
cssVarCls,
{
[`${prefixCls}-${shape}`]: shape !== 'default' && shape,
2024-02-27 19:11:46 +08:00
[`${prefixCls}-${mergedType}`]: mergedType,
[`${prefixCls}-${sizeCls}`]: sizeCls,
2021-04-02 22:37:36 +08:00
[`${prefixCls}-icon-only`]: !children && children !== 0 && !!iconType,
2024-02-27 19:11:46 +08:00
[`${prefixCls}-background-ghost`]: ghost && !isUnBorderedButtonType(mergedType),
[`${prefixCls}-loading`]: innerLoading,
[`${prefixCls}-two-chinese-chars`]: hasTwoCNChar && mergedInsertSpace && !innerLoading,
[`${prefixCls}-block`]: block,
[`${prefixCls}-dangerous`]: danger,
[`${prefixCls}-rtl`]: direction === 'rtl',
[`${prefixCls}-icon-end`]: iconPosition === 'end',
},
feat: add Space.Compact (#37652) * feat: add Space.Compact * feat: update input style * feat: add CompactItem for context memoize * feat: add demo * feat: update button style * feat: update input style * feat: 提取 getCompactClassNames 公用方法 * feat: update button style * feat: update picker * feat: add block prop for Space.Compact * feat: use Space.Compact for Input#addonBefore/After * feat: update addon * refactor: compact * feat: update * feat: update * feat: migrate styles to compact for new Input/Input.Search * feat: organize input demo * feat: add more button compact demo * feat: resolve select border collapse * feat: fix input addon select style * feat: add input addon demo in Space * feat: add useCompactItemContext hook * feat: update compact-item style * feat: rollback input#addon implements * feat: rollback input#addon and input.search style * feat: select border collapse * feat: add Space.Compact demo * feat: Space.Compact vertical for Button * refactor: useCompactItemContext * feat: update Button vertical demo * feat: rtl for compact mixin * feat: rtl for compact button * feat: input rtl * feat: add docs for Space.Compact * test: add some tests for Space.Compact * test: add tests * feat: select style * feat: handle select focus style * feat: add useCompactItemContext for Picker and Cascader * style: add compact-item style for cascader * feat: support nested Space.Compact * style: Input.Search in Space.Compact * chore: clean * feat: add useCompactItemContext for TreeSelect * fix: lint issues * fix: style lint * docs: update demos for Space.Compact * docs: update demo * fix: add deps-lint-skip for space * fix: add deps-lint-skip for space * fix: handle edge case for useCompactItemContext * test: add search test case * chore: + bundlesize * style: merge button compact style into one file * style: improve style for nested compact * fix: stylelint * docs: update Space.Compact docs * test: update demo snapshot * test: update input debug test snapshot * docs: update doccs for Space.Compact * test: improve test cases for Compact * docs: clean demos for Compact * refactor: improve Space.Compact * fix: add useCompactItemContext for Input.Search * style: improve compact border-radius implementation * refactor: use context to make nested compact works * fix: input-number focused style * refactor: remove useless style * refactor: improve style for vertical compact * test: update snapshot * test: update snapshot for input * refactor: improve compact-item-border-radius * fix: search group in RTL * style: improve style for button compact * style: use after * fix: stylelint * chore: update snapshot * style: improve button compact * refactor: improve btn-icon-only style in compact
2022-10-18 16:23:10 +08:00
compactItemClassnames,
className,
rootClassName,
button?.className,
);
const fullStyle: React.CSSProperties = { ...button?.style, ...customStyle };
const iconClasses = classNames(customClassNames?.icon, button?.classNames?.icon);
const iconStyle: React.CSSProperties = {
...(styles?.icon || {}),
...(button?.styles?.icon || {}),
};
const iconNode =
2020-06-02 12:54:22 +08:00
icon && !innerLoading ? (
<IconWrapper prefixCls={prefixCls} className={iconClasses} style={iconStyle}>
{icon}
</IconWrapper>
) : (
2024-06-02 21:48:48 +08:00
<LoadingIcon existIcon={!!icon} prefixCls={prefixCls} loading={innerLoading} />
);
const kids =
children || children === 0 ? spaceChildren(children, needInserted && mergedInsertSpace) : null;
if (linkButtonRestProps.href !== undefined) {
return wrapCSSVar(
<a
{...linkButtonRestProps}
className={classNames(classes, {
[`${prefixCls}-disabled`]: mergedDisabled,
})}
href={mergedDisabled ? undefined : linkButtonRestProps.href}
style={fullStyle}
onClick={handleClick}
ref={buttonRef as React.Ref<HTMLAnchorElement>}
tabIndex={mergedDisabled ? -1 : 0}
>
{iconNode}
{kids}
</a>,
);
}
2019-08-05 18:38:10 +08:00
let buttonNode = (
<button
{...rest}
type={htmlType}
className={classes}
style={fullStyle}
onClick={handleClick}
disabled={mergedDisabled}
ref={buttonRef as React.Ref<HTMLButtonElement>}
>
{iconNode}
{kids}
{/* Styles: compact */}
2024-01-17 22:28:15 +08:00
{!!compactItemClassnames && <CompactCmp key="compact" prefixCls={prefixCls} />}
</button>
);
2024-02-27 19:11:46 +08:00
if (!isUnBorderedButtonType(mergedType)) {
buttonNode = (
<Wave component="Button" disabled={innerLoading}>
{buttonNode}
</Wave>
);
}
return wrapCSSVar(buttonNode);
});
type CompoundedComponent = typeof InternalCompoundedButton & {
Group: typeof Group;
/** @internal */
__ANT_BUTTON: boolean;
};
const Button = InternalCompoundedButton as CompoundedComponent;
Button.Group = Group;
Button.__ANT_BUTTON = true;
if (process.env.NODE_ENV !== 'production') {
Button.displayName = 'Button';
}
export default Button;