/** @jsx h */ import { Component, h, RenderableProps } from 'preact'; import b from 'bem-react-helper'; import { Button } from '@app/components/button'; import { Theme } from '@app/common/types'; interface Props { title: string; heading?: string; isActive?: boolean; onTitleClick?: () => void; mix?: string; theme: Theme; } interface State { isActive: boolean; } export default class Dropdown extends Component { rootNode?: HTMLDivElement; constructor(props: Props) { super(props); this.state = { isActive: props.isActive || false, }; } onTitleClick() { this.setState({ isActive: !this.state.isActive, }); if (this.props.onTitleClick) { this.props.onTitleClick(); } } receiveMessage(e: { data: string | object }) { try { const data = typeof e.data === 'string' ? JSON.parse(e.data) : e.data; if (data.clickOutside) { if (this.state.isActive) { this.setState({ isActive: false, }); } } } catch (e) {} } onOutsideClick(e: MouseEvent) { if (this.rootNode && !this.rootNode.contains(e.target as Node)) { if (this.state.isActive) { this.setState({ isActive: false, }); } } } componentDidMount() { document.addEventListener('click', e => this.onOutsideClick(e)); window.addEventListener('message', e => this.receiveMessage(e)); } componentWillUnmount() { document.removeEventListener('click', e => this.onOutsideClick(e)); window.removeEventListener('message', e => this.receiveMessage(e)); } render(props: RenderableProps, { isActive }: State) { const { title, heading, children, mix } = props; return (
(this.rootNode = r)}>
{heading &&
{heading}
}
{children}
); } }