Skip to content

Commit

Permalink
Merge pull request #1703 from alfonsomthd/fix-kebab-click
Browse files Browse the repository at this point in the history
Fix kebab menu click behavior
  • Loading branch information
openshift-merge-bot[bot] authored Nov 21, 2024
2 parents 29cb726 + ef82f8c commit 294d6d5
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions packages/shared/src/kebab/kebab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,20 @@ import { useCustomTranslation } from '../useCustomTranslationHook';
import { referenceForModel } from '../utils';

const useClickOutside = (
ref: React.RefObject<HTMLElement>,
dropdownRef: React.RefObject<HTMLElement>,
dropdownToggleRef: React.RefObject<HTMLElement>,
callback: () => void
) => {
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (ref.current && !ref.current.contains(event.target as Node)) {
// Dropdown and its toggle button are 2 separate elements at the same
// nesting level, so we check that we're interacting outside both.
if (
dropdownRef.current &&
!dropdownRef.current.contains(event.target as Node) &&
dropdownToggleRef.current &&
!dropdownToggleRef.current.contains(event.target as Node)
) {
callback();
}
};
Expand All @@ -45,7 +53,7 @@ const useClickOutside = (
document.removeEventListener('mousedown', handleClickOutside);
document.removeEventListener('keydown', handleEscapeKey);
};
}, [ref, callback]);
}, [dropdownRef, dropdownToggleRef, callback]);
};

export type CustomKebabItem = {
Expand Down Expand Up @@ -131,14 +139,15 @@ export const Kebab: React.FC<KebabProps> & KebabStaticProperties = ({
const { t } = useCustomTranslation();
const launchModal = useModal();
const eventRef = React.useRef(undefined);
const dropdownRef = React.useRef();
const dropdownToggleRef = React.useRef();
const [toggleDirection, setToggleDirection] =
React.useState<DropdownPopperProps['direction']>('down');
const [isOpen, setOpen] = React.useState(false);
const closeDropdown = useCallback(() => setOpen(false), []);

// Use the custom hook to detect clicks outside the Kebab menu
useClickOutside(dropdownToggleRef, closeDropdown);
useClickOutside(dropdownRef, dropdownToggleRef, closeDropdown);

const { resourceModel, resource } = extraProps;
const resourceLabel = resourceModel.label;
Expand Down Expand Up @@ -285,6 +294,7 @@ export const Kebab: React.FC<KebabProps> & KebabStaticProperties = ({
<Dropdown
data-test="kebab-button"
onSelect={onClick}
ref={dropdownRef}
toggle={{
toggleNode: (
<MenuToggle
Expand All @@ -309,6 +319,7 @@ export const Kebab: React.FC<KebabProps> & KebabStaticProperties = ({
enableFlip: true,
position: 'right',
}}
shouldFocusFirstItemOnOpen={false}
>
{dropdownItems}
</Dropdown>
Expand Down

0 comments on commit 294d6d5

Please sign in to comment.