-
Notifications
You must be signed in to change notification settings - Fork 54
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: Upstream Doughnut Chart to RC #1128
Open
Kxiru
wants to merge
1
commit into
canonical:main
Choose a base branch
from
Kxiru:upstream-doughnut-chart
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
@import "vanilla-framework"; | ||
|
||
.doughnut-chart { | ||
width: 6.5rem; | ||
|
||
.doughnut-chart__tooltip { | ||
display: block; | ||
} | ||
|
||
.doughnut-chart__tooltip > :only-child { | ||
// Override the tooltip wrapper. | ||
display: block !important; | ||
} | ||
|
||
.doughnut-chart__chart { | ||
// Restrict hover areas to the strokes. | ||
pointer-events: stroke; | ||
} | ||
|
||
.doughnut-chart__segment { | ||
fill: transparent; | ||
|
||
// Animate stroke size changes on hover. | ||
transition: stroke-width 0.3s ease; | ||
} | ||
} | ||
|
||
.doughnut-chart__legend { | ||
list-style-type: none; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
import { Meta, StoryObj } from "@storybook/react"; | ||
|
||
import DoughnutChart from "./DoughnutChart"; | ||
|
||
const meta: Meta<typeof DoughnutChart> = { | ||
component: DoughnutChart, | ||
tags: ["autodocs"], | ||
}; | ||
|
||
export default meta; | ||
|
||
type Story = StoryObj<typeof DoughnutChart>; | ||
|
||
/** | ||
* The Doughnut Chart component visually represents data segments in a circular format, with tooltips that appear on hover, and segments that can be customized via props. | ||
*/ | ||
export const Default: Story = { | ||
name: "Default", | ||
args: { | ||
chartID: "default", | ||
segmentHoverWidth: 45, | ||
segmentThickness: 40, | ||
segments: [ | ||
{ | ||
color: "#0E8420", | ||
tooltip: "Running", | ||
value: 10, | ||
}, | ||
{ | ||
color: "#CC7900", | ||
tooltip: "Stopped", | ||
value: 15, | ||
}, | ||
{ color: "#C7162B", tooltip: "Frozen", value: 5 }, | ||
{ color: "#000", tooltip: "Error", value: 5 }, | ||
], | ||
size: 150, | ||
}, | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
import { fireEvent, render, screen, waitFor } from "@testing-library/react"; | ||
import React from "react"; | ||
import DoughnutChart, { TestIds } from "./DoughnutChart"; | ||
|
||
describe("DoughnutChart", () => { | ||
const defaultProps = { | ||
chartID: "test", | ||
segmentHoverWidth: 10, | ||
segmentThickness: 8, | ||
size: 100, | ||
segments: [ | ||
{ | ||
color: "#3498DB", | ||
tooltip: "aaa", | ||
value: 12, | ||
}, | ||
{ | ||
color: "#E74C3C", | ||
tooltip: "bbb", | ||
value: 8, | ||
}, | ||
{ | ||
color: "#F1C40F", | ||
tooltip: "ccc", | ||
value: 18, | ||
}, | ||
{ | ||
color: "#2ECC71", | ||
tooltip: "ddd", | ||
value: 14, | ||
}, | ||
], | ||
}; | ||
|
||
it("renders", () => { | ||
render(<DoughnutChart {...defaultProps} />); | ||
expect(screen.getByTestId("chart")).toBeInTheDocument(); | ||
}); | ||
|
||
it("displays the correct number of segments", () => { | ||
render(<DoughnutChart {...defaultProps} />); | ||
const segments = screen.getAllByTestId(TestIds.Segment); | ||
expect(segments).toHaveLength(defaultProps.segments.length); | ||
}); | ||
|
||
it("shows tooltips on hover", async () => { | ||
const { container } = render(<DoughnutChart {...defaultProps} />); | ||
const segments = screen.getAllByTestId(TestIds.Segment); | ||
|
||
fireEvent.mouseOver(segments[0]); | ||
fireEvent.click(container.firstChild.firstChild); | ||
|
||
await waitFor(() => { | ||
expect(screen.getByText("aaa")).toBeInTheDocument(); | ||
}); | ||
}); | ||
|
||
it("applies custom styles to segments", () => { | ||
render(<DoughnutChart {...defaultProps} />); | ||
const segment = screen.getAllByTestId(TestIds.Segment)[0]; | ||
expect(segment).toHaveStyle(`stroke: ${defaultProps.segments[0].color}`); | ||
expect(segment).toHaveStyle( | ||
`stroke-width: ${defaultProps.segmentThickness}`, | ||
); | ||
}); | ||
|
||
it("displays the label in the center if provided", () => { | ||
render(<DoughnutChart {...defaultProps} label="Test Label" />); | ||
expect(screen.getByText("Test Label")).toBeInTheDocument(); | ||
}); | ||
|
||
it("does not display the label if not provided", () => { | ||
render(<DoughnutChart {...defaultProps} />); | ||
expect(screen.queryByText("Test Label")).not.toBeInTheDocument(); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,214 @@ | ||
import React, { FC, useRef, useState } from "react"; | ||
import classNames from "classnames"; | ||
import Tooltip from "components/Tooltip"; | ||
import "./DoughnutChart.scss"; | ||
|
||
export type Segment = { | ||
/** | ||
* The colour of the segment. | ||
*/ | ||
color: string; | ||
/** | ||
* The segment tooltip. | ||
*/ | ||
tooltip?: string; | ||
/** | ||
* The segment length. | ||
*/ | ||
value: number; | ||
}; | ||
|
||
export type Props = { | ||
/** | ||
* The label in the centre of the doughnut. | ||
*/ | ||
label?: string; | ||
/** | ||
* An optional class name applied to the wrapping element. | ||
*/ | ||
className?: string; | ||
/** | ||
* The width of the segments when hovered. | ||
*/ | ||
segmentHoverWidth: number; | ||
/** | ||
* The width of the segments. | ||
*/ | ||
segmentThickness: number; | ||
/** | ||
* The doughnut segments. | ||
*/ | ||
segments: Segment[]; | ||
/** | ||
* The size of the doughnut. | ||
*/ | ||
size: number; | ||
/** | ||
* ID associated to the specific instance of a Chart. | ||
*/ | ||
chartID: string; | ||
}; | ||
|
||
export enum TestIds { | ||
Label = "label", | ||
Segment = "segment", | ||
Chart = "chart", | ||
Section = "Section", | ||
} | ||
|
||
const DoughnutChart: FC<Props> = ({ | ||
className, | ||
label, | ||
segmentHoverWidth, | ||
segmentThickness, | ||
segments, | ||
size, | ||
chartID, | ||
}): JSX.Element => { | ||
const [tooltipMessage, setTooltipMessage] = useState< | ||
Segment["tooltip"] | null | ||
>(null); | ||
|
||
const id = useRef(`doughnut-chart-${chartID}`); | ||
const hoverIncrease = segmentHoverWidth - segmentThickness; | ||
const adjustedHoverWidth = segmentHoverWidth + hoverIncrease; | ||
// The canvas needs enough space so that the hover state does not get cut off. | ||
const canvasSize = size + adjustedHoverWidth - segmentThickness; | ||
const diameter = size - segmentThickness; | ||
const radius = diameter / 2; | ||
const circumference = Math.round(diameter * Math.PI); | ||
// Calculate the total value of all segments. | ||
const total = segments.reduce( | ||
(totalValue, segment) => (totalValue += segment.value), | ||
0, | ||
); | ||
let accumulatedLength = 0; | ||
const segmentNodes = segments.map(({ color, tooltip, value }, i) => { | ||
// The start position is the value of all previous segments. | ||
const startPosition = accumulatedLength; | ||
// The length of the segment (as a portion of the doughnut circumference) | ||
const segmentLength = (value / total) * circumference; | ||
// The space left until the end of the circle. | ||
const remainingSpace = circumference - (segmentLength + startPosition); | ||
// Add this segment length to the running tally. | ||
accumulatedLength += segmentLength; | ||
|
||
return ( | ||
<circle | ||
className="doughnut-chart__segment" | ||
cx={radius - segmentThickness / 2 - hoverIncrease} | ||
cy={radius + segmentThickness / 2 + hoverIncrease} | ||
data-testid={TestIds.Segment} | ||
key={i} | ||
Kxiru marked this conversation as resolved.
Show resolved
Hide resolved
|
||
tabIndex={0} | ||
aria-label={`${tooltip}: ${value}`} | ||
onMouseOut={ | ||
tooltip | ||
? () => { | ||
// Hide the tooltip. | ||
setTooltipMessage(null); | ||
} | ||
: undefined | ||
} | ||
onMouseOver={ | ||
tooltip | ||
? () => { | ||
setTooltipMessage(tooltip); | ||
} | ||
: undefined | ||
} | ||
r={radius} | ||
style={{ | ||
stroke: color, | ||
strokeWidth: segmentThickness, | ||
// The dash array used is: | ||
// 1 - We want there to be a space before the first visible dash so | ||
// by setting this to 0 we can use the next dash for the space. | ||
// 2 - This gap is the distance of all previous segments | ||
// so that the segment starts in the correct spot. | ||
// 3 - A dash that is the length of the segment. | ||
// 4 - A gap from the end of the segment to the start of the circle | ||
// so that the dash array doesn't repeat and be visible. | ||
strokeDasharray: `0 ${startPosition.toFixed( | ||
2, | ||
)} ${segmentLength.toFixed(2)} ${remainingSpace.toFixed(2)}`, | ||
}} | ||
// Rotate the segment so that the segments start at the top of | ||
// the chart. | ||
transform={`rotate(-90 ${radius},${radius})`} | ||
/> | ||
); | ||
}); | ||
|
||
return ( | ||
<div | ||
className={classNames("doughnut-chart", className)} | ||
style={{ maxWidth: `${canvasSize}px` }} | ||
data-testid={TestIds.Chart} | ||
> | ||
<Tooltip | ||
className="doughnut-chart__tooltip" | ||
followMouse={true} | ||
message={tooltipMessage} | ||
position="right" | ||
> | ||
<style> | ||
{/* Set the hover width of the segments. */} | ||
{`#${id.current} .doughnut-chart__segment:hover { | ||
stroke-width: ${adjustedHoverWidth} !important; | ||
}`} | ||
</style> | ||
<svg | ||
className="doughnut-chart__chart" | ||
id={id.current} | ||
viewBox={`0 0 ${canvasSize} ${canvasSize}`} | ||
data-testid={TestIds.Section} | ||
> | ||
<mask id="canvasMask"> | ||
{/* Cover the canvas, this will be the visible area. */} | ||
<rect | ||
fill="white" | ||
height={canvasSize} | ||
width={canvasSize} | ||
x="0" | ||
y="0" | ||
/> | ||
{/* Cut out the center circle so that the hover state doesn't grow inwards. */} | ||
<circle | ||
cx={canvasSize / 2} | ||
cy={canvasSize / 2} | ||
fill="black" | ||
r={radius - segmentThickness / 2} | ||
/> | ||
</mask> | ||
<g mask="url(#canvasMask)"> | ||
{/* Force the group to cover the full size of the canvas, otherwise it will only mask the children (in their non-hovered state) */} | ||
<rect | ||
fill="transparent" | ||
height={canvasSize} | ||
width={canvasSize} | ||
x="0" | ||
y="0" | ||
/> | ||
<g>{segmentNodes}</g> | ||
</g> | ||
{label ? ( | ||
<text | ||
x={radius + adjustedHoverWidth / 2} | ||
y={radius + adjustedHoverWidth / 2} | ||
> | ||
<tspan | ||
className="doughnut-chart__label" | ||
data-testid={TestIds.Label} | ||
> | ||
{label} | ||
</tspan> | ||
</text> | ||
) : null} | ||
</svg> | ||
</Tooltip> | ||
</div> | ||
); | ||
}; | ||
|
||
export default DoughnutChart; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
export { default } from "./DoughnutChart"; | ||
export type { Props as DoughnutChartProps } from "./DoughnutChart"; | ||
export type { Segment } from "./DoughnutChart"; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why is this necessary, and why is the tooltip child inline-block by default?