import React from 'react'; import SelectionRect from './selection'; import { Range2D, Point2D, linearTransform2D, inRange2D, pointInPolygon, svgSizeScale, svgCoordinate } from '../../utilities'; import { PlotAreaProps, PlotAreaChildProps } from './types'; const PlotArea: React.FC = ({ dimensions, domain, scatterData, lineData, onSelectionEnd, children, nonSelectable, withGuideLines, guideLineProps, onFreeformSelectionEnd, freeformSelection, freeformSelectionProps, onMouseMove, ...props }) => { const transform = linearTransform2D(domain, { x: { start: 0, end: dimensions.width }, y: { start: dimensions.height, end: 0 } }); const pointInRange = inRange2D(domain); const scaleAnnotation = svgSizeScale( { width: domain.x.end - domain.x.start, height: domain.y.end - domain.y.start }, dimensions ); const translateAnnotation = (coordinates: Point2D, doTransform: boolean) => ( svgCoordinate(doTransform ? transform(coordinates) : coordinates) ); const renderChild = (child: React.ReactElement) => { if (child.props.data) { return ( React.cloneElement(child, { ...child.props, transform, domain }) ); } if (child.props.x !== undefined && child.props.y !== undefined) { return ( { React.cloneElement(child, { ...child.props, x: 0, y: 0 }) } ); } if (child.props.x1 !== undefined && child.props.y1 !== undefined && child.props.x2 !== undefined && child.props.y2 !== undefined) { const start = transform({ x: child.props.x1, y: child.props.y1 }); const end = transform({ x: child.props.x2, y: child.props.y2 }); return React.cloneElement(child, { ...child.props, x1: start.x, x2: end.x, y1: start.y, y2: end.y }); } if (child.props.cx !== undefined && child.props.cy !== undefined) { return ( { React.cloneElement(child, { ...child.props, cx: 0, cy: 0 }) } ); } if (child.props.coordinates !== undefined) { return ( { React.cloneElement(child, { ...child.props, cx: 0, cy: 0 }) } ); } return React.cloneElement(child, { ...child.props, transform, domain }); } return ( { children && React.Children.map(children, child => React.isValidElement(child) && renderChild(child)) } { !nonSelectable && ( { onSelectionEnd && scatterData && onSelectionEnd(domain, scatterData.map( (data: Point2D[]): number[] => ( Object.keys(data).filter( (key: string): boolean => pointInRange(data[+key]) ).map((x: string): number => +x) ))); }} onFreeformSelectionEnd={(selection: Point2D[]): void => { const pointFilter = pointInPolygon(selection); onFreeformSelectionEnd && scatterData && onFreeformSelectionEnd(selection, scatterData.map( (data: Point2D[]): number[] => ( Object.keys(data).filter( (key: string): boolean => pointFilter(data[+key]) ).map((x: string): number => +x) ))); }} onMouseMove={onMouseMove} withGuideLines={withGuideLines} guideLineProps={guideLineProps} freeform={freeformSelection} freeformProps={freeformSelectionProps} /> )} ); }; export default PlotArea;