@mantine/core
Version:
React components library focused on usability, accessibility and developer experience
85 lines (82 loc) • 2.9 kB
JavaScript
'use client';
import { useState } from 'react';
import { useComboboxContext } from '../Combobox.context.mjs';
function useComboboxTargetProps({
onKeyDown,
withKeyboardNavigation,
withAriaAttributes,
withExpandedAttribute,
targetType,
autoComplete
}) {
const ctx = useComboboxContext();
const [selectedOptionId, setSelectedOptionId] = useState(null);
const handleKeyDown = (event) => {
onKeyDown?.(event);
if (ctx.readOnly) {
return;
}
if (withKeyboardNavigation) {
if (event.nativeEvent.isComposing) {
return;
}
if (event.nativeEvent.code === "ArrowDown") {
event.preventDefault();
if (!ctx.store.dropdownOpened) {
ctx.store.openDropdown("keyboard");
setSelectedOptionId(ctx.store.selectActiveOption());
ctx.store.updateSelectedOptionIndex("selected", { scrollIntoView: true });
} else {
setSelectedOptionId(ctx.store.selectNextOption());
}
}
if (event.nativeEvent.code === "ArrowUp") {
event.preventDefault();
if (!ctx.store.dropdownOpened) {
ctx.store.openDropdown("keyboard");
setSelectedOptionId(ctx.store.selectActiveOption());
ctx.store.updateSelectedOptionIndex("selected", { scrollIntoView: true });
} else {
setSelectedOptionId(ctx.store.selectPreviousOption());
}
}
if (event.nativeEvent.code === "Enter" || event.nativeEvent.code === "NumpadEnter") {
if (event.nativeEvent.keyCode === 229) {
return;
}
const selectedOptionIndex = ctx.store.getSelectedOptionIndex();
if (ctx.store.dropdownOpened && selectedOptionIndex !== -1) {
event.preventDefault();
ctx.store.clickSelectedOption();
} else if (targetType === "button") {
event.preventDefault();
ctx.store.openDropdown("keyboard");
}
}
if (event.key === "Escape") {
ctx.store.closeDropdown("keyboard");
}
if (event.nativeEvent.code === "Space") {
if (targetType === "button") {
event.preventDefault();
ctx.store.toggleDropdown("keyboard");
}
}
}
};
const ariaAttributes = withAriaAttributes ? {
"aria-haspopup": "listbox",
"aria-expanded": withExpandedAttribute && !!(ctx.store.listId && ctx.store.dropdownOpened) || void 0,
"aria-controls": ctx.store.dropdownOpened ? ctx.store.listId : void 0,
"aria-activedescendant": ctx.store.dropdownOpened ? selectedOptionId || void 0 : void 0,
autoComplete,
"data-expanded": ctx.store.dropdownOpened || void 0,
"data-mantine-stop-propagation": ctx.store.dropdownOpened || void 0
} : {};
return {
...ariaAttributes,
onKeyDown: handleKeyDown
};
}
export { useComboboxTargetProps };
//# sourceMappingURL=use-combobox-target-props.mjs.map