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(dropdown): close dropdown when item is selected #392

Merged
merged 7 commits into from
Oct 19, 2022
17 changes: 16 additions & 1 deletion src/lib/components/Dropdown/Dropdown.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { render, screen } from '@testing-library/react';
import { act, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { FC } from 'react';
import { describe, expect, it } from 'vitest';
Expand All @@ -24,6 +24,19 @@ describe('Components / Dropdown', () => {
await user.click(button());
await user.click(button());

expect(dropdown()).toHaveClass('invisible');
});
});
describe('Mouse interactions', () => {
it('should collapse if item is clicked', async () => {
const user = userEvent.setup();
render(<TestDropdown />);

act(() => {
user.click(button());
userEvent.click(dropdownItem());
});

expect(dropdown()).toHaveClass('invisible');
});
});
Expand All @@ -46,3 +59,5 @@ const TestDropdown: FC = () => (
const button = () => screen.getByRole('button');

const dropdown = () => screen.getByTestId('flowbite-tooltip');

const dropdownItem = () => screen.getByText('Dashboard');
29 changes: 26 additions & 3 deletions src/lib/components/Dropdown/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import type { ComponentProps, FC, PropsWithChildren, ReactNode } from 'react';
import { useMemo } from 'react';
import type { ComponentProps, FC, PropsWithChildren, ReactElement, ReactNode } from 'react';
import React, { Children, useMemo, useState } from 'react';
import { HiOutlineChevronDown, HiOutlineChevronLeft, HiOutlineChevronRight, HiOutlineChevronUp } from 'react-icons/hi';
import { excludeClassName } from '../../helpers/exclude';
import { uuid } from '../../helpers/uuid';
import type { ButtonProps } from '../Button';
import { Button } from '../Button';
import type { FloatingProps } from '../Floating';
Expand Down Expand Up @@ -71,7 +72,28 @@ const DropdownComponent: FC<DropdownProps> = ({ children, ...props }) => {
return icons[p] ?? HiOutlineChevronDown;
}, [placement]);

const content = useMemo(() => <ul className={theme.content}>{children}</ul>, [children, theme]);
const [closeRequestKey, setCloseRequestKey] = useState<string | undefined>(undefined);

// Extends DropdownItem's onClick to trigger a close request to the Floating component
const attachCloseListener: any = (node: ReactNode) => {
if (!React.isValidElement(node)) return node;
if ((node as ReactElement).type === DropdownItem)
return React.cloneElement(node, {
onClick: () => {
node.props.onClick?.();
setCloseRequestKey(uuid());
},
});
if (node.props.children && typeof node.props.children === 'object') {
return React.cloneElement(node, { children: Children.map(node.props.children, attachCloseListener) });
}
return node;
};

const content = useMemo(
() => <ul className={theme.content}>{Children.map(children, attachCloseListener)}</ul>,
[children, theme],
);

const TriggerWrapper: FC<ButtonProps> = ({ children }): JSX.Element =>
inline ? <button className={theme.inlineWrapper}>{children}</button> : <Button {...buttonProps}>{children}</Button>;
Expand All @@ -85,6 +107,7 @@ const DropdownComponent: FC<DropdownProps> = ({ children, ...props }) => {
arrow={floatingArrow}
trigger={trigger}
theme={theme.floating}
closeRequestKey={closeRequestKey}
>
<TriggerWrapper>
{label}
Expand Down
6 changes: 6 additions & 0 deletions src/lib/components/Floating/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export interface FloatingProps extends PropsWithChildren<Omit<ComponentProps<'di
style?: 'dark' | 'light' | 'auto';
animation?: false | `duration-${number}`;
arrow?: boolean;
closeRequestKey?: string;
}

/**
Expand All @@ -59,6 +60,7 @@ export const Floating: FC<FloatingProps> = ({
placement = 'top',
style = 'dark',
trigger = 'hover',
closeRequestKey,
...props
}) => {
const theirProps = excludeClassName(props);
Expand Down Expand Up @@ -97,6 +99,10 @@ export const Floating: FC<FloatingProps> = ({
}
}, [open, refs.floating, refs.reference, update]);

useEffect(() => {
if (closeRequestKey !== undefined) setOpen(false);
}, [closeRequestKey]);

return (
<>
<div className={theme.target} {...getReferenceProps({ ref: reference })} data-testid="flowbite-tooltip-target">
Expand Down
7 changes: 7 additions & 0 deletions src/lib/helpers/uuid.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export function uuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
const r = (Math.random() * 16) | 0,
v = c == 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}