На странице Наработка добавлен сброс даты и выделение данных при наведении

This commit is contained in:
ts_salikhov 2022-10-12 17:37:45 +04:00
parent d43e7d3da9
commit 83666424ad

View File

@ -20,7 +20,7 @@ export type D3HorizontalChartProps = {
height?: Property.Height
data: PercentChartDataType[]
offset?: Partial<ChartOffset>
afterDraw?: (d: d3.Selection<d3.BaseType, PercentChartDataType, d3.BaseType, unknown>) => void
afterDraw?: (d: d3.Selection<SVGRectElement, PercentChartDataType, SVGGElement, unknown>) => void
}
const defaultOffset = { top: 50, right: 100, bottom: 50, left: 100 }
@ -37,7 +37,8 @@ export const D3HorizontalPercentChart = memo<D3HorizontalChartProps>(({
const [divRef, { width, height }] = useElementSize()
const rootRef = useRef<SVGGElement | null>(null)
const root = useCallback(() => d3.select(rootRef.current), [rootRef.current])
const selectedRootRef = useCallback(() => rootRef.current ? d3.select(rootRef.current) : null, [rootRef.current])
const root = selectedRootRef()
const inlineWidth = useMemo(() => width - offset.left - offset.right, [width])
const inlineHeight = useMemo(() => height - offset.top - offset.bottom, [height])
@ -50,15 +51,15 @@ export const D3HorizontalPercentChart = memo<D3HorizontalChartProps>(({
const xAxisTop = d3.axisTop(xScale).tickFormat((d) => `${d}%`).ticks(4).tickSize(-inlineHeight)
const xAxisBottom = d3.axisBottom(xScale).tickFormat((d) => `${d}%`).ticks(4)
root().selectChild<SVGGElement>('.axis.x.bottom').call(xAxisBottom)
root().selectChild<SVGGElement>('.axis.x.top').call(xAxisTop)
root.selectChild<SVGGElement>('.axis.x.bottom').call(xAxisBottom)
root.selectChild<SVGGElement>('.axis.x.top').call(xAxisTop)
.selectAll('.tick')
.attr('class', 'tick grid-line')
}, [root, width, height, xScale, inlineHeight])
useEffect(() => { /// Отрисовываем ось Y слева
if (width < 100 || height < 100 || !root) return
root().selectChild<SVGGElement>('.axis.y.left').call(d3.axisLeft(yScale))
root.selectChild<SVGGElement>('.axis.y.left').call(d3.axisLeft(yScale))
}, [root, width, height, yScale])
useEffect(() => {
@ -66,18 +67,20 @@ export const D3HorizontalPercentChart = memo<D3HorizontalChartProps>(({
const delay = d3.transition().duration(500).ease(d3.easeLinear)
const rects = root().selectChild('.data').selectAll('rect').data(data)
const rects = root.selectChild('.data').selectAll('rect').data(data)
rects.enter().append('rect')
rects.exit().remove()
root().selectChild<SVGGElement>('.data')
const selectedRects = root.selectChild<SVGGElement>('.data')
.selectAll<SVGRectElement, PercentChartDataType>('rect')
.attr('fill', (d) => d.color || 'black')
selectedRects.attr('fill', (d) => d.color || 'black')
.attr('y', (d) => yScale(d.name) ?? null)
.attr('height', yScale.bandwidth())
.transition(delay)
.attr('width', (d) => d.percent > 0 ? xScale(d.percent) : 0)
afterDraw?.(root().selectChild('.data').selectAll('rect'))
afterDraw?.(selectedRects)
}, [data, width, height, root, yScale, xScale, afterDraw])