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

feat(toolbar): add onOutsideClick prop #391

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
11 changes: 11 additions & 0 deletions src/Toolbar/Toolbar.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,15 @@ describe('<Toolbar />', () => {
expect(toolbar).toHaveStyleRule('padding', '0');
});
});

describe('prop: onOutsideClick', () => {
it('should fire callback on container click', () => {
const mockCallBack = jest.fn();
const { container } = render(<Toolbar onOutsideClick={mockCallBack} />);

container.click();

expect(mockCallBack).toHaveBeenCalled();
});
});
});
31 changes: 28 additions & 3 deletions src/Toolbar/Toolbar.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import React, { forwardRef } from 'react';
import React, { forwardRef, useRef, useEffect } from 'react';
import styled from 'styled-components';
import useForkRef from '../common/hooks/useForkRef';

type ToolbarProps = {
children?: React.ReactNode;
noPadding?: boolean;
onOutsideClick?: () => void;
} & React.HTMLAttributes<HTMLDivElement>;

const StyledToolbar = styled.div<ToolbarProps>`
Expand All @@ -14,11 +16,34 @@ const StyledToolbar = styled.div<ToolbarProps>`
`;

const Toolbar = forwardRef<HTMLDivElement, ToolbarProps>(function Toolbar(
{ children, noPadding = false, ...otherProps },
{ children, noPadding = false, onOutsideClick, ...otherProps },
ref
) {
const toolbarRef = useRef<HTMLDivElement | null>(null);
const handleRef = useForkRef(ref, toolbarRef);

useEffect(() => {
if (!onOutsideClick) {
return () => {};
}

const handleOutsideClick = (e: MouseEvent) => {
const target = e.target as Node;

if (!toolbarRef.current?.contains(target)) {
onOutsideClick();
}
};

document.addEventListener('click', handleOutsideClick);

return () => {
document.removeEventListener('click', handleOutsideClick);
};
}, [ref, onOutsideClick]);

return (
<StyledToolbar noPadding={noPadding} ref={ref} {...otherProps}>
<StyledToolbar noPadding={noPadding} ref={handleRef} {...otherProps}>
{children}
</StyledToolbar>
);
Expand Down