ant-design/components/cascader/index.tsx

386 lines
12 KiB
TypeScript
Raw Normal View History

import * as React from 'react';
2015-12-29 18:31:48 +08:00
import classNames from 'classnames';
import type {
BaseOptionType,
DefaultOptionType,
FieldNames,
MultipleCascaderProps as RcMultipleCascaderProps,
2023-12-22 10:05:15 +08:00
SingleCascaderProps as RcSingleCascaderProps,
ShowSearchType,
} from 'rc-cascader';
import RcCascader from 'rc-cascader';
import type { Placement } from 'rc-select/lib/BaseSelect';
import omit from 'rc-util/lib/omit';
import { useZIndex } from '../_util/hooks/useZIndex';
import type { SelectCommonPlacement } from '../_util/motion';
import { getTransitionName } from '../_util/motion';
import genPurePanel from '../_util/PurePanel';
import type { InputStatus } from '../_util/statusUtils';
import { getMergedStatus, getStatusClassNames } from '../_util/statusUtils';
import { devUseWarning } from '../_util/warning';
import { ConfigContext } from '../config-provider';
import DefaultRenderEmpty from '../config-provider/defaultRenderEmpty';
import DisabledContext from '../config-provider/DisabledContext';
import useCSSVarCls from '../config-provider/hooks/useCSSVarCls';
import useSize from '../config-provider/hooks/useSize';
import type { SizeType } from '../config-provider/SizeContext';
import { FormItemInputContext } from '../form/context';
2024-01-03 08:54:15 +08:00
import type { Variant } from '../form/hooks/useVariants';
import useVariant from '../form/hooks/useVariants';
import mergedBuiltinPlacements from '../select/mergedBuiltinPlacements';
2022-06-21 19:40:22 +08:00
import useSelectStyle from '../select/style';
import useIcons from '../select/useIcons';
import useShowArrow from '../select/useShowArrow';
import { useCompactItemContext } from '../space/Compact';
import useBase from './hooks/useBase';
import useCheckable from './hooks/useCheckable';
import useColumnIcons from './hooks/useColumnIcons';
import CascaderPanel from './Panel';
import useStyle from './style';
2015-12-29 11:46:13 +08:00
// Align the design since we use `rc-select` in root. This help:
// - List search content will show all content
// - Hover opacity style
// - Search filter match case
export type { BaseOptionType, DefaultOptionType };
export type FieldNamesType = FieldNames;
export type FilledFieldNamesType = Required<FieldNamesType>;
const { SHOW_CHILD, SHOW_PARENT } = RcCascader;
function highlightKeyword(str: string, lowerKeyword: string, prefixCls?: string) {
const cells = str
.toLowerCase()
.split(lowerKeyword)
.reduce<string[]>(
(list, cur, index) => (index === 0 ? [cur] : [...list, lowerKeyword, cur]),
[],
);
const fillCells: React.ReactNode[] = [];
let start = 0;
cells.forEach((cell, index) => {
const end = start + cell.length;
let originWorld: React.ReactNode = str.slice(start, end);
start = end;
if (index % 2 === 1) {
originWorld = (
// eslint-disable-next-line react/no-array-index-key
<span className={`${prefixCls}-menu-item-keyword`} key={`separator-${index}`}>
{originWorld}
</span>
);
}
fillCells.push(originWorld);
});
return fillCells;
}
const defaultSearchRender: ShowSearchType['render'] = (inputValue, path, prefixCls, fieldNames) => {
const optionList: React.ReactNode[] = [];
// We do lower here to save perf
const lower = inputValue.toLowerCase();
path.forEach((node, index) => {
if (index !== 0) {
optionList.push(' / ');
}
let label = node[fieldNames.label!];
const type = typeof label;
if (type === 'string' || type === 'number') {
label = highlightKeyword(String(label), lower, prefixCls);
}
2016-10-24 12:04:26 +08:00
optionList.push(label);
});
return optionList;
};
export type SingleCascaderProps<OptionType extends BaseOptionType = any> = Omit<
RcSingleCascaderProps<OptionType>,
'checkable' | 'options'
> & {
multiple?: false;
};
export type MultipleCascaderProps<OptionType extends BaseOptionType = any> = Omit<
RcMultipleCascaderProps<OptionType>,
'checkable' | 'options'
> & {
multiple: true;
};
type UnionCascaderProps<OptionType extends BaseOptionType> =
| SingleCascaderProps<OptionType>
| MultipleCascaderProps<OptionType>;
export type CascaderProps<DataNodeType extends BaseOptionType = any> =
UnionCascaderProps<DataNodeType> & {
multiple?: boolean;
size?: SizeType;
/**
* @deprecated `showArrow` is deprecated which will be removed in next major version. It will be a
* default behavior, you can hide it by setting `suffixIcon` to null.
*/
showArrow?: boolean;
disabled?: boolean;
/** @deprecated Use `variant` instead. */
bordered?: boolean;
placement?: SelectCommonPlacement;
suffixIcon?: React.ReactNode;
options?: DataNodeType[];
status?: InputStatus;
autoClearSearchValue?: boolean;
rootClassName?: string;
popupClassName?: string;
/** @deprecated Please use `popupClassName` instead */
dropdownClassName?: string;
/**
* @since 5.13.0
* @default "outlined"
*/
2023-12-22 10:05:15 +08:00
variant?: Variant;
};
export interface CascaderRef {
focus: () => void;
blur: () => void;
}
const Cascader = React.forwardRef<CascaderRef, CascaderProps<any>>((props, ref) => {
const {
prefixCls: customizePrefixCls,
size: customizeSize,
disabled: customDisabled,
className,
rootClassName,
multiple,
bordered = true,
transitionName,
choiceTransitionName = '',
popupClassName,
dropdownClassName,
expandIcon,
placement,
showSearch,
allowClear = true,
notFoundContent,
direction,
getPopupContainer,
status: customStatus,
showArrow,
builtinPlacements,
style,
variant: customVariant,
...rest
} = props;
const restProps = omit(rest, ['suffixIcon']);
const {
getPopupContainer: getContextPopupContainer,
getPrefixCls,
popupOverflow,
cascader,
} = React.useContext(ConfigContext);
// =================== Form =====================
const {
status: contextStatus,
hasFeedback,
isFormItemInput,
feedbackIcon,
} = React.useContext(FormItemInputContext);
const mergedStatus = getMergedStatus(contextStatus, customStatus);
// =================== Warning =====================
if (process.env.NODE_ENV !== 'production') {
const warning = devUseWarning('Cascader');
warning.deprecated(!dropdownClassName, 'dropdownClassName', 'popupClassName');
warning(
!('showArrow' in props),
'deprecated',
'`showArrow` is deprecated which will be removed in next major version. It will be a default behavior, you can hide it by setting `suffixIcon` to null.',
);
warning.deprecated(!('bordered' in props), 'bordered', 'variant');
}
// ==================== Prefix =====================
const [prefixCls, cascaderPrefixCls, mergedDirection, renderEmpty] = useBase(
customizePrefixCls,
direction,
);
const isRtl = mergedDirection === 'rtl';
const rootPrefixCls = getPrefixCls();
const rootCls = useCSSVarCls(prefixCls);
const [wrapSelectCSSVar, hashId, cssVarCls] = useSelectStyle(prefixCls, rootCls);
const cascaderRootCls = useCSSVarCls(cascaderPrefixCls);
const [wrapCascaderCSSVar] = useStyle(cascaderPrefixCls, cascaderRootCls);
2022-03-09 00:29:00 +08:00
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);
2023-12-22 10:05:15 +08:00
const [variant, enableVariantCls] = useVariant(customVariant, bordered);
// =================== No Found ====================
const mergedNotFoundContent = notFoundContent || renderEmpty?.('Cascader') || (
<DefaultRenderEmpty componentName="Cascader" />
);
// =================== Dropdown ====================
const mergedDropdownClassName = classNames(
popupClassName || dropdownClassName,
`${cascaderPrefixCls}-dropdown`,
{
[`${cascaderPrefixCls}-dropdown-rtl`]: mergedDirection === 'rtl',
},
rootClassName,
rootCls,
cascaderRootCls,
2022-03-09 00:29:00 +08:00
hashId,
cssVarCls,
);
// ==================== Search =====================
const mergedShowSearch = React.useMemo(() => {
if (!showSearch) {
return showSearch;
}
let searchConfig: ShowSearchType = {
render: defaultSearchRender,
2015-12-29 11:46:13 +08:00
};
if (typeof showSearch === 'object') {
searchConfig = {
...searchConfig,
...showSearch,
};
}
return searchConfig;
}, [showSearch]);
2019-08-05 18:38:10 +08:00
// ===================== Size ======================
const mergedSize = useSize((ctx) => customizeSize ?? compactSize ?? ctx);
// ===================== Disabled =====================
const disabled = React.useContext(DisabledContext);
const mergedDisabled = customDisabled ?? disabled;
// ===================== Icon ======================
const [mergedExpandIcon, loadingIcon] = useColumnIcons(prefixCls, isRtl, expandIcon);
// =================== Multiple ====================
const checkable = useCheckable(cascaderPrefixCls, multiple);
// ===================== Icons =====================
const showSuffixIcon = useShowArrow(props.suffixIcon, showArrow);
const { suffixIcon, removeIcon, clearIcon } = useIcons({
...props,
hasFeedback,
feedbackIcon,
showSuffixIcon,
multiple,
prefixCls,
componentName: 'Cascader',
});
feat: added rtl direction to all of ant-design components (#19380) * rtl demo change en-us description * change bundlesize css limit * RTL: modal component (exclude confirm) * RTL: table component * RTL: pagination component * cleanup rtl demo * fix pagination.tsx compile error * RTL: button and button-group * RTL: Steps component * fix rtl demo style * fix input suffix icon alignment * fix select component arrow issue * RTL: form component * add pagination rtl test * fix test lint error * RTL: rate component * RTL: radio and radio group components * RTL: tree-select component * some fixes to RTL components * RTL: badge component * fix rtl issue in inline form * fix input component rtl padding issue * fix switch component text rtl issue * fix table grouped header text-align * add rtl support to whole demo with RTL button * Update rtl demo responsive * RTL: page-header component * RTL: typography component * RTL: Dropdown (Partial) * update config-provider doc * RTL: input component * RTL: select component * RTL: switch component * RTL: tree component * fix rtl demo lint * rtl demo change en-us description * RTL: modal component (exclude confirm) * RTL: table component * RTL: pagination component * cleanup rtl demo * RTL: button and button-group * RTL: Steps component * fix rtl demo style * fix input suffix icon alignment * RTL: form component * RTL: rate component * RTL: radio and radio group components * RTL: tree-select component * RTL: badge component * fix rtl issue in inline form * fix input component rtl padding issue * add rtl support to whole demo with RTL button * fix lost changes after rebase * fix lint errors * RTL: Transfer Component * RTL: upload component * RTL: update avatar demo * RTL: comment component * RTL: collapse component * RTL: carousel component * update snapshots * RTL: Card component * RTL: descriptions component * RTL: Empty component * RTL: list component * RTL: slider component * slider component import/order * add shared rtlTest * RTL: Statistic component * RTL: tooltip components * RTL: popover component * RTL: timeline component * RTL: tag component * RTL: alert component * RTL: drawer component * RTL: Tab component * change direction definition * RTL: progress component * input.tsx, remove duplicate after rebase * fix demo.less after rebase * fix ant-row-rtl after rebase * fix upload issues in rtl * badge rtl demo margin fix * fix: tabs with icon margin * fix: radio-wrapper margin * fix: table component after rebase * fix: centered modal text-align * update slider snapshot * RTL: popconfirm component * RTL: back-top component * RTL: spin component * RTL: result component * RTL: skeleton component * RTL: menu component * RTL: time-picker component * RTL: calendar component * RTL: date-picker component * RTL: home page * update snapshots * test: add auto-complete rtl test * test: add avatar component rtl tests * test: add badge component rtl tests * test: add breadcrumb component rtl tests * test: add button components rtl tests * test: add card component rtl tests * test: add carousel component rtl tests * test: add cascader component rtl tests * test: add checkbox component rtl tests * test: add collapse component rtl tests * test: add comment component rtl tests * test: add dropdown component rtl tests * test: add empty component rtl tests * test: add form component rtl tests * test: add grid component rtl tests * test: add input component rtl tests * test: add search component rtl tests * test: add input-number component rtl tests * test: add layout component rtl tests * test: add list component rtl tests * test: add mentions component rtl tests * test: add modal component rtl tests * test: add page-header component rtl tests * test: add pagination component rtl tests * test: add radio component rtl tests * test: add rate component rtl tests * test: add select component rtl tests * test: add slider component rtl tests * test: add steps component rtl tests * test: add switch component rtl tests * test: add table component rtl tests * test: add transfer component rtl tests * test: add tree component rtl tests * test: add tree-select component rtl tests * test: add typography component rtl tests * test: add upload component rtl tests * test: add affix component rtl tests * update calendar tests * increase css file maxSize * update snapshots * remove workflows to allow push * remove duplicate reverse prop from slider * fix: remove table demo from config-provider * fix: remove table demo from config-provider * fix lint error * Added direction property to ConfigProvider * cascader rtl tests added * update config-provider doc * RTL: grid system * RTL: input component * RTL: switch component * fix rtl demo lint * RTL: modal component (exclude confirm) * RTL: table component * RTL: pagination component * cleanup rtl demo * fix pagination.tsx compile error * RTL: button and button-group * RTL: Steps component * fix rtl demo style * RTL: form component * add pagination rtl test * RTL: rate component * RTL: radio and radio group components * RTL: tree-select component * RTL: badge component * fix rtl issue in inline form * fix input component rtl padding issue * add rtl support to whole demo with RTL button * RTL: input component * RTL: select component * RTL: switch component * RTL: tree component * fix rtl demo lint * rtl demo change en-us description * RTL: modal component (exclude confirm) * RTL: table component * RTL: pagination component * cleanup rtl demo * RTL: button and button-group * RTL: Steps component * fix rtl demo style * fix input suffix icon alignment * RTL: form component * RTL: rate component * RTL: radio and radio group components * RTL: tree-select component * RTL: badge component * fix rtl issue in inline form * fix input component rtl padding issue * add rtl support to whole demo with RTL button * input.tsx, remove duplicate after rebase * fix ant-row-rtl after rebase * update snapshots * test: add cascader component rtl tests * test: add pagination component rtl tests * update calendar tests * update snapshots * fix: remove table demo from config-provider * fix: remove table demo from config-provider * fix lint error * update direction.md icons * dropdown and cascader default placement in rtl * update snapshots * fix lint errors * remove duplicate import * update snapshots * update snapshot * update calendar snapshot * update snapshots * integrate with new rc-picker * update snapshots * fix lint errors * update snapshot * update snapshots * update snapshots * update snapshots :| * update snapshots * fix compile error. * fix typo after rebase * update snapshots * remove workflows to allow push * update snapshots * update snapshots * fix dist error * front-page css fix * update snapshots * fix lint and test issues * restore cascader index.less * update snapshots * fix logo in rtl and demo controls * ci errors * resolve steps/index.tsx conflicts * tooltip family demo remove inline style * resolve table/Table.tsx conflicts * resolve modal/Modal.tsx conflicts * resolve cascader/index.tsx conflicts * add workflows from upstream * update snapshots * revert logo to default * fix codebox demo direction of placements * resolve tooltip overlayClassName conflicts * update snapshots * update popover test * fix: cascader miss popupClassName * fix: fix select missing dropdownClassName * chore: Update snapshot * chore: Adjust menu use rtl logic * docs: Update demo line color Co-authored-by: 二货机器人 <smith3816@gmail.com>
2020-01-02 19:10:16 +08:00
// ===================== Placement =====================
const memoPlacement = React.useMemo<Placement>(() => {
if (placement !== undefined) {
return placement;
}
return isRtl ? 'bottomRight' : 'bottomLeft';
}, [placement, isRtl]);
const mergedAllowClear = allowClear === true ? { clearIcon } : allowClear;
// ============================ zIndex ============================
const [zIndex] = useZIndex('SelectLike', restProps.dropdownStyle?.zIndex as number);
// ==================== Render =====================
2022-03-09 00:29:00 +08:00
const renderNode = (
<RcCascader
prefixCls={prefixCls}
className={classNames(
!customizePrefixCls && cascaderPrefixCls,
{
[`${prefixCls}-lg`]: mergedSize === 'large',
[`${prefixCls}-sm`]: mergedSize === 'small',
[`${prefixCls}-rtl`]: isRtl,
[`${prefixCls}-${variant}`]: enableVariantCls,
[`${prefixCls}-in-form-item`]: isFormItemInput,
},
getStatusClassNames(prefixCls, mergedStatus, hasFeedback),
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,
cascader?.className,
className,
rootClassName,
rootCls,
cascaderRootCls,
2022-03-09 00:29:00 +08:00
hashId,
cssVarCls,
)}
disabled={mergedDisabled}
style={{ ...cascader?.style, ...style }}
{...(restProps as any)}
builtinPlacements={mergedBuiltinPlacements(builtinPlacements, popupOverflow)}
direction={mergedDirection}
placement={memoPlacement}
notFoundContent={mergedNotFoundContent}
allowClear={mergedAllowClear}
showSearch={mergedShowSearch}
expandIcon={mergedExpandIcon}
suffixIcon={suffixIcon}
removeIcon={removeIcon}
loadingIcon={loadingIcon}
checkable={checkable}
dropdownClassName={mergedDropdownClassName}
dropdownPrefixCls={customizePrefixCls || cascaderPrefixCls}
2024-01-03 08:54:15 +08:00
dropdownStyle={{ ...restProps.dropdownStyle, zIndex }}
choiceTransitionName={getTransitionName(rootPrefixCls, '', choiceTransitionName)}
transitionName={getTransitionName(rootPrefixCls, 'slide-up', transitionName)}
getPopupContainer={getPopupContainer || getContextPopupContainer}
ref={ref}
/>
);
2022-03-09 00:29:00 +08:00
return wrapCascaderCSSVar(wrapSelectCSSVar(renderNode));
}) as unknown as (<OptionType extends BaseOptionType | DefaultOptionType = DefaultOptionType>(
props: React.PropsWithChildren<CascaderProps<OptionType>> & React.RefAttributes<CascaderRef>,
) => React.ReactElement) & {
displayName: string;
SHOW_PARENT: typeof SHOW_PARENT;
SHOW_CHILD: typeof SHOW_CHILD;
Panel: typeof CascaderPanel;
_InternalPanelDoNotUseOrYouWillBeFired: typeof PurePanel;
};
if (process.env.NODE_ENV !== 'production') {
Cascader.displayName = 'Cascader';
}
// We don't care debug panel
/* istanbul ignore next */
const PurePanel = genPurePanel(Cascader);
Cascader.SHOW_PARENT = SHOW_PARENT;
Cascader.SHOW_CHILD = SHOW_CHILD;
Cascader.Panel = CascaderPanel;
Cascader._InternalPanelDoNotUseOrYouWillBeFired = PurePanel;
export default Cascader;