({
linesProps = [],
dotIndex = -2,
strokeDasharray: restStroke = [5, 3],
curveCorrection = 1,
}: UseStrokeDasharrayProps)
| 103 | } & LineProps; |
| 104 | |
| 105 | export function useStrokeDasharray({ |
| 106 | linesProps = [], |
| 107 | dotIndex = -2, |
| 108 | strokeDasharray: restStroke = [5, 3], |
| 109 | curveCorrection = 1, |
| 110 | }: UseStrokeDasharrayProps): [CalculateStrokeDasharray, LinesStrokeDasharray] { |
| 111 | const linesStrokeDasharray = useRef<LinesStrokeDasharray>([]); |
| 112 | |
| 113 | const calculateStrokeDasharray = useCallback( |
| 114 | (props: RechartsChartProps): null => { |
| 115 | const items = props?.formattedGraphicalItems; |
| 116 | |
| 117 | const getLineWidth = (points: GraphicalItemPoint[]) => { |
| 118 | const width = points?.reduce((acc, point, index) => { |
| 119 | if (!index) return acc; |
| 120 | |
| 121 | const prevPoint = points?.[index - 1]; |
| 122 | |
| 123 | const xAxis = point?.x || 0; |
| 124 | const prevXAxis = prevPoint?.x || 0; |
| 125 | const xWidth = xAxis - prevXAxis; |
| 126 | |
| 127 | const yAxis = point?.y || 0; |
| 128 | const prevYAxis = prevPoint?.y || 0; |
| 129 | const yWidth = Math.abs(yAxis - prevYAxis); |
| 130 | |
| 131 | const hypotenuse = Math.sqrt(xWidth * xWidth + yWidth * yWidth); |
| 132 | acc += hypotenuse; |
| 133 | return acc; |
| 134 | }, 0); |
| 135 | |
| 136 | return width || 0; |
| 137 | }; |
| 138 | |
| 139 | items?.forEach((line) => { |
| 140 | const linePoints = line?.props?.points; |
| 141 | const lineWidth = getLineWidth(linePoints || []); |
| 142 | |
| 143 | const name = line?.item?.props?.dataKey; |
| 144 | const targetLine = linesProps?.find((target) => target?.name === name); |
| 145 | const targetIndex = targetLine?.dotIndex ?? dotIndex; |
| 146 | const dashedPoints = linePoints?.slice(targetIndex); |
| 147 | const dashedWidth = getLineWidth(dashedPoints || []); |
| 148 | |
| 149 | if (!lineWidth || !dashedWidth) return; |
| 150 | |
| 151 | const firstWidth = lineWidth - dashedWidth; |
| 152 | const targetCurve = targetLine?.curveCorrection ?? curveCorrection; |
| 153 | const correctionWidth = (firstWidth * targetCurve) / 100; |
| 154 | const firstDasharray = firstWidth + correctionWidth; |
| 155 | |
| 156 | const targetRestStroke = targetLine?.strokeDasharray || restStroke; |
| 157 | const gapDashWidth = targetRestStroke?.[0] + targetRestStroke?.[1] || 1; |
| 158 | const restDasharrayLength = dashedWidth / gapDashWidth; |
| 159 | const restDasharray = new Array(Math.ceil(restDasharrayLength)).fill( |
| 160 | targetRestStroke.join(' '), |
| 161 | ); |
| 162 |
no test coverage detected