diff --git a/public/llms-full.txt b/public/llms-full.txt index 177b6117..1aed31ce 100644 --- a/public/llms-full.txt +++ b/public/llms-full.txt @@ -2675,6 +2675,8 @@ Extends all native `RadioHTMLAttributes` (except `type`), plus these specialties ); }; + + A selectable option card group for single-choice selections such as style presets, plans, providers, or configuration modes. ### Import @@ -2695,6 +2697,8 @@ bunx carllosnc/dashkit add radio-card Use `RadioCardGroup` with `label` and `valueLabel` to display the group title and active selection summary above a stack of option cards. + + ```tsx const [preset, setPreset] = useState('default'); @@ -2729,6 +2733,8 @@ const [preset, setPreset] = useState('default'); Combine `columns` (`1 | 2 | 3 | 4`), `indicator` (`'none' | 'radio' | 'check'`), and `trailing` slots for multi-column plan or provider pickers. + + ```tsx {\r\n data: Record[];\r\n series: AreaChartSeries[];\r\n /** @default '100%' */\r\n height?: number | string;\r\n /** @default true */\r\n showGrid?: boolean;\r\n /** @default true */\r\n showLabels?: boolean;\r\n /** @default true */\r\n showTooltip?: boolean;\r\n /** @default true */\r\n animate?: boolean;\r\n}\r\n\r\n/**\r\n * Prop-driven (`data`, `series`) responsive SVG area chart with grid, labels, and interactive tooltips.\r\n *\r\n * @example\r\n * ```tsx\r\n * \r\n * ```\r\n */", - "export interface UseAreaChartProps {\r\n data: Record[];\r\n series: AreaChartSeries[];\r\n width?: number;\r\n svgHeight?: number;\r\n defaultColors?: string[];\r\n}" + "export interface AreaChartProps extends React.ComponentPropsWithoutRef<'div'> {\n data: Record[];\n series: AreaChartSeries[];\n /** @default '100%' */\n height?: number | string;\n /** @default true */\n showGrid?: boolean;\n /** @default true */\n showLabels?: boolean;\n /** @default true */\n showTooltip?: boolean;\n /** @default true */\n animate?: boolean;\n /** @default 'linear' */\n curve?: 'linear' | 'smooth';\n /** @default true */\n showDots?: boolean | 'hover';\n /** @default false */\n showYAxis?: boolean;\n /** @default false */\n showLegend?: boolean;\n /** Key in `data` items used for x-axis and tooltip labels. @default 'label' */\n labelKey?: string;\n /** Custom formatter for Y-axis ticks and tooltip values. */\n valueFormatter?: (value: number) => string;\n /** Accessible label for the chart SVG. @default 'Area chart' */\n ariaLabel?: string;\n}\n\n/**\n * Prop-driven (`data`, `series`) responsive SVG area chart with grid, labels, and interactive tooltips.\n *\n * @example\n * ```tsx\n * \n * ```\n */", + "export interface UseAreaChartProps {\n data: Record[];\n series: AreaChartSeries[];\n width?: number;\n svgHeight?: number;\n defaultColors?: string[];\n}" ] }, "avatar": { @@ -188,7 +189,7 @@ "useBarChart" ], "propsDefinitions": [ - "export interface BarChartProps extends ComponentPropsWithoutRef<'div'> {\r\n data: Record[];\r\n series: BarChartSeries[];\r\n /** @default '100%' */\r\n height?: number | string;\r\n /** @default true */\r\n showGrid?: boolean;\r\n /** @default true */\r\n showLabels?: boolean;\r\n /** @default true */\r\n showTooltip?: boolean;\r\n /** @default true */\r\n animate?: boolean;\r\n /** @default 4 */\r\n barGap?: number;\r\n /** @default 64 */\r\n maxBarWidth?: number;\r\n /** @default true */\r\n rounded?: boolean;\r\n /** @default 'none' */\r\n texture?: BarChartTexture;\r\n /** @default false */\r\n showTrack?: boolean;\r\n}\r\n\r\n/**\r\n * Prop-driven (`data`, `series`) SVG bar chart supporting grouped/stacked bars and optional SVG textures.\r\n *\r\n * @example\r\n * ```tsx\r\n * \r\n * ```\r\n */" + "export interface BarChartProps extends ComponentPropsWithoutRef<'div'> {\n data: Record[];\n series: BarChartSeries[];\n /** @default '100%' */\n height?: number | string;\n /** @default true */\n showGrid?: boolean;\n /** @default true */\n showLabels?: boolean;\n /** @default true */\n showTooltip?: boolean;\n /** @default true */\n animate?: boolean;\n /** @default 4 */\n barGap?: number;\n /** @default 64 */\n maxBarWidth?: number;\n /** @default true */\n rounded?: boolean;\n /** @default 'none' */\n texture?: BarChartTexture;\n /** @default false */\n showTrack?: boolean;\n /** @default false */\n stacked?: boolean;\n /** @default false */\n showYAxis?: boolean;\n /** @default false */\n showLegend?: boolean;\n /** Key in `data` items used for x-axis and tooltip labels. @default 'label' */\n labelKey?: string;\n /** Custom formatter for Y-axis ticks and tooltip values. */\n valueFormatter?: (value: number) => string;\n /** Accessible label for the chart SVG. @default 'Bar chart' */\n ariaLabel?: string;\n}\n\n/**\n * Prop-driven (`data`, `series`) SVG bar chart supporting grouped/stacked bars and optional SVG textures.\n *\n * @example\n * ```tsx\n * \n * ```\n */" ] }, "bento-grid": { @@ -860,11 +861,12 @@ "registryDependencies": [], "exports": [ "LineChart", + "buildLineChartPath", "useLineChart" ], "propsDefinitions": [ - "export interface LineChartProps extends React.ComponentPropsWithoutRef<'div'> {\r\n data: Record[];\r\n series: LineChartSeries[];\r\n /** @default true */\r\n showGrid?: boolean;\r\n /** @default true */\r\n showLabels?: boolean;\r\n /** @default true */\r\n showTooltip?: boolean;\r\n /** @default true */\r\n animate?: boolean;\r\n}\r\n\r\n/**\r\n * Prop-driven (`data`, `series`) multi-series SVG line chart with interactive hover tooltips.\r\n *\r\n * @example\r\n * ```tsx\r\n * \r\n * ```\r\n */", - "export interface UseLineChartProps {\n data: Record[];\n series: LineChartSeries[];\n}" + "export interface LineChartProps extends React.ComponentPropsWithoutRef<'div'> {\n data: Record[];\n series: LineChartSeries[];\n /** Optional explicit height. When omitted, defaults to a 2.5:1 aspect ratio. */\n height?: number | string;\n /** @default true */\n showGrid?: boolean;\n /** @default true */\n showLabels?: boolean;\n /** @default true */\n showTooltip?: boolean;\n /** @default true */\n animate?: boolean;\n /** @default 'linear' */\n curve?: 'linear' | 'smooth';\n /** @default true */\n showDots?: boolean | 'hover';\n /** @default false */\n showYAxis?: boolean;\n /** @default false */\n showLegend?: boolean;\n /** Key in `data` items used for x-axis and tooltip labels. @default 'label' */\n labelKey?: string;\n /** Custom formatter for Y-axis ticks and tooltip values. */\n valueFormatter?: (value: number) => string;\n /** Accessible label for the chart SVG. @default 'Line chart' */\n ariaLabel?: string;\n}\n\n/**\n * Prop-driven (`data`, `series`) multi-series SVG line chart with interactive hover tooltips.\n *\n * @example\n * ```tsx\n * \n * ```\n */", + "export interface UseLineChartProps {\n data: Record[];\n series: LineChartSeries[];\n width?: number;\n svgHeight?: number;\n}" ] }, "listtile": { @@ -1078,8 +1080,8 @@ "usePieChart" ], "propsDefinitions": [ - "export interface PieChartProps extends React.ComponentPropsWithoutRef<'div'> {\r\n data: PieChartDataItem[];\r\n /** @default 0 */\r\n innerRadius?: number;\r\n /** @default true */\r\n showLabels?: boolean;\r\n /** @default true */\r\n showTooltip?: boolean;\r\n /** @default true */\r\n animate?: boolean;\r\n /** @default 'none' */\r\n texture?: PieChartTexture;\r\n}\r\n\r\n/**\r\n * Prop-driven (`data`) SVG pie or donut chart with optional inner radius and tooltips.\r\n *\r\n * @example\r\n * ```tsx\r\n * \r\n * ```\r\n */", - "export interface UsePieChartProps {\r\n data: PieChartDataItem[];\r\n innerRadius: number;\r\n showTooltip: boolean;\r\n}" + "export interface PieChartProps extends React.ComponentPropsWithoutRef<'div'> {\n data: PieChartDataItem[];\n /** @default 0 */\n innerRadius?: number;\n /** @default true */\n showLabels?: boolean;\n /** @default true */\n showTooltip?: boolean;\n /** @default true */\n animate?: boolean;\n /** @default 'none' */\n texture?: PieChartTexture;\n /** Custom formatter for tooltip values. */\n valueFormatter?: (value: number) => string;\n /** Accessible label for the chart SVG. @default 'Pie chart' */\n ariaLabel?: string;\n}\n\n/**\n * Prop-driven (`data`) SVG pie or donut chart with optional inner radius and tooltips.\n *\n * @example\n * ```tsx\n * \n * ```\n */", + "export interface UsePieChartProps {\n data: PieChartDataItem[];\n innerRadius: number;\n showTooltip: boolean;\n}" ] }, "popover": { @@ -1190,8 +1192,8 @@ "RadioCard" ], "propsDefinitions": [ - "export interface RadioCardGroupProps\n extends Omit, 'onChange'>,\n VariantProps {\n value?: string;\n defaultValue?: string;\n onValueChange?: (value: string) => void;\n name?: string;\n label?: React.ReactNode;\n valueLabel?: React.ReactNode;\n size?: RadioCardSize;\n indicator?: RadioCardIndicator;\n disabled?: boolean;\n ref?: React.Ref;\n}\n\n/**\n * Accessible group container for `RadioCard` options with optional header label,\n * active value summary, keyboard arrow navigation, and responsive grid columns.\n *\n * @example\n * ```tsx\n * \n * \n * \n * ```\n */", - "export interface RadioCardProps\n extends Omit, 'title' | 'value' | 'onSelect'> {\n value: string;\n title: React.ReactNode;\n description?: React.ReactNode;\n leading?: React.ReactNode;\n trailing?: React.ReactNode;\n size?: RadioCardSize;\n indicator?: RadioCardIndicator;\n disabled?: boolean;\n ref?: React.Ref;\n}\n\n/**\n * Selectable option card for use inside `RadioCardGroup`.\n *\n * @example\n * ```tsx\n * }\n * />\n * ```\n */" + "export interface RadioCardGroupProps\r\n extends Omit, 'onChange'>,\r\n VariantProps {\r\n value?: string;\r\n defaultValue?: string;\r\n onValueChange?: (value: string) => void;\r\n name?: string;\r\n label?: React.ReactNode;\r\n valueLabel?: React.ReactNode;\r\n size?: RadioCardSize;\r\n indicator?: RadioCardIndicator;\r\n disabled?: boolean;\r\n ref?: React.Ref;\r\n}\r\n\r\n/**\r\n * Accessible group container for `RadioCard` options with optional header label,\r\n * active value summary, keyboard arrow navigation, and responsive grid columns.\r\n *\r\n * @example\r\n * ```tsx\r\n * \r\n * \r\n * \r\n * ```\r\n */", + "export interface RadioCardProps\r\n extends Omit, 'title' | 'value' | 'onSelect'> {\r\n value: string;\r\n title: React.ReactNode;\r\n description?: React.ReactNode;\r\n leading?: React.ReactNode;\r\n trailing?: React.ReactNode;\r\n size?: RadioCardSize;\r\n indicator?: RadioCardIndicator;\r\n disabled?: boolean;\r\n ref?: React.Ref;\r\n}\r\n\r\n/**\r\n * Selectable option card for use inside `RadioCardGroup`.\r\n *\r\n * @example\r\n * ```tsx\r\n * }\r\n * />\r\n * ```\r\n */" ] }, "scrollarea": { diff --git a/src/dashkit/AreaChart/AreaChart.test.tsx b/src/dashkit/AreaChart/AreaChart.test.tsx index e594367d..0ac51908 100644 --- a/src/dashkit/AreaChart/AreaChart.test.tsx +++ b/src/dashkit/AreaChart/AreaChart.test.tsx @@ -57,4 +57,38 @@ describe('AreaChart', () => { expect(linePath).toBeInTheDocument(); expect(linePath?.getAttribute('stroke-width')).toBe('3'); }); + + it('handles single data point and zero values without NaN coordinates', () => { + const { container } = render( + + ); + const paths = container.querySelectorAll('path'); + expect(paths.length).toBeGreaterThanOrEqual(2); + paths.forEach((p) => { + expect(p.getAttribute('d')).not.toContain('NaN'); + }); + }); + + it('supports smooth curves, Y-axis, legend, and custom labelKey', () => { + render( + `$${v}`} + animate={false} + /> + ); + expect(screen.getByText('Apr')).toBeInTheDocument(); + expect(screen.getByText('Revenue')).toBeInTheDocument(); + expect(screen.getByText('$0')).toBeInTheDocument(); + }); }); diff --git a/src/dashkit/AreaChart/AreaChart.tsx b/src/dashkit/AreaChart/AreaChart.tsx index 244f5211..6bef4fe9 100644 --- a/src/dashkit/AreaChart/AreaChart.tsx +++ b/src/dashkit/AreaChart/AreaChart.tsx @@ -2,7 +2,7 @@ import * as React from 'react'; import { motion } from 'framer-motion'; import { cn } from '../utils/cn'; -import { useAreaChart, type AreaChartSeries } from './useAreaChart'; +import { buildAreaLinePath, useAreaChart, type AreaChartSeries } from './useAreaChart'; const DEFAULT_COLORS = [ 'var(--color-chart-1)', @@ -12,6 +12,8 @@ const DEFAULT_COLORS = [ 'var(--color-chart-5)', ]; +const defaultFormatter = (value: number) => value.toLocaleString(); + export interface AreaChartProps extends React.ComponentPropsWithoutRef<'div'> { data: Record[]; series: AreaChartSeries[]; @@ -25,6 +27,20 @@ export interface AreaChartProps extends React.ComponentPropsWithoutRef<'div'> { showTooltip?: boolean; /** @default true */ animate?: boolean; + /** @default 'linear' */ + curve?: 'linear' | 'smooth'; + /** @default true */ + showDots?: boolean | 'hover'; + /** @default false */ + showYAxis?: boolean; + /** @default false */ + showLegend?: boolean; + /** Key in `data` items used for x-axis and tooltip labels. @default 'label' */ + labelKey?: string; + /** Custom formatter for Y-axis ticks and tooltip values. */ + valueFormatter?: (value: number) => string; + /** Accessible label for the chart SVG. @default 'Area chart' */ + ariaLabel?: string; } /** @@ -33,7 +49,7 @@ export interface AreaChartProps extends React.ComponentPropsWithoutRef<'div'> { * @example * ```tsx * * ``` @@ -49,18 +65,28 @@ export const AreaChart = React.forwardRef(functi showLabels = true, showTooltip = true, animate = true, + curve = 'linear', + showDots = true, + showYAxis = false, + showLegend = false, + labelKey = 'label', + valueFormatter = defaultFormatter, + ariaLabel = 'Area chart', ...props }, ref ) { + const chartId = React.useId().replace(/[^a-zA-Z0-9-_]/g, ''); const { chartRef, hoveredIndex, tooltipPos, allSeriesPoints, handleMouseMove, + handleTouchMove, setHoveredIndex, isNearTop, + maxVal, width, svgHeight } = useAreaChart({ @@ -73,6 +99,15 @@ export const AreaChart = React.forwardRef(functi return null; } + const hoveredItem = hoveredIndex !== null ? data[hoveredIndex] : undefined; + const hoverLineX = + hoveredIndex !== null + ? data.length === 1 + ? width / 2 + : (hoveredIndex / (data.length - 1)) * width + : 0; + const yTicks = [1, 0.75, 0.5, 0.25, 0]; + return (
(functi style={{ height: typeof height === 'number' ? `${height}px` : height, ...style }} {...props} > -
- setHoveredIndex(null)} - > - - {allSeriesPoints.map(s => ( - - - - +
+ {showYAxis && ( +
+ {yTicks.map((ratio) => ( + + {valueFormatter(Math.round(maxVal * ratio))} + ))} - - - {showGrid && [0.25, 0.5, 0.75, 1].map((line, i) => ( - - ))} +
+ )} - {showTooltip && hoveredIndex !== null && ( - - )} +
+ setHoveredIndex(null)} + onTouchMove={handleTouchMove} + onTouchEnd={() => setHoveredIndex(null)} + > + + {allSeriesPoints.map(s => ( + + + + + ))} + - {allSeriesPoints.map((s) => { - const linePath = s.points.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p.x} ${p.y}`).join(' '); - const areaPath = `${linePath} L ${width} ${svgHeight} L 0 ${svgHeight} Z`; - - return ( - - - - - ); - })} - - -
- {allSeriesPoints.map((s) => ( - s.points.map((p, i) => ( - ( + - )) - ))} -
+ ))} - {showTooltip && hoveredIndex !== null && ( -
)} - style={{ - left: tooltipPos.x, - top: tooltipPos.y - }} - > -
- - {data[hoveredIndex].label} - + + {allSeriesPoints.map((s) => { + const linePath = buildAreaLinePath(s.points, curve, svgHeight); + const firstX = s.points[0]?.x ?? 0; + const lastX = s.points[s.points.length - 1]?.x ?? width; + const areaPath = `${linePath} L ${lastX} ${svgHeight} L ${firstX} ${svgHeight} Z`; + + return ( + + + + + ); + })} + + + {showDots !== false && ( +
+ {allSeriesPoints.map((s) => ( + s.points.map((p, i) => { + const isActive = hoveredIndex === i; + if (showDots === 'hover' && !isActive) return null; + + return ( + + ); + }) + ))}
- {series.map(s => ( -
-
-
- {s.label} -
- - {Number(data[hoveredIndex][s.key]).toLocaleString()} + )} + + {showTooltip && hoveredItem && ( +
+
+ + {hoveredItem[labelKey] ?? hoveredItem.label}
- ))} -
- )} + {allSeriesPoints.map(s => ( +
+
+
+ {s.label} +
+ + {valueFormatter(Number(hoveredItem[s.key]) || 0)} + +
+ ))} +
+ )} +
{showLabels && ( -
+
{data.map((d, i) => ( (functi hoveredIndex === i && "text-foreground" )} > - {d.label} + {d[labelKey] ?? d.label} ))}
)} + + {showLegend && ( +
+ {allSeriesPoints.map((s) => ( +
+ + {s.label} +
+ ))} +
+ )}
); }); diff --git a/src/dashkit/AreaChart/useAreaChart.ts b/src/dashkit/AreaChart/useAreaChart.ts index 6142c657..9e8ba94d 100644 --- a/src/dashkit/AreaChart/useAreaChart.ts +++ b/src/dashkit/AreaChart/useAreaChart.ts @@ -17,6 +17,35 @@ export interface UseAreaChartProps { defaultColors?: string[]; } +export function buildAreaLinePath( + points: { x: number; y: number }[], + curve: 'linear' | 'smooth' = 'linear', + svgHeight = 400 +): string { + if (points.length === 0) return ''; + if (points.length === 1) return `M ${points[0].x} ${points[0].y}`; + if (curve === 'linear' || points.length === 2) { + return points.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p.x} ${p.y}`).join(' '); + } + + const clampY = (y: number) => Math.max(0, Math.min(svgHeight, y)); + let path = `M ${points[0].x} ${points[0].y}`; + for (let i = 0; i < points.length - 1; i++) { + const p0 = points[Math.max(0, i - 1)]; + const p1 = points[i]; + const p2 = points[i + 1]; + const p3 = points[Math.min(points.length - 1, i + 2)]; + + const cp1x = p1.x + (p2.x - p0.x) / 6; + const cp1y = clampY(p1.y + (p2.y - p0.y) / 6); + const cp2x = p2.x - (p3.x - p1.x) / 6; + const cp2y = clampY(p2.y - (p3.y - p1.y) / 6); + + path += ` C ${cp1x} ${cp1y}, ${cp2x} ${cp2y}, ${p2.x} ${p2.y}`; + } + return path; +} + export function useAreaChart({ data, series, @@ -29,10 +58,11 @@ export function useAreaChart({ const [tooltipPos, setTooltipPos] = React.useState<{ x: number; y: number }>({ x: 0, y: 0 }); const maxVal = React.useMemo(() => { - return Math.max( - ...data.flatMap(d => series.map(s => Number(d[s.key]) || 0)), + const rawMax = Math.max( + ...data.flatMap((d) => series.map((s) => Number(d[s.key]) || 0)), 0 - ) * 1.1; + ); + return rawMax === 0 ? 1 : rawMax * 1.1; }, [data, series]); const minVal = 0; @@ -41,7 +71,7 @@ export function useAreaChart({ const getSeriesPoints = React.useCallback((seriesKey: string) => { return data.map((d, i) => { const value = Number(d[seriesKey]) || 0; - const x = (i / (data.length - 1)) * width; + const x = data.length === 1 ? width / 2 : (i / (data.length - 1)) * width; const y = svgHeight - ((value - minVal) / range) * svgHeight; return { x, y, value }; }); @@ -58,28 +88,54 @@ export function useAreaChart({ })); }, [series, defaultColors, getSeriesPoints]); - const handleMouseMove = (e: React.MouseEvent) => { + const updateHoverFromClientX = React.useCallback((clientX: number) => { const svg = chartRef.current; - if (!svg) return; + if (!svg || data.length === 0) return; const rect = svg.getBoundingClientRect(); - const x = e.clientX - rect.left; - const normalizedX = (x / rect.width) * width; + if (rect.width === 0) return; - const index = Math.round((normalizedX / width) * (data.length - 1)); - const clampedIndex = Math.max(0, Math.min(data.length - 1, index)); + const x = clientX - rect.left; + const clampedIndex = + data.length === 1 + ? 0 + : Math.max( + 0, + Math.min( + data.length - 1, + Math.round((x / rect.width) * (data.length - 1)) + ) + ); setHoveredIndex(clampedIndex); - const highestY = Math.min(...allSeriesPoints.map(s => s.points[clampedIndex].y)); + const highestY = Math.min( + ...allSeriesPoints.map((s) => s.points[clampedIndex]?.y ?? svgHeight) + ); const tooltipWidth = 140; - const rawX = (clampedIndex / (data.length - 1)) * rect.width; - const clampedX = Math.max(tooltipWidth / 2 + 8, Math.min(rect.width - tooltipWidth / 2 - 8, rawX)); + const rawX = + data.length === 1 + ? rect.width / 2 + : (clampedIndex / (data.length - 1)) * rect.width; + const clampedX = Math.max( + tooltipWidth / 2 + 8, + Math.min(rect.width - tooltipWidth / 2 - 8, rawX) + ); setTooltipPos({ x: clampedX, y: (highestY / svgHeight) * rect.height }); + }, [allSeriesPoints, data.length, svgHeight]); + + const handleMouseMove = (e: React.MouseEvent) => { + updateHoverFromClientX(e.clientX); + }; + + const handleTouchMove = (e: React.TouchEvent) => { + if (e.touches.length > 0) { + updateHoverFromClientX(e.touches[0].clientX); + } }; const isNearTop = tooltipPos.y < 100; @@ -90,8 +146,10 @@ export function useAreaChart({ tooltipPos, allSeriesPoints, handleMouseMove, + handleTouchMove, setHoveredIndex, isNearTop, + maxVal, width, svgHeight }; diff --git a/src/dashkit/BarChart/BarChart.test.tsx b/src/dashkit/BarChart/BarChart.test.tsx index 9fe10539..67199b9a 100644 --- a/src/dashkit/BarChart/BarChart.test.tsx +++ b/src/dashkit/BarChart/BarChart.test.tsx @@ -51,4 +51,39 @@ describe('BarChart', () => { // groupWidth is 1000 / 2 = 500; groupPadding is (500 - 48) / 2 = 226 expect(rects[0].getAttribute('x')).toBe('226'); }); + + it('handles all-zero values without NaN attributes', () => { + const { container } = render( + + ); + const rects = container.querySelectorAll('rect'); + expect(rects).toHaveLength(2); + rects.forEach((r) => { + expect(r.getAttribute('y')).not.toBe('NaN'); + expect(r.getAttribute('height')).not.toBe('NaN'); + }); + }); + + it('supports stacked bars, showYAxis, and showLegend', () => { + const { container } = render( + `$${v}`} + animate={false} + /> + ); + const rects = container.querySelectorAll('rect'); + expect(rects).toHaveLength(4); + expect(rects[0].getAttribute('x')).toBe(rects[1].getAttribute('x')); + expect(screen.getByText('Series 1')).toBeInTheDocument(); + expect(screen.getByText('$0')).toBeInTheDocument(); + }); }); diff --git a/src/dashkit/BarChart/BarChart.tsx b/src/dashkit/BarChart/BarChart.tsx index 9cf44551..9295cebf 100644 --- a/src/dashkit/BarChart/BarChart.tsx +++ b/src/dashkit/BarChart/BarChart.tsx @@ -11,6 +11,8 @@ export interface BarChartSeries { export type BarChartTexture = 'none' | 'striped' | 'dots' | 'grid' | 'gradient'; +const defaultFormatter = (value: number) => value.toLocaleString(); + export interface BarChartProps extends ComponentPropsWithoutRef<'div'> { data: Record[]; series: BarChartSeries[]; @@ -34,6 +36,18 @@ export interface BarChartProps extends ComponentPropsWithoutRef<'div'> { texture?: BarChartTexture; /** @default false */ showTrack?: boolean; + /** @default false */ + stacked?: boolean; + /** @default false */ + showYAxis?: boolean; + /** @default false */ + showLegend?: boolean; + /** Key in `data` items used for x-axis and tooltip labels. @default 'label' */ + labelKey?: string; + /** Custom formatter for Y-axis ticks and tooltip values. */ + valueFormatter?: (value: number) => string; + /** Accessible label for the chart SVG. @default 'Bar chart' */ + ariaLabel?: string; } /** @@ -63,6 +77,12 @@ export const BarChart = forwardRef(function BarCh rounded = true, texture = 'none', showTrack = false, + stacked = false, + showYAxis = false, + showLegend = false, + labelKey = 'label', + valueFormatter = defaultFormatter, + ariaLabel = 'Bar chart', ...props }, ref @@ -75,6 +95,7 @@ export const BarChart = forwardRef(function BarCh setHoveredIndex, validSeries, minVal, + maxVal, range, width, svgHeight, @@ -82,11 +103,15 @@ export const BarChart = forwardRef(function BarCh groupPadding, barWidth, handleMouseMove, + handleTouchMove, isNearTop - } = useBarChart({ data, series, barGap, maxBarWidth }); + } = useBarChart({ data, series, barGap, maxBarWidth, stacked }); if (!data || data.length === 0 || !series || series.length === 0) return null; + const hoveredItem = hoveredIndex !== null ? data[hoveredIndex] : undefined; + const yTicks = [1, 0.75, 0.5, 0.25, 0]; + return (
(function BarCh style={{ height: typeof height === 'number' ? `${height}px` : height, ...style }} {...props} > - setHoveredIndex(null)} - > - - - - - - - - - - - - - - - +
+ {showYAxis && ( +
+ {yTicks.map((ratio) => ( + + {valueFormatter(Math.round(maxVal * ratio))} + + ))} +
+ )} - {showGrid && [0.25, 0.5, 0.75, 1].map((line, i) => ( - - ))} +
+ setHoveredIndex(null)} + onTouchMove={handleTouchMove} + onTouchEnd={() => setHoveredIndex(null)} + > + + + + + + + + + + + + + + + - {data.map((d, dataIdx) => ( - - {validSeries.map((s, seriesIdx) => { - const value = Number(d[s.key]) || 0; - const barHeight = ((value - minVal) / range) * svgHeight; - const x = dataIdx * groupWidth + groupPadding + seriesIdx * (barWidth + barGap); - const y = svgHeight - barHeight; - const rx = rounded ? Math.min(barWidth / 2, 6) : 0; + {showGrid && [0.25, 0.5, 0.75, 1].map((line, i) => ( + + ))} + {data.map((d, dataIdx) => { + let stackedOffset = 0; return ( - - {showTrack && ( - - )} - - {texture && texture !== 'none' && ( - - )} - + + {validSeries.map((s, seriesIdx) => { + const value = Number(d[s.key]) || 0; + const barHeight = Math.max(0, ((value - minVal) / range) * svgHeight); + const x = stacked + ? dataIdx * groupWidth + groupPadding + : dataIdx * groupWidth + groupPadding + seriesIdx * (barWidth + barGap); + const y = stacked + ? svgHeight - stackedOffset - barHeight + : svgHeight - barHeight; + if (stacked) { + stackedOffset += barHeight; + } + const isTopStacked = !stacked || seriesIdx === validSeries.length - 1; + const rx = rounded && isTopStacked ? Math.min(barWidth / 2, 6) : 0; + + return ( + + {showTrack && (!stacked || seriesIdx === 0) && ( + + )} + + {texture && texture !== 'none' && ( + + )} + + ); + })} + ); })} - - ))} - + - {showTooltip && hoveredIndex !== null && ( -
-
- - {data[hoveredIndex].label} - -
- {validSeries.map(s => ( -
-
-
- {s.label} + {showTooltip && hoveredItem && ( +
+
+ + {hoveredItem[labelKey] ?? hoveredItem.label} +
- - {Number(data[hoveredIndex][s.key]).toLocaleString()} - + {validSeries.map(s => ( +
+
+
+ {s.label} +
+ + {valueFormatter(Number(hoveredItem[s.key]) || 0)} + +
+ ))}
- ))} + )}
- )} +
{showLabels && ( -
+
{data.map((d, i) => (
(function BarCh hoveredIndex === i && 'text-foreground' )} > - {d.label} + {d[labelKey] ?? d.label}
))}
)} + + {showLegend && ( +
+ {validSeries.map((s) => ( +
+ + {s.label} +
+ ))} +
+ )}
); }); diff --git a/src/dashkit/BarChart/useBarChart.ts b/src/dashkit/BarChart/useBarChart.ts index 4da44e6e..ebab0841 100644 --- a/src/dashkit/BarChart/useBarChart.ts +++ b/src/dashkit/BarChart/useBarChart.ts @@ -14,12 +14,19 @@ interface UseBarChartProps { series: BarChartSeries[]; barGap: number; maxBarWidth: number; + stacked?: boolean; } -export function useBarChart({ data, series, barGap, maxBarWidth }: UseBarChartProps) { +export function useBarChart({ + data, + series, + barGap, + maxBarWidth, + stacked = false +}: UseBarChartProps) { const chartRef = React.useRef(null); const [hoveredIndex, setHoveredIndex] = React.useState(null); - const [tooltipPos, setTooltipPos] = React.useState<{ x: number, y: number }>({ x: 0, y: 0 }); + const [tooltipPos, setTooltipPos] = React.useState<{ x: number; y: number }>({ x: 0, y: 0 }); const validSeries = React.useMemo(() => series.map((s, i) => ({ @@ -28,35 +35,50 @@ export function useBarChart({ data, series, barGap, maxBarWidth }: UseBarChartPr })), [series] ); - const maxVal = React.useMemo(() => - Math.max( - ...data.flatMap(d => validSeries.map(s => Number(d[s.key]) || 0)), - 0 - ) * 1.1, [data, validSeries] - ); + const maxVal = React.useMemo(() => { + if (!data || data.length === 0 || validSeries.length === 0) return 1; + const rawMax = stacked + ? Math.max( + ...data.map((d) => + validSeries.reduce((sum, s) => sum + (Number(d[s.key]) || 0), 0) + ), + 0 + ) + : Math.max( + ...data.flatMap((d) => validSeries.map((s) => Number(d[s.key]) || 0)), + 0 + ); + return rawMax === 0 ? 1 : rawMax * 1.1; + }, [data, validSeries, stacked]); const minVal = 0; - const range = maxVal - minVal; + const range = maxVal - minVal || 1; const width = 1000; const svgHeight = 400; const groupWidth = data.length > 0 ? width / data.length : 0; const maxBarsContainerWidth = groupWidth * 0.8; - const rawBarWidth = validSeries.length > 0 - ? (maxBarsContainerWidth - (validSeries.length - 1) * barGap) / validSeries.length - : 0; + const rawBarWidth = stacked + ? maxBarsContainerWidth + : validSeries.length > 0 + ? (maxBarsContainerWidth - (validSeries.length - 1) * barGap) / validSeries.length + : 0; const barWidth = Math.max(0, Math.min(rawBarWidth, maxBarWidth)); - const barsContainerWidth = validSeries.length > 0 - ? validSeries.length * barWidth + (validSeries.length - 1) * barGap - : 0; + const barsContainerWidth = stacked + ? barWidth + : validSeries.length > 0 + ? validSeries.length * barWidth + (validSeries.length - 1) * barGap + : 0; const groupPadding = (groupWidth - barsContainerWidth) / 2; - const handleMouseMove = (e: React.MouseEvent) => { + const updateHoverFromClientX = React.useCallback((clientX: number) => { const svg = chartRef.current; - if (!svg) return; + if (!svg || data.length === 0 || groupWidth === 0) return; const rect = svg.getBoundingClientRect(); - const x = e.clientX - rect.left; + if (rect.width === 0) return; + + const x = clientX - rect.left; const normalizedX = (x / rect.width) * width; const index = Math.floor(normalizedX / groupWidth); @@ -67,15 +89,30 @@ export function useBarChart({ data, series, barGap, maxBarWidth }: UseBarChartPr const tooltipWidth = 140; const centerX = clampedIndex * groupWidth + groupWidth / 2; const tooltipX = (centerX / width) * rect.width; - const clampedX = Math.max(tooltipWidth / 2 + 8, Math.min(rect.width - tooltipWidth / 2 - 8, tooltipX)); - - const groupMaxVal = Math.max(...validSeries.map(s => Number(data[clampedIndex][s.key]) || 0), 0); + const clampedX = Math.max( + tooltipWidth / 2 + 8, + Math.min(rect.width - tooltipWidth / 2 - 8, tooltipX) + ); + + const groupMaxVal = stacked + ? validSeries.reduce((sum, s) => sum + (Number(data[clampedIndex][s.key]) || 0), 0) + : Math.max(...validSeries.map((s) => Number(data[clampedIndex][s.key]) || 0), 0); const highestY = svgHeight - ((groupMaxVal - minVal) / range) * svgHeight; setTooltipPos({ x: clampedX, y: (highestY / svgHeight) * rect.height }); + }, [data, groupWidth, minVal, range, stacked, svgHeight, validSeries]); + + const handleMouseMove = (e: React.MouseEvent) => { + updateHoverFromClientX(e.clientX); + }; + + const handleTouchMove = (e: React.TouchEvent) => { + if (e.touches.length > 0) { + updateHoverFromClientX(e.touches[0].clientX); + } }; const isNearTop = tooltipPos.y < 100; @@ -87,6 +124,7 @@ export function useBarChart({ data, series, barGap, maxBarWidth }: UseBarChartPr setHoveredIndex, validSeries, minVal, + maxVal, range, width, svgHeight, @@ -94,6 +132,7 @@ export function useBarChart({ data, series, barGap, maxBarWidth }: UseBarChartPr groupPadding, barWidth, handleMouseMove, + handleTouchMove, isNearTop }; } diff --git a/src/dashkit/LineChart/LineChart.test.tsx b/src/dashkit/LineChart/LineChart.test.tsx index 9faca4ed..ac893a75 100644 --- a/src/dashkit/LineChart/LineChart.test.tsx +++ b/src/dashkit/LineChart/LineChart.test.tsx @@ -34,4 +34,36 @@ describe('LineChart', () => { expect(screen.getByText(/Jan/i)).toBeInTheDocument(); expect(screen.getByText(/Feb/i)).toBeInTheDocument(); }); + + it('handles single data point and all-zero values without NaN', () => { + const { container } = render( + + ); + const path = container.querySelector('path'); + expect(path).toBeInTheDocument(); + expect(path?.getAttribute('d')).not.toContain('NaN'); + }); + + it('applies height, showYAxis, showLegend, and showDots="hover"', () => { + const { container } = render( + `${v}ms`} + animate={false} + /> + ); + expect(container.firstChild).toHaveStyle('height: 300px'); + expect(screen.getByText('Series 1')).toBeInTheDocument(); + expect(screen.getByText('0ms')).toBeInTheDocument(); + expect(container.querySelectorAll('.rounded-full')).toHaveLength(1); // only legend dot + }); }); diff --git a/src/dashkit/LineChart/LineChart.tsx b/src/dashkit/LineChart/LineChart.tsx index 50e1a30d..5551aea9 100644 --- a/src/dashkit/LineChart/LineChart.tsx +++ b/src/dashkit/LineChart/LineChart.tsx @@ -1,12 +1,14 @@ import * as React from 'react'; import { motion } from 'framer-motion'; import { cn } from '../utils/cn'; -import { useLineChart } from './useLineChart'; +import { buildLineChartPath, useLineChart } from './useLineChart'; export interface LineChartSeries { key: string; label: string; color?: string; + strokeDasharray?: string; + strokeWidth?: number; } const DEFAULT_COLORS = [ @@ -17,9 +19,13 @@ const DEFAULT_COLORS = [ 'var(--color-chart-5)', ]; +const defaultFormatter = (value: number) => value.toLocaleString(); + export interface LineChartProps extends React.ComponentPropsWithoutRef<'div'> { data: Record[]; series: LineChartSeries[]; + /** Optional explicit height. When omitted, defaults to a 2.5:1 aspect ratio. */ + height?: number | string; /** @default true */ showGrid?: boolean; /** @default true */ @@ -28,6 +34,20 @@ export interface LineChartProps extends React.ComponentPropsWithoutRef<'div'> { showTooltip?: boolean; /** @default true */ animate?: boolean; + /** @default 'linear' */ + curve?: 'linear' | 'smooth'; + /** @default true */ + showDots?: boolean | 'hover'; + /** @default false */ + showYAxis?: boolean; + /** @default false */ + showLegend?: boolean; + /** Key in `data` items used for x-axis and tooltip labels. @default 'label' */ + labelKey?: string; + /** Custom formatter for Y-axis ticks and tooltip values. */ + valueFormatter?: (value: number) => string; + /** Accessible label for the chart SVG. @default 'Line chart' */ + ariaLabel?: string; } /** @@ -36,7 +56,7 @@ export interface LineChartProps extends React.ComponentPropsWithoutRef<'div'> { * @example * ```tsx * * ``` @@ -45,18 +65,28 @@ export const LineChart = React.forwardRef(functi { data, series, + height, className, + style, showGrid = true, showLabels = true, showTooltip = true, animate = true, + curve = 'linear', + showDots = true, + showYAxis = false, + showLegend = false, + labelKey = 'label', + valueFormatter = defaultFormatter, + ariaLabel = 'Line chart', ...props }, ref ) { const validSeries = React.useMemo(() => series.map((s, i) => ({ ...s, - color: s.color || DEFAULT_COLORS[i % DEFAULT_COLORS.length] + color: s.color || DEFAULT_COLORS[i % DEFAULT_COLORS.length], + strokeWidth: s.strokeWidth ?? 2.5, })), [series]); const { @@ -66,144 +96,224 @@ export const LineChart = React.forwardRef(functi tooltipPos, allSeriesPoints, handleMouseMove, + handleTouchMove, isNearTop, + maxVal, width, svgHeight } = useLineChart({ data, series: validSeries }); if (!data || data.length === 0 || !series || series.length === 0) return null; - return ( -
-
- setHoveredIndex(null)} - > - {showGrid && [0.25, 0.5, 0.75, 1].map((line, i) => ( - - ))} + const hoveredItem = hoveredIndex !== null ? data[hoveredIndex] : undefined; + const hoverLineX = + hoveredIndex !== null + ? data.length === 1 + ? width / 2 + : (hoveredIndex / (data.length - 1)) * width + : 0; + const yTicks = [1, 0.75, 0.5, 0.25, 0]; - {showTooltip && hoveredIndex !== null && ( - - )} + return ( +
+
+ {showYAxis && ( +
+ {yTicks.map((ratio) => ( + + {valueFormatter(Math.round(maxVal * ratio))} + + ))} +
+ )} - {allSeriesPoints.map((s) => { - const linePath = s.points.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p.x} ${p.y}`).join(' '); - - return ( - + setHoveredIndex(null)} + onTouchMove={handleTouchMove} + onTouchEnd={() => setHoveredIndex(null)} + > + {showGrid && [0.25, 0.5, 0.75, 1].map((line, i) => ( + - ); - })} - - -
- {allSeriesPoints.map((s) => ( - s.points.map((p, i) => ( - - )) - ))} -
-
+ )} + + {allSeriesPoints.map((s) => { + const linePath = buildLineChartPath(s.points, curve, svgHeight); + + return ( + + ); + })} + - {showTooltip && hoveredIndex !== null && ( -
+ {allSeriesPoints.map((s) => ( + s.points.map((p, i) => { + const isActive = hoveredIndex === i; + if (showDots === 'hover' && !isActive) return null; + + return ( + + ); + }) + ))} +
)} - style={{ - left: tooltipPos.x, - top: tooltipPos.y - }} - > -
- - {data[hoveredIndex].label} - -
- {validSeries.map(s => ( -
-
-
- {s.label} + + {showTooltip && hoveredItem && ( +
+
+ + {hoveredItem[labelKey] ?? hoveredItem.label} +
- - {Number(data[hoveredIndex][s.key]).toLocaleString()} - + {validSeries.map(s => ( +
+
+
+ {s.label} +
+ + {valueFormatter(Number(hoveredItem[s.key]) || 0)} + +
+ ))}
- ))} + )}
- )} +
{showLabels && ( -
+
{data.map((d, i) => ( - {d.label} + {d[labelKey] ?? d.label} ))}
)} + + {showLegend && ( +
+ {validSeries.map((s) => ( +
+ + {s.label} +
+ ))} +
+ )}
); }); diff --git a/src/dashkit/LineChart/useLineChart.ts b/src/dashkit/LineChart/useLineChart.ts index 54c93ccf..9005ca92 100644 --- a/src/dashkit/LineChart/useLineChart.ts +++ b/src/dashkit/LineChart/useLineChart.ts @@ -4,75 +4,123 @@ import { type LineChartSeries } from './LineChart'; export interface UseLineChartProps { data: Record[]; series: LineChartSeries[]; + width?: number; + svgHeight?: number; } -export function useLineChart({ data, series }: UseLineChartProps) { - const chartRef = React.useRef(null); - const [hoveredIndex, setHoveredIndex] = React.useState(null); - const [tooltipPos, setTooltipPos] = React.useState<{ x: number, y: number }>({ x: 0, y: 0 }); - - const width = 1000; - const svgHeight = 400; - - if (!data || data.length === 0 || !series || series.length === 0) { - return { - chartRef, - hoveredIndex, - setHoveredIndex, - tooltipPos, - allSeriesPoints: [], - handleMouseMove: () => {}, - isNearTop: false, - width, - svgHeight - }; +export function buildLineChartPath( + points: { x: number; y: number }[], + curve: 'linear' | 'smooth' = 'linear', + svgHeight = 400 +): string { + if (points.length === 0) return ''; + if (points.length === 1) return `M ${points[0].x} ${points[0].y}`; + if (curve === 'linear' || points.length === 2) { + return points.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p.x} ${p.y}`).join(' '); } - const maxVal = Math.max( - ...data.flatMap(d => series.map(s => Number(d[s.key]) || 0)), - 0 - ) * 1.1; + const clampY = (y: number) => Math.max(0, Math.min(svgHeight, y)); + let path = `M ${points[0].x} ${points[0].y}`; + for (let i = 0; i < points.length - 1; i++) { + const p0 = points[Math.max(0, i - 1)]; + const p1 = points[i]; + const p2 = points[i + 1]; + const p3 = points[Math.min(points.length - 1, i + 2)]; - const minVal = 0; - const range = maxVal - minVal; - - const getSeriesPoints = (seriesKey: string) => { - return data.map((d, i) => { - const value = Number(d[seriesKey]) || 0; - const x = (i / (data.length - 1)) * width; - const y = svgHeight - ((value - minVal) / range) * svgHeight; - return { x, y, value }; - }); - }; + const cp1x = p1.x + (p2.x - p0.x) / 6; + const cp1y = clampY(p1.y + (p2.y - p0.y) / 6); + const cp2x = p2.x - (p3.x - p1.x) / 6; + const cp2y = clampY(p2.y - (p3.y - p1.y) / 6); - const allSeriesPoints = series.map(s => ({ - ...s, - points: getSeriesPoints(s.key) - })); + path += ` C ${cp1x} ${cp1y}, ${cp2x} ${cp2y}, ${p2.x} ${p2.y}`; + } + return path; +} - const handleMouseMove = (e: React.MouseEvent) => { +export function useLineChart({ + data, + series, + width = 1000, + svgHeight = 400 +}: UseLineChartProps) { + const chartRef = React.useRef(null); + const [hoveredIndex, setHoveredIndex] = React.useState(null); + const [tooltipPos, setTooltipPos] = React.useState<{ x: number; y: number }>({ x: 0, y: 0 }); + + const maxVal = React.useMemo(() => { + if (!data || data.length === 0 || !series || series.length === 0) return 1; + const rawMax = Math.max( + ...data.flatMap((d) => series.map((s) => Number(d[s.key]) || 0)), + 0 + ); + return rawMax === 0 ? 1 : rawMax * 1.1; + }, [data, series]); + + const minVal = 0; + const range = maxVal - minVal || 1; + + const allSeriesPoints = React.useMemo(() => { + if (!data || data.length === 0 || !series || series.length === 0) return []; + return series.map((s) => ({ + ...s, + points: data.map((d, i) => { + const value = Number(d[s.key]) || 0; + const x = data.length === 1 ? width / 2 : (i / (data.length - 1)) * width; + const y = svgHeight - ((value - minVal) / range) * svgHeight; + return { x, y, value }; + }) + })); + }, [data, series, width, svgHeight, range, minVal]); + + const updateHoverFromClientX = React.useCallback((clientX: number) => { const svg = chartRef.current; - if (!svg) return; + if (!svg || data.length === 0) return; const rect = svg.getBoundingClientRect(); - const x = e.clientX - rect.left; - const normalizedX = (x / rect.width) * width; - - const index = Math.round((normalizedX / width) * (data.length - 1)); - const clampedIndex = Math.max(0, Math.min(data.length - 1, index)); + if (rect.width === 0) return; + + const x = clientX - rect.left; + const clampedIndex = + data.length === 1 + ? 0 + : Math.max( + 0, + Math.min( + data.length - 1, + Math.round((x / rect.width) * (data.length - 1)) + ) + ); setHoveredIndex(clampedIndex); - const highestY = Math.min(...allSeriesPoints.map(s => s.points[clampedIndex].y)); + const highestY = Math.min( + ...allSeriesPoints.map((s) => s.points[clampedIndex]?.y ?? svgHeight) + ); const tooltipWidth = 140; - const rawX = (clampedIndex / (data.length - 1)) * rect.width; - const clampedX = Math.max(tooltipWidth / 2 + 8, Math.min(rect.width - tooltipWidth / 2 - 8, rawX)); + const rawX = + data.length === 1 + ? rect.width / 2 + : (clampedIndex / (data.length - 1)) * rect.width; + const clampedX = Math.max( + tooltipWidth / 2 + 8, + Math.min(rect.width - tooltipWidth / 2 - 8, rawX) + ); setTooltipPos({ x: clampedX, y: (highestY / svgHeight) * rect.height }); + }, [allSeriesPoints, data.length, svgHeight]); + + const handleMouseMove = (e: React.MouseEvent) => { + updateHoverFromClientX(e.clientX); + }; + + const handleTouchMove = (e: React.TouchEvent) => { + if (e.touches.length > 0) { + updateHoverFromClientX(e.touches[0].clientX); + } }; const isNearTop = tooltipPos.y < 100; @@ -84,7 +132,9 @@ export function useLineChart({ data, series }: UseLineChartProps) { tooltipPos, allSeriesPoints, handleMouseMove, + handleTouchMove, isNearTop, + maxVal, width, svgHeight }; diff --git a/src/dashkit/PieChart/PieChart.test.tsx b/src/dashkit/PieChart/PieChart.test.tsx index 0686fd3c..bcb4a626 100644 --- a/src/dashkit/PieChart/PieChart.test.tsx +++ b/src/dashkit/PieChart/PieChart.test.tsx @@ -55,4 +55,26 @@ describe('PieChart', () => { expect(paths).toHaveLength(3); expect(paths[1].getAttribute('fill')).toMatch(/^url\(#pie-texture-striped-/); }); + + it('renders a full-circle slice when one item represents 100%', () => { + const { container } = render( + + ); + const paths = container.querySelectorAll('path'); + expect(paths).toHaveLength(1); + expect(paths[0].getAttribute('d')).not.toContain('NaN'); + expect(paths[0].getAttribute('d')).toContain('A '); + }); + + it('handles zero-total data safely without NaN', () => { + const { container } = render( + + ); + expect(container.querySelector('svg')).toBeInTheDocument(); + expect(container.querySelectorAll('path')).toHaveLength(0); + }); }); diff --git a/src/dashkit/PieChart/PieChart.tsx b/src/dashkit/PieChart/PieChart.tsx index 4d04c855..143c6b20 100644 --- a/src/dashkit/PieChart/PieChart.tsx +++ b/src/dashkit/PieChart/PieChart.tsx @@ -21,6 +21,8 @@ const DEFAULT_COLORS = [ 'var(--color-chart-5)', ]; +const defaultFormatter = (value: number) => value.toLocaleString(); + export interface PieChartProps extends React.ComponentPropsWithoutRef<'div'> { data: PieChartDataItem[]; /** @default 0 */ @@ -33,6 +35,10 @@ export interface PieChartProps extends React.ComponentPropsWithoutRef<'div'> { animate?: boolean; /** @default 'none' */ texture?: PieChartTexture; + /** Custom formatter for tooltip values. */ + valueFormatter?: (value: number) => string; + /** Accessible label for the chart SVG. @default 'Pie chart' */ + ariaLabel?: string; } /** @@ -40,7 +46,7 @@ export interface PieChartProps extends React.ComponentPropsWithoutRef<'div'> { * * @example * ```tsx - * + * * ``` */ export const PieChart = React.forwardRef(function PieChart( @@ -52,6 +58,8 @@ export const PieChart = React.forwardRef(function showTooltip = true, animate = true, texture = 'none', + valueFormatter = defaultFormatter, + ariaLabel = 'Pie chart', ...props }, ref @@ -70,6 +78,7 @@ export const PieChart = React.forwardRef(function containerRef, slices, handleMouseMove, + handleTouchMove, isNearTop, total, size, @@ -87,6 +96,10 @@ export const PieChart = React.forwardRef(function if (!data || data.length === 0) return null; + const hoveredItem = hoveredIndex !== null ? validData[hoveredIndex] : undefined; + const hoveredPercent = + hoveredItem && total > 0 ? ((Math.max(0, hoveredItem.value) / total) * 100).toFixed(1) : '0.0'; + return (
(function >
setHoveredIndex(null)} + onTouchEnd={() => setHoveredIndex(null)} > (function {slices.map((slice, i) => { + if (!slice.path) return null; const sliceTexture = slice.texture || texture; return ( (function transition: { type: 'spring', stiffness: 400, damping: 25 } }} onMouseMove={(e) => handleMouseMove(e, i)} - onMouseLeave={() => setHoveredIndex(null)} + onTouchMove={(e) => handleTouchMove(e, i)} /> {sliceTexture && sliceTexture !== 'none' && ( (function })} - {showTooltip && hoveredIndex !== null && ( + {showTooltip && hoveredItem && (
(function }} >
-
- {validData[hoveredIndex].label} +
+ {hoveredItem.label}
-
- - {validData[hoveredIndex].value.toLocaleString()} - - ({((validData[hoveredIndex].value / total) * 100).toFixed(1)}%) - - +
+ + {valueFormatter(hoveredItem.value)} + + + ({hoveredPercent}%) +
)}
+ {showLabels && ( -
+
{validData.map((item, i) => (
setHoveredIndex(i)} + onMouseLeave={() => setHoveredIndex(null)} className={cn( - 'flex items-center gap-2 transition-opacity duration-200', + 'flex items-center gap-2 transition-opacity duration-200 cursor-default', hoveredIndex !== null && hoveredIndex !== i && 'opacity-40' )} > -
- +
+ {item.label}
diff --git a/src/dashkit/PieChart/usePieChart.ts b/src/dashkit/PieChart/usePieChart.ts index fdb24d71..fff2fbc7 100644 --- a/src/dashkit/PieChart/usePieChart.ts +++ b/src/dashkit/PieChart/usePieChart.ts @@ -9,7 +9,7 @@ export interface UsePieChartProps { export function usePieChart({ data, innerRadius, showTooltip }: UsePieChartProps) { const [hoveredIndex, setHoveredIndex] = React.useState(null); - const [tooltipPos, setTooltipPos] = React.useState<{ x: number, y: number }>({ x: 0, y: 0 }); + const [tooltipPos, setTooltipPos] = React.useState<{ x: number; y: number }>({ x: 0, y: 0 }); const containerRef = React.useRef(null); if (!data || data.length === 0) { @@ -20,6 +20,7 @@ export function usePieChart({ data, innerRadius, showTooltip }: UsePieChartProps containerRef, slices: [], handleMouseMove: () => {}, + handleTouchMove: () => {}, isNearTop: false, total: 0, size: 400, @@ -27,7 +28,7 @@ export function usePieChart({ data, innerRadius, showTooltip }: UsePieChartProps }; } - const total = data.reduce((sum, item) => sum + item.value, 0); + const total = data.reduce((sum, item) => sum + Math.max(0, item.value), 0); const size = 400; const center = size / 2; const radius = size * 0.4; @@ -38,50 +39,82 @@ export function usePieChart({ data, innerRadius, showTooltip }: UsePieChartProps const slices = data.reduce((acc, item) => { const { slices: currentSlices, currentAngle } = acc; - const angle = (item.value / total) * Math.PI * 2; + const safeValue = Math.max(0, item.value); + const angle = total > 0 ? (safeValue / total) * Math.PI * 2 : 0; const startAngle = currentAngle; const endAngle = currentAngle + angle; - const x1 = center + radius * Math.cos(startAngle); - const y1 = center + radius * Math.sin(startAngle); - const x2 = center + radius * Math.cos(endAngle); - const y2 = center + radius * Math.sin(endAngle); + let path = ''; + if (angle >= Math.PI * 2 - 0.0001) { + // Full-circle fallback: split into two 180° arcs so SVG doesn't collapse start==end + const outer = [ + `M ${center} ${center - radius}`, + `A ${radius} ${radius} 0 1 1 ${center} ${center + radius}`, + `A ${radius} ${radius} 0 1 1 ${center} ${center - radius}` + ]; + if (holeRadius > 0) { + path = [ + ...outer, + `M ${center} ${center - holeRadius}`, + `A ${holeRadius} ${holeRadius} 0 1 0 ${center} ${center + holeRadius}`, + `A ${holeRadius} ${holeRadius} 0 1 0 ${center} ${center - holeRadius}`, + 'Z' + ].join(' '); + } else { + path = [...outer, 'Z'].join(' '); + } + } else if (angle > 0) { + const x1 = center + radius * Math.cos(startAngle); + const y1 = center + radius * Math.sin(startAngle); + const x2 = center + radius * Math.cos(endAngle); + const y2 = center + radius * Math.sin(endAngle); - const x3 = center + holeRadius * Math.cos(endAngle); - const y3 = center + holeRadius * Math.sin(endAngle); - const x4 = center + holeRadius * Math.cos(startAngle); - const y4 = center + holeRadius * Math.sin(startAngle); + const x3 = center + holeRadius * Math.cos(endAngle); + const y3 = center + holeRadius * Math.sin(endAngle); + const x4 = center + holeRadius * Math.cos(startAngle); + const y4 = center + holeRadius * Math.sin(startAngle); - const largeArc = angle > Math.PI ? 1 : 0; + const largeArc = angle > Math.PI ? 1 : 0; - const path = [ - `M ${x1} ${y1}`, - `A ${radius} ${radius} 0 ${largeArc} 1 ${x2} ${y2}`, - `L ${x3} ${y3}`, - `A ${holeRadius} ${holeRadius} 0 ${largeArc} 0 ${x4} ${y4}`, - 'Z' - ].join(' '); + path = [ + `M ${x1} ${y1}`, + `A ${radius} ${radius} 0 ${largeArc} 1 ${x2} ${y2}`, + `L ${x3} ${y3}`, + `A ${holeRadius} ${holeRadius} 0 ${largeArc} 0 ${x4} ${y4}`, + 'Z' + ].join(' '); + } return { slices: [...currentSlices, { ...item, path, startAngle, endAngle }], currentAngle: endAngle }; }, { - slices: [] as (PieChartDataItem & { path: string, startAngle: number, endAngle: number })[], + slices: [] as (PieChartDataItem & { path: string; startAngle: number; endAngle: number })[], currentAngle: -Math.PI / 2 }).slices; - const handleMouseMove = (e: React.MouseEvent, index: number) => { + const updateTooltipFromCoords = (clientX: number, clientY: number, index: number) => { if (!showTooltip || !containerRef.current) return; const rect = containerRef.current.getBoundingClientRect(); setTooltipPos({ - x: e.clientX - rect.left, - y: e.clientY - rect.top + x: clientX - rect.left, + y: clientY - rect.top }); setHoveredIndex(index); }; + const handleMouseMove = (e: React.MouseEvent, index: number) => { + updateTooltipFromCoords(e.clientX, e.clientY, index); + }; + + const handleTouchMove = (e: React.TouchEvent, index: number) => { + if (e.touches.length > 0) { + updateTooltipFromCoords(e.touches[0].clientX, e.touches[0].clientY, index); + } + }; + const isNearTop = tooltipPos.y < 100; return { @@ -91,6 +124,7 @@ export function usePieChart({ data, innerRadius, showTooltip }: UsePieChartProps containerRef, slices, handleMouseMove, + handleTouchMove, isNearTop, total, size,