Skip to content

Commit

Permalink
Fix the kebab menu close when we click outside the kebab.
Browse files Browse the repository at this point in the history
  • Loading branch information
TimothyAsirJeyasing committed Nov 14, 2024
1 parent 24037de commit 54ce4b0
Showing 1 changed file with 32 additions and 5 deletions.
37 changes: 32 additions & 5 deletions packages/shared/src/kebab/kebab.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as React from 'react';
import { useEffect } from 'react';
import { getNamespace, getName } from '@odf/shared/selectors';
import {
K8sResourceCommon,
Expand All @@ -21,6 +22,32 @@ import { ModalKeys, defaultModalMap } from '../modals/types';
import { useCustomTranslation } from '../useCustomTranslationHook';
import { referenceForModel } from '../utils';

const useClickOutside = (
ref: React.RefObject<HTMLElement>,
callback: () => void
) => {
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (ref.current && !ref.current.contains(event.target as Node)) {
callback();
}
};

const handleEscapeKey = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
callback();
}
};

document.addEventListener('mousedown', handleClickOutside);
document.addEventListener('keydown', handleEscapeKey);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
document.removeEventListener('keydown', handleEscapeKey);
};
}, [ref, callback]);
};

export type CustomKebabItem = {
key: string;
value: string;
Expand Down Expand Up @@ -101,19 +128,18 @@ export const Kebab: React.FC<KebabProps> & KebabStaticProperties = ({
hideItems,
}) => {
const { t } = useCustomTranslation();

const launchModal = useModal();

const eventRef = React.useRef(undefined);
const dropdownToggleRef = React.useRef();
const [toggleDirection, setToggleDirection] =
React.useState<DropdownPopperProps['direction']>('down');
const [isOpen, setOpen] = React.useState(false);

const { resourceModel, resource } = extraProps;
// Use the custom hook to detect clicks outside the Kebab menu
useClickOutside(dropdownToggleRef, () => setOpen(false));

const { resourceModel, resource } = extraProps;
const resourceLabel = resourceModel.label;

const navigate = useNavigate();

const [canCreate, createLoading] = useAccessReview({
Expand Down Expand Up @@ -237,6 +263,7 @@ export const Kebab: React.FC<KebabProps> & KebabStaticProperties = ({
const content = _.has(resource.metadata, 'deletionTimestamp')
? terminatingTooltip || t('Resource is being deleted.')
: '';

return (
<Tooltip
content={
Expand All @@ -259,7 +286,7 @@ export const Kebab: React.FC<KebabProps> & KebabStaticProperties = ({
ref={dropdownToggleRef}
aria-label="Dropdown toggle"
variant={toggleType === 'Kebab' ? 'plain' : 'default'}
onClick={() => setOpen((o) => !o)}
onClick={() => setOpen(!isOpen)}
isExpanded={isOpen}
data-test="kebab-button"
isDisabled={isDisabled}
Expand Down

0 comments on commit 54ce4b0

Please sign in to comment.