Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(react-examples): Improve keyboard navigation in ContextualMenu.CustomMenuList #25172

Merged
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { ISearchBoxStyles, SearchBox } from '@fluentui/react/lib/SearchBox';
import { Icon } from '@fluentui/react/lib/Icon';
import { IContextualMenuListProps, IContextualMenuItem } from '@fluentui/react/lib/ContextualMenu';
import { IRenderFunction } from '@fluentui/react/lib/Utilities';
import { KeyCodes } from '@fluentui/react';

export const ContextualMenuWithCustomMenuListExample: React.FunctionComponent = () => {
const [items, setItems] = React.useState(menuItems);
Expand Down Expand Up @@ -32,6 +33,21 @@ export const ContextualMenuWithCustomMenuListExample: React.FunctionComponent =
setItems(filteredItems);
}, []);

const onKeyDown = React.useCallback((e, ...args) => {
/* Key Up, but we are not at the beginning of the text: stop event propagation to prevent ContextualMenu to focus */
if (e.target.selectionStart > 0 && e.which === KeyCodes.up) {
e.stopPropagation();
}
/* Key Down, but we are not at the end of the text: stop event propagation to prevent ContextualMenu to focus */
if (e.target.selectionStart !== e.target.value.length && e.which === KeyCodes.down) {
e.stopPropagation();
}
}, []);

const onDismiss = React.useCallback(() => {
setItems(menuItems);
}, []);

const renderMenuList = React.useCallback(
(menuListProps: IContextualMenuListProps, defaultRender: IRenderFunction<IContextualMenuListProps>) => {
return (
Expand All @@ -42,14 +58,15 @@ export const ContextualMenuWithCustomMenuListExample: React.FunctionComponent =
placeholder="Filter actions"
onAbort={onAbort}
onChange={onChange}
onKeyDown={onKeyDown}
styles={searchBoxStyles}
/>
</div>
{defaultRender(menuListProps)}
</div>
);
},
[onAbort, onChange],
[onAbort, onChange, onKeyDown],
);

const menuProps = React.useMemo(
Expand All @@ -58,8 +75,12 @@ export const ContextualMenuWithCustomMenuListExample: React.FunctionComponent =
title: 'Actions',
shouldFocusOnMount: true,
items,
focusZoneProps: {
shouldInputLoseFocusOnArrowKey: () => true /* Allow up and down arrows to move focus out of the SearchBox */,
},
onDismiss,
}),
[items, renderMenuList],
[items, renderMenuList, onDismiss],
);

return <DefaultButton text="Click for ContextualMenu" menuProps={menuProps} />;
Expand Down