Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions packages/components/hooks/useKeyboardNavigation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { useCallback, useEffect, useState } from 'react';

interface KeyboardNavigationProps {
options: any[];
initialIndex: number;
onSelect: (option: any, e: React.KeyboardEvent) => void;
}

const useKeyboardNavigation = ({ options, initialIndex, onSelect }: KeyboardNavigationProps) => {
const [hoverIndex, setHoverIndex] = useState(initialIndex);

useEffect(() => {
setHoverIndex(initialIndex);
}, [initialIndex]);

const findNextEnabledIndex = useCallback(
(startIndex: number, direction: 1 | -1) => {
if (!options || options.length === 0) return -1;
const len = options.length;
let i = startIndex;
for (let step = 0; step < len; step += 1) {
i = direction === 1 ? (i + 1) % len : (i - 1 + len) % len;
const opt = options[i];
if (!opt?.disabled) return i;
}
return startIndex;
},
[options],
);

const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (options.length === 0) return;

switch (e.key) {
case 'ArrowDown':
e.preventDefault();
setHoverIndex((prev) => {
const start = prev < 0 ? -1 : prev;
const next = findNextEnabledIndex(start, 1);
return next === start ? prev : next;
});
break;

case 'ArrowUp':
e.preventDefault();
setHoverIndex((prev) => {
const start = prev < 0 ? 0 : prev;
const next = findNextEnabledIndex(start, -1);
return next === start ? prev : next;
});
break;

case 'Enter':
e.preventDefault();
if (hoverIndex >= 0 && hoverIndex < options.length) {
const current = options[hoverIndex];
onSelect(current, e);
}
break;

default:
break;
}
},
[options, hoverIndex, onSelect, findNextEnabledIndex],
);

return {
hoverIndex,
handleKeyDown,
};
};

export default useKeyboardNavigation;
14 changes: 6 additions & 8 deletions packages/components/select/base/PopupContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,10 @@ interface SelectPopupProps
trigger: SelectValueChangeTrigger;
},
) => void;
/**
* 是否展示popup
*/
showPopup: boolean;
/**
* 控制popup展示的函数
*/
setShowPopup: (show: boolean) => void;
hoverIndex: number;
children?: React.ReactNode;
setShowPopup: (show: boolean) => void;
onCheckAllChange?: (checkAll: boolean, e: React.MouseEvent<HTMLLIElement>) => void;
getPopupInstance?: () => HTMLDivElement;
}
Expand Down Expand Up @@ -177,10 +172,13 @@ const PopupContent = React.forwardRef<HTMLDivElement, SelectPopupProps>((props,
const { value: optionValue, label, disabled, children, ...restData } = item as TdOptionProps;
// 当 keys 属性配置 content 作为 value 或 label 时,确保 restData 中也包含它, 不参与渲染计算
const { content } = item as TdOptionProps;
const shouldOmitContent = Object.values(keys || {}).includes('content');
const shouldOmitContent = Object.values(keys || {}).includes('content');
return (
<Option
key={index}
className={classNames({
[`${classPrefix}-select-option__hover`]: index === props.hoverIndex,
})}
max={max}
label={label}
value={optionValue}
Expand Down
51 changes: 51 additions & 0 deletions packages/components/select/base/Select.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import FakeArrow from '../../common/FakeArrow';
import useConfig from '../../hooks/useConfig';
import useControlled from '../../hooks/useControlled';
import useDefaultProps from '../../hooks/useDefaultProps';
import useKeyboardNavigation from '../../hooks/useKeyboardNavigation';
import Loading from '../../loading';
import { useLocaleReceiver } from '../../locale/LocalReceiver';
import SelectInput, { type SelectInputValue, type SelectInputValueChangeContext } from '../../select-input';
Expand Down Expand Up @@ -338,6 +339,51 @@ const Select = forwardRefWithStatics(
onClear(context);
};

const initialIndex = useMemo(() => {
if (!showPopup || multiple || !selectedOptions.length) return -1;
return currentOptions.findIndex((option) => {
if (isSelectOptionGroup(option)) return false;
const selectedValue =
valueType === 'object' ? selectedOptions[0] : selectedOptions[0]?.[keys?.value || 'value'];
const optionValue = valueType === 'object' ? option : option[keys?.value || 'value'];
return selectedValue === optionValue;
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [showPopup, currentOptions]);

const { hoverIndex, handleKeyDown } = useKeyboardNavigation({
options: currentOptions,
initialIndex,
onSelect: (option, e) => {
if (!option || option.disabled) return;
const optionValue = valueType === 'object' ? option : option[keys?.value || 'value'];
const optionLabel = option[keys?.label || 'label'];
handleChange(
multiple
? getSelectValueArr(
value,
optionValue,
!selectedOptions.some((selected) => {
const selectedValue = valueType === 'object' ? selected : selected[keys?.value || 'value'];
return selectedValue === optionValue;
}),
valueType,
keys,
option,
)
: optionValue,
{
// @ts-ignore
e,
trigger: 'default',
value: optionValue,
label: optionLabel,
},
);
handleShowPopup(false, {});
},
});

useEffect(() => {
if (typeof inputValue !== 'undefined') {
handleFilter(String(inputValue));
Expand Down Expand Up @@ -390,6 +436,7 @@ const Select = forwardRefWithStatics(
onCheckAllChange,
getPopupInstance,
scroll,
hoverIndex,
};
return <PopupContent {...popupContentProps}>{childrenWithProps}</PopupContent>;
};
Expand Down Expand Up @@ -550,6 +597,10 @@ const Select = forwardRefWithStatics(
tagProps={{ size, ...tagProps }}
inputProps={{
size,
onKeydown: (value, { e }) => {
props.inputProps?.onKeydown?.(value, { e });
handleKeyDown(e);
},
...inputProps,
}}
minCollapsedNum={minCollapsedNum}
Expand Down
Loading