Files
twenty/front/src/modules/ui/dropdown/components/DropdownButton.tsx
T
gitstart-twenty 00a3c8ca2b Change to using arrow functions (#1603)
* Change to using arrow functions

Co-authored-by: v1b3m <vibenjamin6@gmail.com>
Co-authored-by: Matheus <matheus_benini@hotmail.com>

* Add lint rule

---------

Co-authored-by: v1b3m <vibenjamin6@gmail.com>
Co-authored-by: Matheus <matheus_benini@hotmail.com>
Co-authored-by: Charles Bochet <charles@twenty.com>
2023-09-15 18:41:10 -07:00

83 lines
2.1 KiB
TypeScript

import { useRef } from 'react';
import { Keys } from 'react-hotkeys-hook';
import { flip, offset, Placement, useFloating } from '@floating-ui/react';
import { HotkeyEffect } from '@/ui/utilities/hotkey/components/HotkeyEffect';
import { HotkeyScope } from '@/ui/utilities/hotkey/types/HotkeyScope';
import { useListenClickOutside } from '@/ui/utilities/pointer-event/hooks/useListenClickOutside';
import { useDropdownButton } from '../hooks/useDropdownButton';
import { useInternalHotkeyScopeManagement } from '../hooks/useInternalHotkeyScopeManagement';
type OwnProps = {
buttonComponents: JSX.Element | JSX.Element[];
dropdownComponents: JSX.Element | JSX.Element[];
dropdownId: string;
hotkey?: {
key: Keys;
scope: string;
};
dropdownHotkeyScope?: HotkeyScope;
dropdownPlacement?: Placement;
onClickOutside?: () => void;
};
export const DropdownButton = ({
buttonComponents,
dropdownComponents,
dropdownId,
hotkey,
dropdownHotkeyScope,
dropdownPlacement = 'bottom-end',
onClickOutside,
}: OwnProps) => {
const containerRef = useRef<HTMLDivElement>(null);
const { isDropdownButtonOpen, toggleDropdownButton, closeDropdownButton } =
useDropdownButton({
dropdownId,
});
const { refs, floatingStyles } = useFloating({
placement: dropdownPlacement,
middleware: [flip(), offset()],
});
const handleHotkeyTriggered = () => {
toggleDropdownButton();
};
useListenClickOutside({
refs: [containerRef],
callback: () => {
onClickOutside?.();
if (isDropdownButtonOpen) {
closeDropdownButton();
}
},
});
useInternalHotkeyScopeManagement({
dropdownId,
dropdownHotkeyScope,
});
return (
<div ref={containerRef}>
{hotkey && (
<HotkeyEffect
hotkey={hotkey}
onHotkeyTriggered={handleHotkeyTriggered}
/>
)}
<div ref={refs.setReference}>{buttonComponents}</div>
{isDropdownButtonOpen && (
<div ref={refs.setFloating} style={floatingStyles}>
{dropdownComponents}
</div>
)}
</div>
);
};