// @flow import * as React from 'react'; import { useOnClickBody } from '../utils'; import { type TargetedComponentProps } from '../types'; function withTargetedClickThrough( WrappedComponent: React.ComponentType, ): React.ComponentType<{| ...Config, ...$Exact, |}> { const WrapperComponent = ({ children, closeOnClickOutside, shouldTarget, useTargetingApi, onDismiss, ...rest }: {| ...Config, ...$Exact, |}) => { const { canShow, onComplete, onClose, onShow } = useTargetingApi(); const handleClose = () => { onClose(); if (onDismiss) { // $FlowFixMe onDismiss should be declared in both inferred types, which is not true, because we declare props types as Union of Config & TargetedComponentProps onDismiss(); } }; const handleOnComplete = () => { if (shouldTarget && canShow) { onComplete(); } }; const shouldShow = shouldTarget && canShow; useOnClickBody(onClose, !!(shouldShow && closeOnClickOutside)); React.useEffect(() => { if (shouldShow) { onShow(); } }, [shouldShow, onShow]); return ( {children} ); }; WrapperComponent.displayName = `withTargetedClickThrough(${WrappedComponent.displayName || WrappedComponent.name || 'Component'})`; return WrapperComponent; } export default withTargetedClickThrough;