Skip to content
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