import { useMemo } from 'react' import { useValueFormatter, usePropertyAccessor } from '@nivo/core' import { useOrdinalColorScale } from '@nivo/colors' import { computeXYScalesForSeries } from '@nivo/scales' import { useAnnotations } from '@nivo/annotations' import { computePoints, getNodeSizeGenerator } from './compute' import { ScatterPlotCommonProps, ScatterPlotDataProps, ScatterPlotDatum, ScatterPlotNodeData, } from './types' const useNodeSize = ( size: ScatterPlotCommonProps['nodeSize'] ) => useMemo(() => getNodeSizeGenerator(size), [size]) export const useScatterPlot = ({ data, xScaleSpec, xFormat, yScaleSpec, yFormat, width, height, nodeId, nodeSize, colors, }: { data: ScatterPlotDataProps['data'] xScaleSpec: ScatterPlotCommonProps['xScale'] xFormat?: ScatterPlotCommonProps['xFormat'] yScaleSpec: ScatterPlotCommonProps['yScale'] yFormat?: ScatterPlotCommonProps['yFormat'] width: number height: number nodeId: ScatterPlotCommonProps['nodeId'] nodeSize: ScatterPlotCommonProps['nodeSize'] colors: ScatterPlotCommonProps['colors'] }) => { const { series, xScale, yScale } = useMemo( () => computeXYScalesForSeries<{ id: string | number }, RawDatum>( data, xScaleSpec, yScaleSpec, width, height ), [data, xScaleSpec, yScaleSpec, width, height] ) const formatX = useValueFormatter(xFormat) const formatY = useValueFormatter(yFormat) const getNodeId = usePropertyAccessor(nodeId) const rawNodes = useMemo( () => computePoints({ series, formatX, formatY, getNodeId }), [series, formatX, formatY, getNodeId] ) const getNodeSize = useNodeSize(nodeSize) const getColor = useOrdinalColorScale(colors, 'serieId') const nodes: ScatterPlotNodeData[] = useMemo( () => rawNodes.map(rawNode => ({ ...rawNode, size: getNodeSize(rawNode), color: getColor({ serieId: rawNode.serieId }), })), [rawNodes, getNodeSize, getColor] ) const legendData = useMemo( () => series.map(serie => ({ id: serie.id, label: serie.id, color: getColor({ serieId: serie.id }), })), [series, getColor] ) return { xScale, yScale, nodes, legendData, } } export const useScatterPlotAnnotations = ( items: ScatterPlotNodeData[], annotations: ScatterPlotCommonProps['annotations'] ) => useAnnotations>({ data: items, annotations, getPosition: (node: ScatterPlotNodeData) => ({ x: node.x, y: node.y, }), getDimensions: (node: ScatterPlotNodeData) => ({ size: node.size, width: node.size, height: node.size, }), })