@langchain/macaw-components 1.6.2 → 1.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/catalog.json +724 -710
- package/dist/components/BarChart/BarChart.d.ts +1 -1
- package/dist/components/BarChart/BarChart.js +5 -3
- package/dist/components/BarChart/BarChart.js.map +1 -1
- package/dist/components/BarChart/BarChart.types.d.ts +6 -0
- package/dist/components/ChartLegend/ChartLegend.d.ts +17 -0
- package/dist/components/ChartLegend/ChartLegend.js +5 -2
- package/dist/components/ChartLegend/ChartLegend.js.map +1 -1
- package/dist/components/ChartLegend/ChartLegendItemRenderer.d.ts +4 -2
- package/dist/components/ChartLegend/ChartLegendItemRenderer.js +16 -11
- package/dist/components/ChartLegend/ChartLegendItemRenderer.js.map +1 -1
- package/dist/components/ChartLegend/index.d.ts +1 -1
- package/dist/components/ChatConversation/ChatConversation.d.ts +26 -0
- package/dist/components/ChatConversation/ChatConversation.js +115 -0
- package/dist/components/ChatConversation/ChatConversation.js.map +1 -0
- package/dist/components/ChatConversation/index.d.ts +2 -0
- package/dist/components/ChatConversation/index.js +2 -0
- package/dist/components/DonutChart/DonutChart.d.ts +8 -1
- package/dist/components/DonutChart/DonutChart.js +3 -2
- package/dist/components/DonutChart/DonutChart.js.map +1 -1
- package/dist/components/DonutChart/DonutChart.utils.d.ts +10 -7
- package/dist/components/DonutChart/DonutChart.utils.js +13 -11
- package/dist/components/DonutChart/DonutChart.utils.js.map +1 -1
- package/dist/components/LineChart/LineChart.d.ts +1 -1
- package/dist/components/LineChart/LineChart.js +4 -3
- package/dist/components/LineChart/LineChart.js.map +1 -1
- package/dist/components/LineChart/LineChart.types.d.ts +7 -0
- package/dist/components/RadarChart/RadarChart.d.ts +3 -0
- package/dist/components/RadarChart/RadarChart.js +3 -4
- package/dist/components/RadarChart/RadarChart.js.map +1 -1
- package/dist/components/index.d.ts +2 -0
- package/dist/components/index.js +2 -1
- package/dist/index.js +2 -1
- package/dist/utilities.css +1 -1
- package/docs/DESIGN.md +2 -0
- package/package.json +6 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ChatConversation.js","names":[],"sources":["../../../src/components/ChatConversation/ChatConversation.tsx"],"sourcesContent":["import {\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n type CSSProperties,\n type ReactNode,\n type Ref,\n} from 'react';\n\nimport { CaretDownIcon } from '@phosphor-icons/react/dist/ssr/CaretDown';\n\nimport { cn } from '../../utils/cn';\nimport { mergeRefs } from '../../utils/merge-refs';\nimport { Button } from '../Button';\n\n/** Distance from the bottom, in px, that still counts as reading the latest output. */\nconst FOLLOW_THRESHOLD = 48;\n\nconst COLUMN_CLASS_NAME = 'mx-auto w-full min-w-0 max-w-3xl px-space-4';\n\n// Caps the top fade at 32px. Inline because the unlayered `.scroll-mask-t`\n// rule in base.css overrides utility classes.\nconst VIEWPORT_MASK_STYLE = {\n '--scroll-mask-fade-from-t': 'calc(100% - 2rem)',\n} as CSSProperties;\n\nexport interface ChatConversationProps {\n /** Messages, or a host-provided empty or loading state. */\n children: ReactNode;\n /** Fixed content above the scrolling messages; the host supplies its styling. */\n header?: ReactNode;\n /** Fixed content below the messages, such as a composer. Shares the message column. */\n footer?: ReactNode;\n /** Accessible name for the region; the message log is named \"{label} messages\". */\n label?: string;\n className?: string;\n /**\n * The scrolling element. Older messages inserted above the viewport are not\n * anchored; hosts that load history upward can adjust `scrollTop` here.\n */\n viewportRef?: Ref<HTMLDivElement>;\n}\n\n/**\n * Bounded-height chat layout that follows new output while the reader is at\n * the bottom. Remount with a conversation `key` when switching threads.\n *\n * The message log doesn't announce changes (`aria-live=\"off\"`), since streamed\n * text would be read out word by word. Announce completed replies from a\n * polite `role=\"status\"` region in the host.\n */\nexport function ChatConversation({\n children,\n header,\n footer,\n label = 'Conversation',\n className,\n viewportRef: externalViewportRef,\n}: ChatConversationProps) {\n const viewportRef = useRef<HTMLDivElement>(null);\n const contentRef = useRef<HTMLDivElement>(null);\n const followingRef = useRef(true);\n const [isNearBottom, setIsNearBottom] = useState(true);\n const mergedViewportRef = useMemo(\n () => mergeRefs([viewportRef, externalViewportRef]),\n [externalViewportRef]\n );\n\n useLayoutEffect(() => {\n const viewport = viewportRef.current;\n const content = contentRef.current;\n if (!viewport || !content) return;\n\n const followContent = () => {\n if (!followingRef.current) return;\n viewport.scrollTop = viewport.scrollHeight;\n };\n\n let lastScrollTop = viewport.scrollTop;\n const handleScroll = () => {\n const { scrollTop, scrollHeight, clientHeight } = viewport;\n const nearBottom =\n scrollHeight - clientHeight - scrollTop <= FOLLOW_THRESHOLD;\n // Only scrolling up stops following. The scroll event from our own pin\n // can land after more content arrives, leaving a gap the reader didn't make.\n followingRef.current =\n nearBottom || (followingRef.current && scrollTop >= lastScrollTop);\n lastScrollTop = scrollTop;\n setIsNearBottom(followingRef.current);\n };\n\n followContent();\n const observer = new ResizeObserver(() => {\n followContent();\n handleScroll();\n });\n observer.observe(viewport);\n observer.observe(content);\n viewport.addEventListener('scroll', handleScroll, { passive: true });\n return () => {\n observer.disconnect();\n viewport.removeEventListener('scroll', handleScroll);\n };\n }, []);\n\n function scrollToLatest() {\n const viewport = viewportRef.current;\n if (!viewport) return;\n followingRef.current = true;\n viewport.scrollTop = viewport.scrollHeight;\n setIsNearBottom(true);\n // The jump button disappears; keep keyboard focus in the reading region.\n viewport.focus({ preventScroll: true });\n }\n\n return (\n <section\n aria-label={label}\n className={cn(\n 'flex h-full min-h-0 min-w-0 flex-col overflow-hidden bg-surface-level-1 text-primary',\n className\n )}\n >\n {header != null && <div className=\"min-w-0 shrink-0\">{header}</div>}\n <div className=\"relative flex min-h-0 flex-1 flex-col\">\n <div\n ref={mergedViewportRef}\n role=\"log\"\n aria-label={`${label} messages`}\n aria-live=\"off\"\n tabIndex={0}\n style={VIEWPORT_MASK_STYLE}\n className=\"peer scroll-mask-t min-h-0 flex-1 overflow-y-auto overflow-x-hidden overscroll-contain outline-hidden [scrollbar-gutter:stable_both-edges]\"\n >\n <div\n ref={contentRef}\n className={cn(\n COLUMN_CLASS_NAME,\n 'flex min-h-full flex-col gap-space-6 py-space-5 pb-space-9'\n )}\n >\n {children}\n </div>\n </div>\n {/* The focus ring sits on an overlay so the viewport's scroll mask can't fade it. */}\n <div\n aria-hidden\n className=\"pointer-events-none absolute inset-0 ring-inset ring-focus peer-focus-visible:ring-2\"\n />\n {!isNearBottom && (\n <div className=\"pointer-events-none absolute inset-x-0 bottom-0 flex justify-center pb-space-3\">\n <Button\n color=\"secondary\"\n size=\"md\"\n leftDecorator={CaretDownIcon}\n className=\"pointer-events-auto shadow-md hover:bg-elevated pointer-coarse:h-11\"\n onClick={scrollToLatest}\n >\n Jump to latest\n </Button>\n </div>\n )}\n </div>\n {footer != null && (\n <div className={cn(COLUMN_CLASS_NAME, 'shrink-0 py-space-3')}>\n {footer}\n </div>\n )}\n </section>\n );\n}\n"],"mappings":";;;;;;;;AAiBA,IAAM,mBAAmB;AAEzB,IAAM,oBAAoB;AAI1B,IAAM,sBAAsB,EAC1B,6BAA6B,oBAC/B;;;;;;;;;AA2BA,SAAgB,iBAAiB,EAC/B,UACA,QACA,QACA,QAAQ,gBACR,WACA,aAAa,uBACW;CACxB,MAAM,cAAc,OAAuB,IAAI;CAC/C,MAAM,aAAa,OAAuB,IAAI;CAC9C,MAAM,eAAe,OAAO,IAAI;CAChC,MAAM,CAAC,cAAc,mBAAmB,SAAS,IAAI;CACrD,MAAM,oBAAoB,cAClB,UAAU,CAAC,aAAa,mBAAmB,CAAC,GAClD,CAAC,mBAAmB,CACtB;CAEA,sBAAsB;EACpB,MAAM,WAAW,YAAY;EAC7B,MAAM,UAAU,WAAW;EAC3B,IAAI,CAAC,YAAY,CAAC,SAAS;EAE3B,MAAM,sBAAsB;GAC1B,IAAI,CAAC,aAAa,SAAS;GAC3B,SAAS,YAAY,SAAS;EAChC;EAEA,IAAI,gBAAgB,SAAS;EAC7B,MAAM,qBAAqB;GACzB,MAAM,EAAE,WAA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,WAAW,GAAG,mBAAmB,qBAAqB;IACxD,UAAA;GACE,CAAA;EAEA;;AAEb"}
|
|
@@ -44,6 +44,13 @@ export type DonutChartProps = Omit<HTMLAttributes<HTMLDivElement>, 'children' |
|
|
|
44
44
|
* the data it was made against cannot empty the chart.
|
|
45
45
|
*/
|
|
46
46
|
selectedIds?: ReadonlySet<string>;
|
|
47
|
+
/**
|
|
48
|
+
* Segments left out of the donut, whatever `selectedIds` holds. They stay
|
|
49
|
+
* in the legend, marked excluded with a 0% share; to toggle them from the
|
|
50
|
+
* legend, set `legendProps.itemClickAction` to `exclude` and wire
|
|
51
|
+
* `onItemClick`. IDs address the collated list, as `selectedIds` does.
|
|
52
|
+
*/
|
|
53
|
+
excludedIds?: ReadonlySet<string>;
|
|
47
54
|
/**
|
|
48
55
|
* Number to render in the donut hole.
|
|
49
56
|
*/
|
|
@@ -97,5 +104,5 @@ export type DonutChartProps = Omit<HTMLAttributes<HTMLDivElement>, 'children' |
|
|
|
97
104
|
* absorbs any segment flagged `isOther`.
|
|
98
105
|
|
|
99
106
|
*/
|
|
100
|
-
export declare const DonutChart: ({ segments, selectedIds, centerNumber, centerDescriptor, scaleCenterNumberSize, activeSegmentId, activeLegendItemId, shouldAnimate, getSegmentAriaLabel, isRendering, otherCollationThreshold, showLegend, legendProps, formatValue, onSegmentPointerMove, onSegmentPointerOut, onSegmentPointerUp, onSegmentFocus, onSegmentBlur, className, ...rest }: DonutChartProps) => import("react").JSX.Element;
|
|
107
|
+
export declare const DonutChart: ({ segments, selectedIds, excludedIds, centerNumber, centerDescriptor, scaleCenterNumberSize, activeSegmentId, activeLegendItemId, shouldAnimate, getSegmentAriaLabel, isRendering, otherCollationThreshold, showLegend, legendProps, formatValue, onSegmentPointerMove, onSegmentPointerOut, onSegmentPointerUp, onSegmentFocus, onSegmentBlur, className, ...rest }: DonutChartProps) => import("react").JSX.Element;
|
|
101
108
|
export {};
|
|
@@ -62,14 +62,14 @@ var AnimatedDonutArc = ({ arc, path, animationProgress, animationStartAngle, ani
|
|
|
62
62
|
* absorbs any segment flagged `isOther`.
|
|
63
63
|
|
|
64
64
|
*/
|
|
65
|
-
var DonutChart = ({ segments, selectedIds, centerNumber, centerDescriptor, scaleCenterNumberSize = false, activeSegmentId, activeLegendItemId, shouldAnimate = true, getSegmentAriaLabel, isRendering = true, otherCollationThreshold, showLegend = true, legendProps, formatValue = formatSegmentValue, onSegmentPointerMove, onSegmentPointerOut, onSegmentPointerUp, onSegmentFocus, onSegmentBlur, className, ...rest }) => {
|
|
65
|
+
var DonutChart = ({ segments, selectedIds, excludedIds, centerNumber, centerDescriptor, scaleCenterNumberSize = false, activeSegmentId, activeLegendItemId, shouldAnimate = true, getSegmentAriaLabel, isRendering = true, otherCollationThreshold, showLegend = true, legendProps, formatValue = formatSegmentValue, onSegmentPointerMove, onSegmentPointerOut, onSegmentPointerUp, onSegmentFocus, onSegmentBlur, className, ...rest }) => {
|
|
66
66
|
const [activeBuiltInLegendItemId, setActiveBuiltInLegendItemId] = useState(null);
|
|
67
67
|
const isReducedMotion = (useReducedMotion() ?? false) || !shouldAnimate;
|
|
68
68
|
const ariaProps = { "aria-label": rest["aria-label"] };
|
|
69
69
|
const rootProps = { ...rest };
|
|
70
70
|
delete rootProps["aria-label"];
|
|
71
71
|
const collatedSegments = collateDonutSegments(segments, otherCollationThreshold);
|
|
72
|
-
const drawnSegments = getDrawnSegments(collatedSegments, selectedIds);
|
|
72
|
+
const drawnSegments = getDrawnSegments(collatedSegments, selectedIds, excludedIds);
|
|
73
73
|
const renderedSegments = drawnSegments.filter((segment) => segment.value > 0);
|
|
74
74
|
const drawnTotal = sumSegmentValues(drawnSegments);
|
|
75
75
|
const drawnIds = new Set(drawnSegments.map((segment) => segment.id));
|
|
@@ -89,6 +89,7 @@ var DonutChart = ({ segments, selectedIds, centerNumber, centerDescriptor, scale
|
|
|
89
89
|
const legendItems = getDonutLegendItems({
|
|
90
90
|
segments: collatedSegments,
|
|
91
91
|
selectedIds,
|
|
92
|
+
excludedIds,
|
|
92
93
|
drawnIds,
|
|
93
94
|
drawnTotal,
|
|
94
95
|
formatValue
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DonutChart.js","names":[],"sources":["../../../src/components/DonutChart/DonutChart.tsx"],"sourcesContent":["import {\n useState,\n type AriaAttributes,\n type FocusEvent,\n type FocusEventHandler,\n type HTMLAttributes,\n type PointerEvent,\n type PointerEventHandler,\n type ReactNode,\n} from 'react';\n\nimport {\n animated,\n type SpringValue,\n useReducedMotion,\n useSpring,\n} from '@react-spring/web';\nimport { Group } from '@visx/group';\nimport { Pie as Donut } from '@visx/shape';\n\nimport { CHART_DIMMED_OPACITY } from '../../utils/chartConstants';\nimport { cn } from '../../utils/cn';\nimport { ChartLegend, type ChartLegendProps } from '../ChartLegend';\nimport { Text } from '../Text';\nimport {\n collateDonutSegments,\n getDonutLegendItems,\n getDrawnSegments,\n sumSegmentValues,\n} from './DonutChart.utils';\n\n// Viewport-invariant units. The donut renders into a fixed-size viewBox and\n// scales via `preserveAspectRatio=\"xMidYMid meet\"`.\nconst DONUT_VIEWBOX = 200;\nconst DONUT_CENTER = DONUT_VIEWBOX / 2;\nconst DONUT_OUTER_RADIUS = DONUT_CENTER - 8;\nconst DONUT_INNER_RADIUS = DONUT_OUTER_RADIUS * 0.64;\n\nconst numberFormatter = new Intl.NumberFormat('en-US');\n\nconst formatSegmentValue = (value: number) => numberFormatter.format(value);\n\n/**\n * Sizes the center number against the donut hole: `1cqi` is 1% of the hole's\n * width, so a longer value resolves to a smaller size, capped at the heading\n * size so short values do not balloon.\n */\nconst getFittedCenterFontSize = (value: string) =>\n `min(1.75rem, ${100 / (value.length * 0.7)}cqi)`;\n\nexport type DonutChartSegment = {\n id: string;\n label: ReactNode;\n value: number;\n /** Use DS CSS color token; typically a `var(--chart-...)` reference. */\n color: string;\n /**\n * Marks a segment that already stands for a group of others — a remainder the\n * data source rolled up, say. `otherCollationThreshold` merges it with the\n * tail it collates instead of drawing a second \"Other\" beside it.\n */\n isOther?: boolean;\n};\n\ntype DonutArcDatumLike<Datum> = {\n data: Datum;\n value: number;\n index: number;\n startAngle: number;\n endAngle: number;\n padAngle: number;\n};\n\n/**\n * Everything `ChartLegend` accepts except `items`, which the donut derives from\n * `segments`. Namespacing these under `legendProps` keeps `className` and the\n * other DOM attributes on the chart root unambiguous.\n */\ntype DonutChartLegendProps = Omit<ChartLegendProps, 'items'>;\n\n/**\n * `legendProps` only exists while there is a legend to configure: with\n * `showLegend={false}` it narrows to `never`, so autocomplete stops offering it\n * and passing it is a type error rather than a silently ignored prop.\n */\ntype DonutChartLegendConfig =\n | {\n /** Defaults to true. */\n showLegend?: true;\n /** Forwarded to the rendered `ChartLegend`. */\n legendProps?: DonutChartLegendProps;\n }\n | {\n showLegend: false;\n legendProps?: never;\n };\n\nexport type DonutChartProps = Omit<\n HTMLAttributes<HTMLDivElement>,\n 'children' | 'onPointerOut'\n> &\n DonutChartLegendConfig & {\n segments: readonly DonutChartSegment[];\n /**\n * When provided and non-empty, only segments whose IDs are in the set are\n * rendered in the donut. Unselected segments stay in the legend with a 0%\n * share. IDs address the collated list, so the segments behind an \"Other\"\n * slice are selected as `DONUT_OTHER_SEGMENT_ID` rather than individually. A\n * set naming none of those IDs draws everything, so a selection outliving\n * the data it was made against cannot empty the chart.\n */\n selectedIds?: ReadonlySet<string>;\n /**\n * Number to render in the donut hole.\n */\n centerNumber?: string;\n /**\n * Descriptor for the number in the donut hole.\n */\n centerDescriptor?: string;\n /**\n * Scales `centerNumber` to the width of the donut hole.\n */\n scaleCenterNumberSize?: boolean;\n /** Emphasizes one segment and dims the rest. */\n activeSegmentId?: string | null;\n /** Emphasizes the segment represented by one external legend item. Built-in legends set this automatically. */\n activeLegendItemId?: string | null;\n /** Animates segments when they are drawn. Defaults to true. */\n shouldAnimate?: boolean;\n /** Names segments and makes them focusable. */\n getSegmentAriaLabel?: (\n segment: DonutChartSegment\n ) => AriaAttributes['aria-label'];\n /**\n * Set to false to skip drawing the donut. Use it to avoid the work while a\n * parent container is actively resizing. Defaults to true.\n */\n isRendering?: boolean;\n /**\n * Collates segments less than this set number to an \"Other\" slice, automatically merging any segment flagged `isOther`. Do not pass a value to render all segments, even if they are tiny.\n */\n otherCollationThreshold?: number;\n /**\n * Formats each segment's value for the legend. Defaults to a plain\n * `en-US` number; pass a unit-aware formatter for durations, bytes, cost.\n */\n formatValue?: (value: number) => ReactNode;\n onSegmentPointerMove?: (\n segment: DonutChartSegment,\n event: PointerEvent<SVGPathElement>\n ) => void;\n onSegmentPointerOut?: () => void;\n onSegmentPointerUp?: (\n segment: DonutChartSegment,\n event: PointerEvent<SVGPathElement>\n ) => void;\n onSegmentFocus?: (\n segment: DonutChartSegment,\n event: FocusEvent<SVGPathElement>\n ) => void;\n onSegmentBlur?: (\n segment: DonutChartSegment,\n event: FocusEvent<SVGPathElement>\n ) => void;\n };\n\ntype AnimatedDonutArcProps = {\n arc: DonutArcDatumLike<DonutChartSegment>;\n path: (arc: DonutArcDatumLike<DonutChartSegment>) => string | null;\n animationProgress: SpringValue<number>;\n animationStartAngle: number;\n animationEndAngle: number;\n 'aria-label'?: AriaAttributes['aria-label'];\n isDimmed: boolean;\n onPointerMove?: PointerEventHandler<SVGPathElement>;\n onPointerOut?: () => void;\n onPointerUp?: PointerEventHandler<SVGPathElement>;\n onFocus?: FocusEventHandler<SVGPathElement>;\n onBlur?: FocusEventHandler<SVGPathElement>;\n};\n\nconst AnimatedDonutArc = ({\n arc,\n path,\n animationProgress,\n animationStartAngle,\n animationEndAngle,\n isDimmed,\n onPointerMove,\n onPointerOut,\n onPointerUp,\n onFocus,\n onBlur,\n ...ariaProps\n}: AnimatedDonutArcProps) => {\n const isInteractive =\n onPointerMove != null || onPointerOut != null || onPointerUp != null;\n const handlePointerDown = (event: PointerEvent<SVGPathElement>) => {\n // Chromium can match :focus-visible when a focusable SVG path is clicked.\n // Keep the focus indicator for keyboard navigation without showing it for\n // pointer interaction.\n if (\n (event.pointerType === 'mouse' || event.pointerType === 'pen') &&\n event.currentTarget.hasAttribute('tabindex')\n ) {\n event.preventDefault();\n }\n };\n\n return (\n <animated.path\n fill={arc.data.color}\n opacity={isDimmed ? CHART_DIMMED_OPACITY : 1}\n className={cn(\n 'transition-opacity duration-fast focus:outline-hidden focus-visible:stroke-focus focus-visible:stroke-2 motion-reduce:transition-none',\n isInteractive && 'cursor-pointer'\n )}\n d={animationProgress.to((progress) => {\n const revealAngle =\n animationStartAngle +\n (animationEndAngle - animationStartAngle) * progress;\n const endAngle = Math.min(\n arc.endAngle,\n Math.max(arc.startAngle, revealAngle)\n );\n return path({ ...arc, endAngle }) ?? '';\n })}\n role={ariaProps['aria-label'] == null ? undefined : 'graphics-symbol img'}\n tabIndex={ariaProps['aria-label'] == null ? undefined : 0}\n {...ariaProps}\n onPointerMove={onPointerMove}\n onPointerDown={handlePointerDown}\n onPointerOut={onPointerOut}\n onPointerUp={onPointerUp}\n onFocus={onFocus}\n onBlur={onBlur}\n />\n );\n};\n\n/**\n * DonutChart renders a donut and its `ChartLegend` from a flat list of\n * segments. Consumers own the segment palette and pair the chart\n * with `ChartCard` and their own tooltip.\n *\n * The legend sits below the donut in narrow containers and beside it once the\n * container passes 496px. Pass `showLegend={false}` for the donut alone,\n * `legendProps` to configure the legend, and `legendProps.onItemClick` with\n * `selectedIds` to make legend entries filter the donut. A long tail of tiny\n * slices collapses into one \"Other\" slice via `otherCollationThreshold`, which\n * absorbs any segment flagged `isOther`.\n\n */\nexport const DonutChart = ({\n segments,\n selectedIds,\n centerNumber,\n centerDescriptor,\n scaleCenterNumberSize = false,\n activeSegmentId,\n activeLegendItemId,\n shouldAnimate = true,\n getSegmentAriaLabel,\n isRendering = true,\n otherCollationThreshold,\n showLegend = true,\n legendProps,\n formatValue = formatSegmentValue,\n onSegmentPointerMove,\n onSegmentPointerOut,\n onSegmentPointerUp,\n onSegmentFocus,\n onSegmentBlur,\n className,\n ...rest\n}: DonutChartProps) => {\n const [activeBuiltInLegendItemId, setActiveBuiltInLegendItemId] = useState<\n string | null\n >(null);\n const isReducedMotion = (useReducedMotion() ?? false) || !shouldAnimate;\n const ariaProps = { 'aria-label': rest['aria-label'] };\n const rootProps: HTMLAttributes<HTMLDivElement> = { ...rest };\n delete rootProps['aria-label'];\n\n // Collation happens before the selection, so the legend lists the same rows\n // the donut draws arcs for and neither reflows while filtering.\n const collatedSegments = collateDonutSegments(\n segments,\n otherCollationThreshold\n );\n const drawnSegments = getDrawnSegments(collatedSegments, selectedIds);\n const renderedSegments = drawnSegments.filter((segment) => segment.value > 0);\n const drawnTotal = sumSegmentValues(drawnSegments);\n const drawnIds = new Set(drawnSegments.map((segment) => segment.id));\n const drawnArcIds = new Set(renderedSegments.map((segment) => segment.id));\n const hasDrawnSegments = isRendering && drawnTotal > 0;\n const segmentAnimationKey = JSON.stringify(\n renderedSegments.map((segment) => [segment.id, segment.value])\n );\n // A single sweep angle reveals the arcs in sequence, leaving only one moving\n // boundary regardless of how many colored segments the donut contains.\n const [animation] = useSpring(\n () => ({\n from: { progress: 0 },\n to: { progress: hasDrawnSegments ? 1 : 0 },\n reset: true,\n immediate: isReducedMotion,\n }),\n [segmentAnimationKey, hasDrawnSegments, isReducedMotion]\n );\n\n const legendItems = getDonutLegendItems({\n segments: collatedSegments,\n selectedIds,\n drawnIds,\n drawnTotal,\n formatValue,\n });\n const hasLegend = showLegend && collatedSegments.length > 0;\n const legendLayout = legendProps?.layout ?? 'list';\n const requestedActiveLegendItemId =\n (hasLegend ? activeBuiltInLegendItemId : null) ?? activeLegendItemId;\n const renderedActiveLegendItemId =\n requestedActiveLegendItemId != null &&\n drawnArcIds.has(requestedActiveLegendItemId)\n ? requestedActiveLegendItemId\n : null;\n const renderedActiveSegmentId =\n activeSegmentId != null && drawnArcIds.has(activeSegmentId)\n ? activeSegmentId\n : null;\n const activeId = renderedActiveLegendItemId ?? renderedActiveSegmentId;\n\n const donut = (\n <div className=\"relative flex size-full min-h-0 min-w-0 items-center justify-center [&>svg]:max-h-[22.5rem] [&>svg]:max-w-[22.5rem]\">\n <svg\n viewBox={`0 0 ${DONUT_VIEWBOX} ${DONUT_VIEWBOX}`}\n preserveAspectRatio=\"xMidYMid meet\"\n className=\"size-full\"\n role={getSegmentAriaLabel == null ? 'img' : 'graphics-document group'}\n {...ariaProps}\n >\n {isRendering && (\n <>\n {drawnTotal > 0 && (\n <Group\n top={DONUT_CENTER}\n left={DONUT_CENTER}\n className={cn(\n activeId == null &&\n '[&:focus-within>path:not(:focus)]:opacity-[0.45] [&>path:focus]:opacity-100'\n )}\n >\n <Donut\n data={renderedSegments}\n pieValue={(segment) => segment.value}\n pieSort={null}\n pieSortValues={null}\n outerRadius={DONUT_OUTER_RADIUS}\n innerRadius={DONUT_INNER_RADIUS}\n >\n {(donut) => {\n const animationStartAngle = donut.arcs[0]?.startAngle ?? 0;\n const animationEndAngle =\n donut.arcs.at(-1)?.endAngle ?? animationStartAngle;\n return donut.arcs.map((arc) => (\n <AnimatedDonutArc\n key={arc.data.id}\n arc={arc}\n path={donut.path}\n animationProgress={animation.progress}\n animationStartAngle={animationStartAngle}\n animationEndAngle={animationEndAngle}\n aria-label={getSegmentAriaLabel?.(arc.data)}\n isDimmed={activeId != null && activeId !== arc.data.id}\n onPointerMove={\n onSegmentPointerMove == null\n ? undefined\n : (event) => onSegmentPointerMove(arc.data, event)\n }\n onPointerOut={onSegmentPointerOut}\n onPointerUp={\n onSegmentPointerUp == null\n ? undefined\n : (event) => onSegmentPointerUp(arc.data, event)\n }\n onFocus={\n onSegmentFocus == null\n ? undefined\n : (event) => onSegmentFocus(arc.data, event)\n }\n onBlur={\n onSegmentBlur == null\n ? undefined\n : (event) => onSegmentBlur(arc.data, event)\n }\n />\n ));\n }}\n </Donut>\n </Group>\n )}\n {(centerNumber || centerDescriptor) != null && (\n <foreignObject\n x={DONUT_CENTER - DONUT_INNER_RADIUS}\n y={DONUT_CENTER - DONUT_INNER_RADIUS}\n width={DONUT_INNER_RADIUS * 2}\n height={DONUT_INNER_RADIUS * 2}\n className=\"pointer-events-none\"\n >\n <div\n className=\"flex size-full min-w-0 flex-col items-center justify-center\"\n style={{ containerType: 'inline-size' }}\n >\n <Text\n as=\"span\"\n variant=\"h2\"\n weight=\"semibold\"\n className={cn(\n scaleCenterNumberSize && 'block w-full text-center'\n )}\n style={\n scaleCenterNumberSize && centerNumber != null\n ? { fontSize: getFittedCenterFontSize(centerNumber) }\n : undefined\n }\n >\n {centerNumber}\n </Text>\n <Text as=\"span\" variant=\"xs\" color=\"tertiary\">\n {centerDescriptor}\n </Text>\n </div>\n </foreignObject>\n )}\n </>\n )}\n </svg>\n </div>\n );\n\n const legend = (\n <ChartLegend\n aria-label={\n ariaProps['aria-label'] == null\n ? undefined\n : `${ariaProps['aria-label']} legend`\n }\n {...legendProps}\n layout={legendLayout}\n items={legendItems}\n onItemActiveChange={(item) => {\n setActiveBuiltInLegendItemId(item?.id ?? null);\n legendProps?.onItemActiveChange?.(item);\n }}\n />\n );\n\n return (\n <div\n className={cn('size-full min-h-0 min-w-0 @container', className)}\n {...rootProps}\n >\n {hasLegend ? (\n <div\n className={cn(\n 'grid size-full min-h-0 min-w-0 grid-cols-1 items-center justify-stretch',\n legendLayout === 'list'\n ? 'grid-rows-[minmax(0,1fr)_minmax(0,45%)] gap-space-3 @[496px]:grid-cols-2 @[496px]:grid-rows-[minmax(0,1fr)] @[496px]:justify-center @[496px]:gap-space-5'\n : 'grid-rows-[minmax(0,1fr)_auto] gap-space-2'\n )}\n >\n {donut}\n {legendLayout === 'list' ? (\n <div className=\"scroll-mask-t scroll-mask-b h-full min-h-0 min-w-0 overflow-y-auto overflow-x-hidden\">\n <div className=\"flex min-h-full flex-col\">\n <div className=\"my-auto\">{legend}</div>\n </div>\n </div>\n ) : (\n legend\n )}\n </div>\n ) : (\n donut\n )}\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;AAiCA,IAAM,gBAAgB;AACtB,IAAM,eAAe,gBAAgB;AACrC,IAAM,qBAA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BAAwB,YAAY,EAAE,IAClD,KAAA;MAGL,UAAA;KACG,CAAA,GACN,oBAAC,MAAD;MAAM,IAAG;MAAO,SAAQ;MAAK,OAAM;MAChC,UAAA;KACG,CAAA,CACH;;GACQ,CAAA,CAEjB,EAAA,CAAA;EAED,CAAA;CACF,CAAA;CAGP,MAAM,SACJ,oBAAC,aAAD;EACE,cACE,UAAU,iBAAiB,OACvB,KAAA,IACA,GAAG,UAAU,cAAc;EAEjC,GAAI;EACJ,QAAQ;EACR,OAAO;EACP,qBAAqB,SAAS;GAC5B,6BAA6B,MAAM,MAAM,IAAI;GAC7C,aAAa,qBAAqB,IAAI;EACxC;CACD,CAAA;CAGH,OACE,oBAAC,OAAD;EACE,WAAW,GAAG,wCAAwC,SAAS;EAC/D,GAAI;EAEH,UAAA,YACC,qBAAC,OAAD;GACE,WAAW,GACT,2EACA,iBAAiB,SACb,6JACA,4CACN;GANF,UAAA,CAQG,OACA,iBAAiB,SAChB,oBAAC,OAAD;IAAK,WAAU;IACb,UAAA,oBAAC,OAAD;KAAK,WAAU;KACb,UAAA,oBAAC,OAAD;MAAK,WAAU;MAAW,UAAA;KAAY,CAAA;IACnC,CAAA;GACF,CAAA,IAEL,MAEC;EAEL,CAAA,IAAA;CAEC,CAAA;AAET"}
|
|
1
|
+
{"version":3,"file":"DonutChart.js","names":[],"sources":["../../../src/components/DonutChart/DonutChart.tsx"],"sourcesContent":["import {\n useState,\n type AriaAttributes,\n type FocusEvent,\n type FocusEventHandler,\n type HTMLAttributes,\n type PointerEvent,\n type PointerEventHandler,\n type ReactNode,\n} from 'react';\n\nimport {\n animated,\n type SpringValue,\n useReducedMotion,\n useSpring,\n} from '@react-spring/web';\nimport { Group } from '@visx/group';\nimport { Pie as Donut } from '@visx/shape';\n\nimport { CHART_DIMMED_OPACITY } from '../../utils/chartConstants';\nimport { cn } from '../../utils/cn';\nimport { ChartLegend, type ChartLegendProps } from '../ChartLegend';\nimport { Text } from '../Text';\nimport {\n collateDonutSegments,\n getDonutLegendItems,\n getDrawnSegments,\n sumSegmentValues,\n} from './DonutChart.utils';\n\n// Viewport-invariant units. The donut renders into a fixed-size viewBox and\n// scales via `preserveAspectRatio=\"xMidYMid meet\"`.\nconst DONUT_VIEWBOX = 200;\nconst DONUT_CENTER = DONUT_VIEWBOX / 2;\nconst DONUT_OUTER_RADIUS = DONUT_CENTER - 8;\nconst DONUT_INNER_RADIUS = DONUT_OUTER_RADIUS * 0.64;\n\nconst numberFormatter = new Intl.NumberFormat('en-US');\n\nconst formatSegmentValue = (value: number) => numberFormatter.format(value);\n\n/**\n * Sizes the center number against the donut hole: `1cqi` is 1% of the hole's\n * width, so a longer value resolves to a smaller size, capped at the heading\n * size so short values do not balloon.\n */\nconst getFittedCenterFontSize = (value: string) =>\n `min(1.75rem, ${100 / (value.length * 0.7)}cqi)`;\n\nexport type DonutChartSegment = {\n id: string;\n label: ReactNode;\n value: number;\n /** Use DS CSS color token; typically a `var(--chart-...)` reference. */\n color: string;\n /**\n * Marks a segment that already stands for a group of others — a remainder the\n * data source rolled up, say. `otherCollationThreshold` merges it with the\n * tail it collates instead of drawing a second \"Other\" beside it.\n */\n isOther?: boolean;\n};\n\ntype DonutArcDatumLike<Datum> = {\n data: Datum;\n value: number;\n index: number;\n startAngle: number;\n endAngle: number;\n padAngle: number;\n};\n\n/**\n * Everything `ChartLegend` accepts except `items`, which the donut derives from\n * `segments`. Namespacing these under `legendProps` keeps `className` and the\n * other DOM attributes on the chart root unambiguous.\n */\ntype DonutChartLegendProps = Omit<ChartLegendProps, 'items'>;\n\n/**\n * `legendProps` only exists while there is a legend to configure: with\n * `showLegend={false}` it narrows to `never`, so autocomplete stops offering it\n * and passing it is a type error rather than a silently ignored prop.\n */\ntype DonutChartLegendConfig =\n | {\n /** Defaults to true. */\n showLegend?: true;\n /** Forwarded to the rendered `ChartLegend`. */\n legendProps?: DonutChartLegendProps;\n }\n | {\n showLegend: false;\n legendProps?: never;\n };\n\nexport type DonutChartProps = Omit<\n HTMLAttributes<HTMLDivElement>,\n 'children' | 'onPointerOut'\n> &\n DonutChartLegendConfig & {\n segments: readonly DonutChartSegment[];\n /**\n * When provided and non-empty, only segments whose IDs are in the set are\n * rendered in the donut. Unselected segments stay in the legend with a 0%\n * share. IDs address the collated list, so the segments behind an \"Other\"\n * slice are selected as `DONUT_OTHER_SEGMENT_ID` rather than individually. A\n * set naming none of those IDs draws everything, so a selection outliving\n * the data it was made against cannot empty the chart.\n */\n selectedIds?: ReadonlySet<string>;\n /**\n * Segments left out of the donut, whatever `selectedIds` holds. They stay\n * in the legend, marked excluded with a 0% share; to toggle them from the\n * legend, set `legendProps.itemClickAction` to `exclude` and wire\n * `onItemClick`. IDs address the collated list, as `selectedIds` does.\n */\n excludedIds?: ReadonlySet<string>;\n /**\n * Number to render in the donut hole.\n */\n centerNumber?: string;\n /**\n * Descriptor for the number in the donut hole.\n */\n centerDescriptor?: string;\n /**\n * Scales `centerNumber` to the width of the donut hole.\n */\n scaleCenterNumberSize?: boolean;\n /** Emphasizes one segment and dims the rest. */\n activeSegmentId?: string | null;\n /** Emphasizes the segment represented by one external legend item. Built-in legends set this automatically. */\n activeLegendItemId?: string | null;\n /** Animates segments when they are drawn. Defaults to true. */\n shouldAnimate?: boolean;\n /** Names segments and makes them focusable. */\n getSegmentAriaLabel?: (\n segment: DonutChartSegment\n ) => AriaAttributes['aria-label'];\n /**\n * Set to false to skip drawing the donut. Use it to avoid the work while a\n * parent container is actively resizing. Defaults to true.\n */\n isRendering?: boolean;\n /**\n * Collates segments less than this set number to an \"Other\" slice, automatically merging any segment flagged `isOther`. Do not pass a value to render all segments, even if they are tiny.\n */\n otherCollationThreshold?: number;\n /**\n * Formats each segment's value for the legend. Defaults to a plain\n * `en-US` number; pass a unit-aware formatter for durations, bytes, cost.\n */\n formatValue?: (value: number) => ReactNode;\n onSegmentPointerMove?: (\n segment: DonutChartSegment,\n event: PointerEvent<SVGPathElement>\n ) => void;\n onSegmentPointerOut?: () => void;\n onSegmentPointerUp?: (\n segment: DonutChartSegment,\n event: PointerEvent<SVGPathElement>\n ) => void;\n onSegmentFocus?: (\n segment: DonutChartSegment,\n event: FocusEvent<SVGPathElement>\n ) => void;\n onSegmentBlur?: (\n segment: DonutChartSegment,\n event: FocusEvent<SVGPathElement>\n ) => void;\n };\n\ntype AnimatedDonutArcProps = {\n arc: DonutArcDatumLike<DonutChartSegment>;\n path: (arc: DonutArcDatumLike<DonutChartSegment>) => string | null;\n animationProgress: SpringValue<number>;\n animationStartAngle: number;\n animationEndAngle: number;\n 'aria-label'?: AriaAttributes['aria-label'];\n isDimmed: boolean;\n onPointerMove?: PointerEventHandler<SVGPathElement>;\n onPointerOut?: () => void;\n onPointerUp?: PointerEventHandler<SVGPathElement>;\n onFocus?: FocusEventHandler<SVGPathElement>;\n onBlur?: FocusEventHandler<SVGPathElement>;\n};\n\nconst AnimatedDonutArc = ({\n arc,\n path,\n animationProgress,\n animationStartAngle,\n animationEndAngle,\n isDimmed,\n onPointerMove,\n onPointerOut,\n onPointerUp,\n onFocus,\n onBlur,\n ...ariaProps\n}: AnimatedDonutArcProps) => {\n const isInteractive =\n onPointerMove != null || onPointerOut != null || onPointerUp != null;\n const handlePointerDown = (event: PointerEvent<SVGPathElement>) => {\n // Chromium can match :focus-visible when a focusable SVG path is clicked.\n // Keep the focus indicator for keyboard navigation without showing it for\n // pointer interaction.\n if (\n (event.pointerType === 'mouse' || event.pointerType === 'pen') &&\n event.currentTarget.hasAttribute('tabindex')\n ) {\n event.preventDefault();\n }\n };\n\n return (\n <animated.path\n fill={arc.data.color}\n opacity={isDimmed ? CHART_DIMMED_OPACITY : 1}\n className={cn(\n 'transition-opacity duration-fast focus:outline-hidden focus-visible:stroke-focus focus-visible:stroke-2 motion-reduce:transition-none',\n isInteractive && 'cursor-pointer'\n )}\n d={animationProgress.to((progress) => {\n const revealAngle =\n animationStartAngle +\n (animationEndAngle - animationStartAngle) * progress;\n const endAngle = Math.min(\n arc.endAngle,\n Math.max(arc.startAngle, revealAngle)\n );\n return path({ ...arc, endAngle }) ?? '';\n })}\n role={ariaProps['aria-label'] == null ? undefined : 'graphics-symbol img'}\n tabIndex={ariaProps['aria-label'] == null ? undefined : 0}\n {...ariaProps}\n onPointerMove={onPointerMove}\n onPointerDown={handlePointerDown}\n onPointerOut={onPointerOut}\n onPointerUp={onPointerUp}\n onFocus={onFocus}\n onBlur={onBlur}\n />\n );\n};\n\n/**\n * DonutChart renders a donut and its `ChartLegend` from a flat list of\n * segments. Consumers own the segment palette and pair the chart\n * with `ChartCard` and their own tooltip.\n *\n * The legend sits below the donut in narrow containers and beside it once the\n * container passes 496px. Pass `showLegend={false}` for the donut alone,\n * `legendProps` to configure the legend, and `legendProps.onItemClick` with\n * `selectedIds` to make legend entries filter the donut. A long tail of tiny\n * slices collapses into one \"Other\" slice via `otherCollationThreshold`, which\n * absorbs any segment flagged `isOther`.\n\n */\nexport const DonutChart = ({\n segments,\n selectedIds,\n excludedIds,\n centerNumber,\n centerDescriptor,\n scaleCenterNumberSize = false,\n activeSegmentId,\n activeLegendItemId,\n shouldAnimate = true,\n getSegmentAriaLabel,\n isRendering = true,\n otherCollationThreshold,\n showLegend = true,\n legendProps,\n formatValue = formatSegmentValue,\n onSegmentPointerMove,\n onSegmentPointerOut,\n onSegmentPointerUp,\n onSegmentFocus,\n onSegmentBlur,\n className,\n ...rest\n}: DonutChartProps) => {\n const [activeBuiltInLegendItemId, setActiveBuiltInLegendItemId] = useState<\n string | null\n >(null);\n const isReducedMotion = (useReducedMotion() ?? false) || !shouldAnimate;\n const ariaProps = { 'aria-label': rest['aria-label'] };\n const rootProps: HTMLAttributes<HTMLDivElement> = { ...rest };\n delete rootProps['aria-label'];\n\n // Collation happens before the selection, so the legend lists the same rows\n // the donut draws arcs for and neither reflows while filtering.\n const collatedSegments = collateDonutSegments(\n segments,\n otherCollationThreshold\n );\n const drawnSegments = getDrawnSegments(\n collatedSegments,\n selectedIds,\n excludedIds\n );\n const renderedSegments = drawnSegments.filter((segment) => segment.value > 0);\n const drawnTotal = sumSegmentValues(drawnSegments);\n const drawnIds = new Set(drawnSegments.map((segment) => segment.id));\n const drawnArcIds = new Set(renderedSegments.map((segment) => segment.id));\n const hasDrawnSegments = isRendering && drawnTotal > 0;\n const segmentAnimationKey = JSON.stringify(\n renderedSegments.map((segment) => [segment.id, segment.value])\n );\n // A single sweep angle reveals the arcs in sequence, leaving only one moving\n // boundary regardless of how many colored segments the donut contains.\n const [animation] = useSpring(\n () => ({\n from: { progress: 0 },\n to: { progress: hasDrawnSegments ? 1 : 0 },\n reset: true,\n immediate: isReducedMotion,\n }),\n [segmentAnimationKey, hasDrawnSegments, isReducedMotion]\n );\n\n const legendItems = getDonutLegendItems({\n segments: collatedSegments,\n selectedIds,\n excludedIds,\n drawnIds,\n drawnTotal,\n formatValue,\n });\n const hasLegend = showLegend && collatedSegments.length > 0;\n const legendLayout = legendProps?.layout ?? 'list';\n const requestedActiveLegendItemId =\n (hasLegend ? activeBuiltInLegendItemId : null) ?? activeLegendItemId;\n const renderedActiveLegendItemId =\n requestedActiveLegendItemId != null &&\n drawnArcIds.has(requestedActiveLegendItemId)\n ? requestedActiveLegendItemId\n : null;\n const renderedActiveSegmentId =\n activeSegmentId != null && drawnArcIds.has(activeSegmentId)\n ? activeSegmentId\n : null;\n const activeId = renderedActiveLegendItemId ?? renderedActiveSegmentId;\n\n const donut = (\n <div className=\"relative flex size-full min-h-0 min-w-0 items-center justify-center [&>svg]:max-h-[22.5rem] [&>svg]:max-w-[22.5rem]\">\n <svg\n viewBox={`0 0 ${DONUT_VIEWBOX} ${DONUT_VIEWBOX}`}\n preserveAspectRatio=\"xMidYMid meet\"\n className=\"size-full\"\n role={getSegmentAriaLabel == null ? 'img' : 'graphics-document group'}\n {...ariaProps}\n >\n {isRendering && (\n <>\n {drawnTotal > 0 && (\n <Group\n top={DONUT_CENTER}\n left={DONUT_CENTER}\n className={cn(\n activeId == null &&\n '[&:focus-within>path:not(:focus)]:opacity-[0.45] [&>path:focus]:opacity-100'\n )}\n >\n <Donut\n data={renderedSegments}\n pieValue={(segment) => segment.value}\n pieSort={null}\n pieSortValues={null}\n outerRadius={DONUT_OUTER_RADIUS}\n innerRadius={DONUT_INNER_RADIUS}\n >\n {(donut) => {\n const animationStartAngle = donut.arcs[0]?.startAngle ?? 0;\n const animationEndAngle =\n donut.arcs.at(-1)?.endAngle ?? animationStartAngle;\n return donut.arcs.map((arc) => (\n <AnimatedDonutArc\n key={arc.data.id}\n arc={arc}\n path={donut.path}\n animationProgress={animation.progress}\n animationStartAngle={animationStartAngle}\n animationEndAngle={animationEndAngle}\n aria-label={getSegmentAriaLabel?.(arc.data)}\n isDimmed={activeId != null && activeId !== arc.data.id}\n onPointerMove={\n onSegmentPointerMove == null\n ? undefined\n : (event) => onSegmentPointerMove(arc.data, event)\n }\n onPointerOut={onSegmentPointerOut}\n onPointerUp={\n onSegmentPointerUp == null\n ? undefined\n : (event) => onSegmentPointerUp(arc.data, event)\n }\n onFocus={\n onSegmentFocus == null\n ? undefined\n : (event) => onSegmentFocus(arc.data, event)\n }\n onBlur={\n onSegmentBlur == null\n ? undefined\n : (event) => onSegmentBlur(arc.data, event)\n }\n />\n ));\n }}\n </Donut>\n </Group>\n )}\n {(centerNumber || centerDescriptor) != null && (\n <foreignObject\n x={DONUT_CENTER - DONUT_INNER_RADIUS}\n y={DONUT_CENTER - DONUT_INNER_RADIUS}\n width={DONUT_INNER_RADIUS * 2}\n height={DONUT_INNER_RADIUS * 2}\n className=\"pointer-events-none\"\n >\n <div\n className=\"flex size-full min-w-0 flex-col items-center justify-center\"\n style={{ containerType: 'inline-size' }}\n >\n <Text\n as=\"span\"\n variant=\"h2\"\n weight=\"semibold\"\n className={cn(\n scaleCenterNumberSize && 'block w-full text-center'\n )}\n style={\n scaleCenterNumberSize && centerNumber != null\n ? { fontSize: getFittedCenterFontSize(centerNumber) }\n : undefined\n }\n >\n {centerNumber}\n </Text>\n <Text as=\"span\" variant=\"xs\" color=\"tertiary\">\n {centerDescriptor}\n </Text>\n </div>\n </foreignObject>\n )}\n </>\n )}\n </svg>\n </div>\n );\n\n const legend = (\n <ChartLegend\n aria-label={\n ariaProps['aria-label'] == null\n ? undefined\n : `${ariaProps['aria-label']} legend`\n }\n {...legendProps}\n layout={legendLayout}\n items={legendItems}\n onItemActiveChange={(item) => {\n setActiveBuiltInLegendItemId(item?.id ?? null);\n legendProps?.onItemActiveChange?.(item);\n }}\n />\n );\n\n return (\n <div\n className={cn('size-full min-h-0 min-w-0 @container', className)}\n {...rootProps}\n >\n {hasLegend ? (\n <div\n className={cn(\n 'grid size-full min-h-0 min-w-0 grid-cols-1 items-center justify-stretch',\n legendLayout === 'list'\n ? 'grid-rows-[minmax(0,1fr)_minmax(0,45%)] gap-space-3 @[496px]:grid-cols-2 @[496px]:grid-rows-[minmax(0,1fr)] @[496px]:justify-center @[496px]:gap-space-5'\n : 'grid-rows-[minmax(0,1fr)_auto] gap-space-2'\n )}\n >\n {donut}\n {legendLayout === 'list' ? (\n <div className=\"scroll-mask-t scroll-mask-b h-full min-h-0 min-w-0 overflow-y-auto overflow-x-hidden\">\n <div className=\"flex min-h-full flex-col\">\n <div className=\"my-auto\">{legend}</div>\n </div>\n </div>\n ) : (\n legend\n )}\n </div>\n ) : (\n donut\n )}\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;AAiCA,IAAM,gBAAgB;AACtB,IAAM,eAAe,gBAAgB;AACrC,IAAM,qBAAqB;AAC3B,IAAM,qBAAqB,qBAAqB;AAEhD,IAAM,kBAAkB,IAAI,KAAK,aAAa,OAAO;AAErD,IAAM,sBAAsB,UAAkB,gBAAgB,OAAO,KAAK;;;;;;AAO1E,IAAM,2BAA2B,UAC/B,gBAAgB,OAAO,MAAM,SAAS,IAAK;AA6I7C,IAAM,oBAAoB,EACxB,KACA,MACA,mBACA,qBACA,mBACA,UACA,eACA,cACA,aACA,SACA,QACA,GAAG,gBACwB;CAC3B,MAAM,gBACJ,iBAAiB,QAAQ,gB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qBAAqB,SAAS;GAC5B,6BAA6B,MAAM,MAAM,IAAI;GAC7C,aAAa,qBAAqB,IAAI;EACxC;CACD,CAAA;CAGH,OACE,oBAAC,OAAD;EACE,WAAW,GAAG,wCAAwC,SAAS;EAC/D,GAAI;EAEH,UAAA,YACC,qBAAC,OAAD;GACE,WAAW,GACT,2EACA,iBAAiB,SACb,6JACA,4CACN;GANF,UAAA,CAQG,OACA,iBAAiB,SAChB,oBAAC,OAAD;IAAK,WAAU;IACb,UAAA,oBAAC,OAAD;KAAK,WAAU;KACb,UAAA,oBAAC,OAAD;MAAK,WAAU;MAAW,UAAA;KAAY,CAAA;IACnC,CAAA;GACF,CAAA,IAEL,MAEC;EAEL,CAAA,IAAA;CAEC,CAAA;AAET"}
|
|
@@ -14,13 +14,15 @@ export declare const sumSegmentValues: (segments: readonly DonutChartSegment[])
|
|
|
14
14
|
*/
|
|
15
15
|
export declare const collateDonutSegments: (segments: readonly DonutChartSegment[], threshold: number | undefined) => readonly DonutChartSegment[];
|
|
16
16
|
/**
|
|
17
|
-
* Filters collated segments to a legend selection
|
|
18
|
-
* draws everything, and so does a
|
|
19
|
-
* has: ids outlive the data they
|
|
20
|
-
*
|
|
21
|
-
* with no row left to toggle the
|
|
17
|
+
* Filters collated segments to a legend selection, then leaves out excluded
|
|
18
|
+
* segments. An empty or absent selection draws everything, and so does a
|
|
19
|
+
* selection that names no segment the donut has: ids outlive the data they
|
|
20
|
+
* came from — a group can be collated away or disappear from a refetch — and
|
|
21
|
+
* drawing nothing would strand the chart empty with no row left to toggle the
|
|
22
|
+
* stale id off. Excluding every segment draws none; their rows stay in the
|
|
23
|
+
* legend to include them again.
|
|
22
24
|
*/
|
|
23
|
-
export declare const getDrawnSegments: (segments: readonly DonutChartSegment[], selectedIds: ReadonlySet<string> | undefined) => DonutChartSegment[];
|
|
25
|
+
export declare const getDrawnSegments: (segments: readonly DonutChartSegment[], selectedIds: ReadonlySet<string> | undefined, excludedIds?: ReadonlySet<string>) => DonutChartSegment[];
|
|
24
26
|
/**
|
|
25
27
|
* Every segment stays in the legend, including filtered-out ones — those report
|
|
26
28
|
* a 0% share so the list does not reflow while filtering. Rows correspond to
|
|
@@ -29,9 +31,10 @@ export declare const getDrawnSegments: (segments: readonly DonutChartSegment[],
|
|
|
29
31
|
* A row reports a share when its arc is drawn rather than when it is selected,
|
|
30
32
|
* so the two cannot disagree about what the donut is showing.
|
|
31
33
|
*/
|
|
32
|
-
export declare const getDonutLegendItems: ({ segments, selectedIds, drawnIds, drawnTotal, formatValue, }: {
|
|
34
|
+
export declare const getDonutLegendItems: ({ segments, selectedIds, excludedIds, drawnIds, drawnTotal, formatValue, }: {
|
|
33
35
|
segments: readonly DonutChartSegment[];
|
|
34
36
|
selectedIds: ReadonlySet<string> | undefined;
|
|
37
|
+
excludedIds?: ReadonlySet<string>;
|
|
35
38
|
drawnIds: ReadonlySet<string>;
|
|
36
39
|
drawnTotal: number;
|
|
37
40
|
formatValue: (value: number) => ReactNode;
|
|
@@ -57,16 +57,17 @@ var collateDonutSegments = (segments, threshold) => {
|
|
|
57
57
|
}];
|
|
58
58
|
};
|
|
59
59
|
/**
|
|
60
|
-
* Filters collated segments to a legend selection
|
|
61
|
-
* draws everything, and so does a
|
|
62
|
-
* has: ids outlive the data they
|
|
63
|
-
*
|
|
64
|
-
* with no row left to toggle the
|
|
60
|
+
* Filters collated segments to a legend selection, then leaves out excluded
|
|
61
|
+
* segments. An empty or absent selection draws everything, and so does a
|
|
62
|
+
* selection that names no segment the donut has: ids outlive the data they
|
|
63
|
+
* came from — a group can be collated away or disappear from a refetch — and
|
|
64
|
+
* drawing nothing would strand the chart empty with no row left to toggle the
|
|
65
|
+
* stale id off. Excluding every segment draws none; their rows stay in the
|
|
66
|
+
* legend to include them again.
|
|
65
67
|
*/
|
|
66
|
-
var getDrawnSegments = (segments, selectedIds) => {
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
return selected.length > 0 ? selected : [...segments];
|
|
68
|
+
var getDrawnSegments = (segments, selectedIds, excludedIds) => {
|
|
69
|
+
const selected = selectedIds == null || selectedIds.size === 0 ? segments : segments.filter((segment) => selectedIds.has(segment.id));
|
|
70
|
+
return (selected.length > 0 ? selected : segments).filter((segment) => !excludedIds?.has(segment.id));
|
|
70
71
|
};
|
|
71
72
|
/**
|
|
72
73
|
* Every segment stays in the legend, including filtered-out ones — those report
|
|
@@ -76,7 +77,7 @@ var getDrawnSegments = (segments, selectedIds) => {
|
|
|
76
77
|
* A row reports a share when its arc is drawn rather than when it is selected,
|
|
77
78
|
* so the two cannot disagree about what the donut is showing.
|
|
78
79
|
*/
|
|
79
|
-
var getDonutLegendItems = ({ segments, selectedIds, drawnIds, drawnTotal, formatValue }) => segments.map((segment) => {
|
|
80
|
+
var getDonutLegendItems = ({ segments, selectedIds, excludedIds, drawnIds, drawnTotal, formatValue }) => segments.map((segment) => {
|
|
80
81
|
const isDrawn = drawnIds.has(segment.id);
|
|
81
82
|
return {
|
|
82
83
|
id: segment.id,
|
|
@@ -84,7 +85,8 @@ var getDonutLegendItems = ({ segments, selectedIds, drawnIds, drawnTotal, format
|
|
|
84
85
|
markerColor: segment.color,
|
|
85
86
|
value: formatValue(segment.value),
|
|
86
87
|
secondaryValue: `${percentFormatter.format(isDrawn && drawnTotal > 0 ? segment.value / drawnTotal * 100 : 0)}%`,
|
|
87
|
-
selected: selectedIds?.has(segment.id) ?? false
|
|
88
|
+
selected: selectedIds?.has(segment.id) ?? false,
|
|
89
|
+
excluded: excludedIds?.has(segment.id) ?? false
|
|
88
90
|
};
|
|
89
91
|
});
|
|
90
92
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DonutChart.utils.js","names":[],"sources":["../../../src/components/DonutChart/DonutChart.utils.ts"],"sourcesContent":["import type { ReactNode } from 'react';\n\nimport { CHART_OTHER_COLOR } from '../../utils/chartColors';\nimport type { ChartLegendItem } from '../ChartLegend';\nimport { DONUT_OTHER_SEGMENT_ID, DONUT_OTHER_SEGMENT_LABEL } from './constants';\nimport type { DonutChartSegment } from './DonutChart';\n\nconst percentFormatter = new Intl.NumberFormat('en-US', {\n maximumFractionDigits: 1,\n});\n\nexport const sumSegmentValues = (segments: readonly DonutChartSegment[]) =>\n segments.reduce((sum, segment) => sum + segment.value, 0);\n\n/**\n * Splits segments into the ones the donut draws on their own and the ones that\n * fold into a single \"Other\": every segment flagged `isOther` or using the\n * reserved Other ID, plus segments below `threshold` percent of the total.\n *\n * `collapses` is false when there is nothing to fold, and also when the only\n * member is an existing Other segment, so replacing it would change its\n * metadata without changing what is drawn.\n */\nconst partitionSegments = (\n segments: readonly DonutChartSegment[],\n threshold: number | undefined\n): {\n kept: readonly DonutChartSegment[];\n members: readonly DonutChartSegment[];\n collapses: boolean;\n} => {\n const total = sumSegmentValues(segments);\n if (threshold == null || total === 0) {\n return { kept: segments, members: [], collapses: false };\n }\n\n const kept: DonutChartSegment[] = [];\n const members: DonutChartSegment[] = [];\n segments.forEach((segment) => {\n if (\n segment.isOther ||\n segment.id === DONUT_OTHER_SEGMENT_ID ||\n (segment.value / total) * 100 < threshold\n ) {\n members.push(segment);\n } else {\n kept.push(segment);\n }\n });\n\n return {\n kept,\n members,\n collapses:\n members.length > 1 ||\n (members.length === 1 &&\n !members[0].isOther &&\n members[0].id !== DONUT_OTHER_SEGMENT_ID),\n };\n};\n\n/**\n * Folds a segment's long tail into one \"Other\" segment appended after the ones\n * that clear `threshold`. Segments already flagged `isOther` — a rollup the\n * data source computed, say — merge into that same segment rather than sitting\n * beside a second one wearing the same label and color. Invalid values are\n * normalized to zero. Without a threshold, valid segments pass through untouched.\n *\n * `DonutChart` applies this itself; call it directly when you also need the\n * collated list — to total the values behind the center number, for instance.\n */\nexport const collateDonutSegments = (\n segments: readonly DonutChartSegment[],\n threshold: number | undefined\n): readonly DonutChartSegment[] => {\n const normalizedSegments = segments.some(\n (segment) => !Number.isFinite(segment.value) || segment.value < 0\n )\n ? segments.map((segment) => ({\n ...segment,\n value: Number.isFinite(segment.value) ? Math.max(0, segment.value) : 0,\n }))\n : segments;\n const { kept, members, collapses } = partitionSegments(\n normalizedSegments,\n threshold\n );\n if (!collapses) return normalizedSegments;\n\n return [\n ...kept,\n {\n id: DONUT_OTHER_SEGMENT_ID,\n label: DONUT_OTHER_SEGMENT_LABEL,\n value: sumSegmentValues(members),\n color: CHART_OTHER_COLOR,\n isOther: true,\n },\n ];\n};\n\n/**\n * Filters collated segments to a legend selection. An empty or absent selection
|
|
1
|
+
{"version":3,"file":"DonutChart.utils.js","names":[],"sources":["../../../src/components/DonutChart/DonutChart.utils.ts"],"sourcesContent":["import type { ReactNode } from 'react';\n\nimport { CHART_OTHER_COLOR } from '../../utils/chartColors';\nimport type { ChartLegendItem } from '../ChartLegend';\nimport { DONUT_OTHER_SEGMENT_ID, DONUT_OTHER_SEGMENT_LABEL } from './constants';\nimport type { DonutChartSegment } from './DonutChart';\n\nconst percentFormatter = new Intl.NumberFormat('en-US', {\n maximumFractionDigits: 1,\n});\n\nexport const sumSegmentValues = (segments: readonly DonutChartSegment[]) =>\n segments.reduce((sum, segment) => sum + segment.value, 0);\n\n/**\n * Splits segments into the ones the donut draws on their own and the ones that\n * fold into a single \"Other\": every segment flagged `isOther` or using the\n * reserved Other ID, plus segments below `threshold` percent of the total.\n *\n * `collapses` is false when there is nothing to fold, and also when the only\n * member is an existing Other segment, so replacing it would change its\n * metadata without changing what is drawn.\n */\nconst partitionSegments = (\n segments: readonly DonutChartSegment[],\n threshold: number | undefined\n): {\n kept: readonly DonutChartSegment[];\n members: readonly DonutChartSegment[];\n collapses: boolean;\n} => {\n const total = sumSegmentValues(segments);\n if (threshold == null || total === 0) {\n return { kept: segments, members: [], collapses: false };\n }\n\n const kept: DonutChartSegment[] = [];\n const members: DonutChartSegment[] = [];\n segments.forEach((segment) => {\n if (\n segment.isOther ||\n segment.id === DONUT_OTHER_SEGMENT_ID ||\n (segment.value / total) * 100 < threshold\n ) {\n members.push(segment);\n } else {\n kept.push(segment);\n }\n });\n\n return {\n kept,\n members,\n collapses:\n members.length > 1 ||\n (members.length === 1 &&\n !members[0].isOther &&\n members[0].id !== DONUT_OTHER_SEGMENT_ID),\n };\n};\n\n/**\n * Folds a segment's long tail into one \"Other\" segment appended after the ones\n * that clear `threshold`. Segments already flagged `isOther` — a rollup the\n * data source computed, say — merge into that same segment rather than sitting\n * beside a second one wearing the same label and color. Invalid values are\n * normalized to zero. Without a threshold, valid segments pass through untouched.\n *\n * `DonutChart` applies this itself; call it directly when you also need the\n * collated list — to total the values behind the center number, for instance.\n */\nexport const collateDonutSegments = (\n segments: readonly DonutChartSegment[],\n threshold: number | undefined\n): readonly DonutChartSegment[] => {\n const normalizedSegments = segments.some(\n (segment) => !Number.isFinite(segment.value) || segment.value < 0\n )\n ? segments.map((segment) => ({\n ...segment,\n value: Number.isFinite(segment.value) ? Math.max(0, segment.value) : 0,\n }))\n : segments;\n const { kept, members, collapses } = partitionSegments(\n normalizedSegments,\n threshold\n );\n if (!collapses) return normalizedSegments;\n\n return [\n ...kept,\n {\n id: DONUT_OTHER_SEGMENT_ID,\n label: DONUT_OTHER_SEGMENT_LABEL,\n value: sumSegmentValues(members),\n color: CHART_OTHER_COLOR,\n isOther: true,\n },\n ];\n};\n\n/**\n * Filters collated segments to a legend selection, then leaves out excluded\n * segments. An empty or absent selection draws everything, and so does a\n * selection that names no segment the donut has: ids outlive the data they\n * came from — a group can be collated away or disappear from a refetch — and\n * drawing nothing would strand the chart empty with no row left to toggle the\n * stale id off. Excluding every segment draws none; their rows stay in the\n * legend to include them again.\n */\nexport const getDrawnSegments = (\n segments: readonly DonutChartSegment[],\n selectedIds: ReadonlySet<string> | undefined,\n excludedIds?: ReadonlySet<string>\n): DonutChartSegment[] => {\n const selected =\n selectedIds == null || selectedIds.size === 0\n ? segments\n : segments.filter((segment) => selectedIds.has(segment.id));\n return (selected.length > 0 ? selected : segments).filter(\n (segment) => !excludedIds?.has(segment.id)\n );\n};\n\n/**\n * Every segment stays in the legend, including filtered-out ones — those report\n * a 0% share so the list does not reflow while filtering. Rows correspond to\n * arcs one for one, so shares are measured against the drawn total.\n *\n * A row reports a share when its arc is drawn rather than when it is selected,\n * so the two cannot disagree about what the donut is showing.\n */\nexport const getDonutLegendItems = ({\n segments,\n selectedIds,\n excludedIds,\n drawnIds,\n drawnTotal,\n formatValue,\n}: {\n segments: readonly DonutChartSegment[];\n selectedIds: ReadonlySet<string> | undefined;\n excludedIds?: ReadonlySet<string>;\n drawnIds: ReadonlySet<string>;\n drawnTotal: number;\n formatValue: (value: number) => ReactNode;\n}): readonly ChartLegendItem[] =>\n segments.map((segment) => {\n const isDrawn = drawnIds.has(segment.id);\n\n return {\n id: segment.id,\n label: segment.label,\n markerColor: segment.color,\n value: formatValue(segment.value),\n secondaryValue: `${percentFormatter.format(\n isDrawn && drawnTotal > 0 ? (segment.value / drawnTotal) * 100 : 0\n )}%`,\n selected: selectedIds?.has(segment.id) ?? false,\n excluded: excludedIds?.has(segment.id) ?? false,\n };\n });\n"],"mappings":";;;AAOA,IAAM,mBAAmB,IAAI,KAAK,aAAa,SAAS,EACtD,uBAAuB,EACzB,CAAC;AAED,IAAa,oBAAoB,aAC/B,SAAS,QAAQ,KAAK,YAAY,MAAM,QAAQ,OAAO,CAAC;;;;;;;;;;AAW1D,IAAM,qBACJ,UACA,cAKG;CACH,MAAM,QAAQ,iBAAiB,QAAQ;CACvC,IAAI,aAAa,QAAQ,UAAU,GACjC,OAAO;EAAE,MAAM;EAAU,SAAS,CAAC;EAAG,WAAW;CAAM;CAGzD,MAAM,OAA4B,CAAC;CACnC,MAAM,UAA+B,CAAC;CACtC,SAAS,SAAS,YAAY;EAC5B,IACE,QAAQ,WACR,QAAQ,OAAA,iBACP,QAAQ,QAAQ,QAAS,MAAM,WAEhC,QAAQ,KAAK,OAAO;OAEpB,KAAK,KAAK,OAAO;CAErB,CAAC;CAED,OAAO;EACL;EACA;EACA,WACE,QAAQ,SAAS,KAChB,QAAQ,WAAW,KAClB,CAA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 @@ export type { LineChartDisplayAxis, LineChartDisplaySeries, LineChartGrid, LineC
|
|
|
5
5
|
* multiple axes, legend filtering, configurable grids and x scales, brushing,
|
|
6
6
|
* and consumer-owned tooltip interactions.
|
|
7
7
|
*/
|
|
8
|
-
export declare const LineChart: ({ series, variant, yAxes, xDomain, formatXValue, xScale: xScaleType, xTickCount, xTickValues, selectedIds, showPoints, connectNulls, grid, activeX, activeLegendItemId, selectionRange, yBands, verticalMarkers, renderActiveOverlay, shouldAnimate, isRendering, showLegend, legendProps, onDatumPointerDown, onDatumPointerMove, onDatumPointerOut, onDatumPointerUp, className, ...rest }: LineChartProps) => import("react").JSX.Element;
|
|
8
|
+
export declare const LineChart: ({ series, variant, yAxes, xDomain, formatXValue, xScale: xScaleType, xTickCount, xTickValues, selectedIds, excludedIds, showPoints, connectNulls, grid, activeX, activeLegendItemId, selectionRange, yBands, verticalMarkers, renderActiveOverlay, shouldAnimate, isRendering, showLegend, legendProps, onDatumPointerDown, onDatumPointerMove, onDatumPointerOut, onDatumPointerUp, className, ...rest }: LineChartProps) => import("react").JSX.Element;
|
|
@@ -73,7 +73,7 @@ var resolveAxes = (layouts, innerHeight) => layouts.map(({ config, domain, nice,
|
|
|
73
73
|
* multiple axes, legend filtering, configurable grids and x scales, brushing,
|
|
74
74
|
* and consumer-owned tooltip interactions.
|
|
75
75
|
*/
|
|
76
|
-
var LineChart = ({ series, variant = "line", yAxes, xDomain, formatXValue = defaultFormatValue, xScale: xScaleType = "linear", xTickCount, xTickValues, selectedIds, showPoints = false, connectNulls = true, grid, activeX, activeLegendItemId, selectionRange, yBands = [], verticalMarkers = [], renderActiveOverlay, shouldAnimate = true, isRendering = true, showLegend, legendProps, onDatumPointerDown, onDatumPointerMove, onDatumPointerOut, onDatumPointerUp, className, ...rest }) => {
|
|
76
|
+
var LineChart = ({ series, variant = "line", yAxes, xDomain, formatXValue = defaultFormatValue, xScale: xScaleType = "linear", xTickCount, xTickValues, selectedIds, excludedIds, showPoints = false, connectNulls = true, grid, activeX, activeLegendItemId, selectionRange, yBands = [], verticalMarkers = [], renderActiveOverlay, shouldAnimate = true, isRendering = true, showLegend, legendProps, onDatumPointerDown, onDatumPointerMove, onDatumPointerOut, onDatumPointerUp, className, ...rest }) => {
|
|
77
77
|
const [activeBuiltInLegendItemId, setActiveBuiltInLegendItemId] = useState(null);
|
|
78
78
|
const ariaProps = {
|
|
79
79
|
"aria-describedby": rest["aria-describedby"],
|
|
@@ -93,7 +93,7 @@ var LineChart = ({ series, variant = "line", yAxes, xDomain, formatXValue = defa
|
|
|
93
93
|
opacity: item.opacity == null || !Number.isFinite(item.opacity) ? 1 : Math.min(1, Math.max(0, item.opacity)),
|
|
94
94
|
showActiveMarker: item.showActiveMarker ?? true
|
|
95
95
|
}));
|
|
96
|
-
const visibleSeries = selectedIds == null || selectedIds.size === 0
|
|
96
|
+
const visibleSeries = displaySeries.filter((item) => (selectedIds == null || selectedIds.size === 0 || selectedIds.has(item.id)) && !excludedIds?.has(item.id));
|
|
97
97
|
const xValues = visibleSeries.flatMap((item) => item.points.map((point) => point.x));
|
|
98
98
|
const resolvedXDomain = getNumericDomain(xValues, xDomain);
|
|
99
99
|
const uniqueXValues = Array.from(new Set(xValues.filter((value) => value >= resolvedXDomain[0] && value <= resolvedXDomain[1]))).sort((left, right) => left - right);
|
|
@@ -127,7 +127,8 @@ var LineChart = ({ series, variant = "line", yAxes, xDomain, formatXValue = defa
|
|
|
127
127
|
id: item.id,
|
|
128
128
|
label: item.label,
|
|
129
129
|
markerColor: item.color,
|
|
130
|
-
selected: selectedIds?.has(item.id) ?? false
|
|
130
|
+
selected: selectedIds?.has(item.id) ?? false,
|
|
131
|
+
excluded: excludedIds?.has(item.id) ?? false
|
|
131
132
|
}));
|
|
132
133
|
const hasLegend = (showLegend ?? legendItems.length > 1) && legendItems.length > 0;
|
|
133
134
|
const legendLayout = legendProps?.layout ?? "inline";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LineChart.js","names":[],"sources":["../../../src/components/LineChart/LineChart.tsx"],"sourcesContent":["import { useState, type HTMLAttributes } from 'react';\n\nimport { useResizeObserver } from '@mantine/hooks';\nimport { scaleLinear } from '@visx/scale';\n\nimport {\n getCategoricalFillColor,\n getCategoricalLineChartColor,\n} from '../../utils/chartColors';\nimport {\n CHART_AXIS_LABEL_THICKNESS,\n CHART_TICK_FONT_SIZE,\n CHART_VALUE_AXIS_TICK_LENGTH,\n} from '../../utils/chartConstants';\nimport { cn } from '../../utils/cn';\nimport { getYAxisLeftMargin } from '../../utils/getYAxisLeftMargin';\nimport { ChartLegend, type ChartLegendItem } from '../ChartLegend';\nimport {\n LINE_CHART_DEFAULT_TICK_COUNT,\n LINE_CHART_VALUE_AXIS_THICKNESS,\n} from './constants';\nimport type {\n LineChartDisplayAxis,\n LineChartDisplaySeries,\n LineChartProps,\n LineChartStackedSeries,\n LineChartVariant,\n LineChartYAxis,\n} from './LineChart.types';\nimport {\n createLineChartXScaleAdapter,\n getLineChartYDomainValues,\n getLineSegments,\n getNumericDomain,\n normalizeLineChartSeries,\n stackLineChartSeries,\n} from './LineChart.utils';\nimport { LineChartPlot } from './LineChartPlot';\n\nexport type {\n LineChartDisplayAxis,\n LineChartDisplaySeries,\n LineChartGrid,\n LineChartInteractionDatum,\n LineChartInteractionPoint,\n LineChartPoint,\n LineChartProps,\n LineChartSelectionRange,\n LineChartSeries,\n LineChartVariant,\n LineChartVerticalMarker,\n LineChartXScale,\n LineChartYBand,\n LineChartYAxis,\n} from './LineChart.types';\n\ntype LineChartAxisLayout = {\n config: LineChartYAxis;\n domain: [number, number];\n nice: boolean;\n thickness: number;\n};\n\nconst DEFAULT_AXIS_ID = 'line-chart-default-axis';\nconst CHART_MARGIN_TOP = 8;\nconst CHART_MARGIN_BOTTOM = 28;\nconst CHART_MARGIN_RIGHT = 8;\nconst DEFAULT_STROKE_WIDTH = 2;\nconst NUMBER_FORMATTER = new Intl.NumberFormat('en-US', {\n maximumFractionDigits: 2,\n});\n\nconst defaultFormatValue = (value: number) => NUMBER_FORMATTER.format(value);\n\n// Areas are filled marks, so line-palette colors switch to their fill pair.\nconst getSeriesColor = (color: string, variant: LineChartVariant) =>\n variant === 'stacked-area' ? getCategoricalFillColor(color) : color;\n\nconst resolveAxisLayouts = (\n series: readonly Pick<LineChartDisplaySeries, 'yAxisId' | 'points'>[],\n configuredAxes: readonly LineChartYAxis[] | undefined,\n xDomain: readonly [number, number],\n connectNulls: boolean\n): readonly LineChartAxisLayout[] => {\n const axisConfigs = new Map(\n configuredAxes?.map((axis) => [axis.id, axis]) ?? []\n );\n const axisIds = Array.from(\n new Set(configuredAxes?.map((axis) => axis.id) ?? [])\n );\n\n for (const item of series) {\n if (!axisIds.includes(item.yAxisId)) axisIds.push(item.yAxisId);\n }\n if (axisIds.length === 0) axisIds.push(DEFAULT_AXIS_ID);\n\n return axisIds.map((axisId): LineChartAxisLayout => {\n const config = axisConfigs.get(axisId) ?? { id: axisId };\n const values = series\n .filter((item) => item.yAxisId === axisId)\n .flatMap((item) =>\n getLineChartYDomainValues(item.points, xDomain, connectNulls)\n );\n const domain = getNumericDomain(values, config.domain);\n const nice = config.domain == null;\n const tickLabelThickness = getYAxisLeftMargin({\n yDomain: domain,\n formatTick: config.formatValue ?? defaultFormatValue,\n fontSize: CHART_TICK_FONT_SIZE,\n numTicks: config.tickCount ?? LINE_CHART_DEFAULT_TICK_COUNT,\n tickValues: config.tickValues,\n tickLength: CHART_VALUE_AXIS_TICK_LENGTH,\n nice,\n });\n return {\n config,\n domain,\n nice,\n thickness:\n Math.max(LINE_CHART_VALUE_AXIS_THICKNESS, tickLabelThickness) +\n (config.label == null ? 0 : CHART_AXIS_LABEL_THICKNESS),\n };\n });\n};\n\n// A stacked band spans y0 to y1, so both edges bound its axis.\nconst getStackedEdges = (series: readonly LineChartStackedSeries[]) =>\n series.flatMap(({ yAxisId, points }) => [\n { yAxisId, points: points.map(({ x, y0 }) => ({ x, y: y0 })) },\n { yAxisId, points: points.map(({ x, y1 }) => ({ x, y: y1 })) },\n ]);\n\nconst resolveAxes = (\n layouts: readonly LineChartAxisLayout[],\n innerHeight: number\n): readonly LineChartDisplayAxis[] =>\n layouts.map(({ config, domain, nice, thickness }) => ({\n ...config,\n thickness,\n scale: scaleLinear<number>({\n domain,\n range: [innerHeight, 0],\n nice,\n }),\n }));\n\n/**\n * Responsive numeric line or stacked-area chart with nullable observations,\n * multiple axes, legend filtering, configurable grids and x scales, brushing,\n * and consumer-owned tooltip interactions.\n */\nexport const LineChart = ({\n series,\n variant = 'line',\n yAxes,\n xDomain,\n formatXValue = defaultFormatValue,\n xScale: xScaleType = 'linear',\n xTickCount,\n xTickValues,\n selectedIds,\n showPoints = false,\n connectNulls = true,\n grid,\n activeX,\n activeLegendItemId,\n selectionRange,\n yBands = [],\n verticalMarkers = [],\n renderActiveOverlay,\n shouldAnimate = true,\n isRendering = true,\n showLegend,\n legendProps,\n onDatumPointerDown,\n onDatumPointerMove,\n onDatumPointerOut,\n onDatumPointerUp,\n className,\n ...rest\n}: LineChartProps) => {\n const [activeBuiltInLegendItemId, setActiveBuiltInLegendItemId] = useState<\n string | null\n >(null);\n const ariaProps = {\n 'aria-describedby': rest['aria-describedby'],\n 'aria-label': rest['aria-label'],\n };\n const rootProps: HTMLAttributes<HTMLDivElement> = { ...rest };\n delete rootProps['aria-describedby'];\n delete rootProps['aria-label'];\n\n const [containerRef, dimensions] = useResizeObserver();\n const normalizedSeries = normalizeLineChartSeries(series);\n const defaultAxisId = yAxes?.[0]?.id ?? DEFAULT_AXIS_ID;\n const displaySeries: readonly LineChartDisplaySeries[] = normalizedSeries.map(\n (item, index) => ({\n ...item,\n color: getSeriesColor(\n item.color ?? getCategoricalLineChartColor(index),\n variant\n ),\n yAxisId: item.yAxisId ?? defaultAxisId,\n strokeWidth:\n item.strokeWidth == null || !Number.isFinite(item.strokeWidth)\n ? DEFAULT_STROKE_WIDTH\n : Math.max(0, item.strokeWidth),\n opacity:\n item.opacity == null || !Number.isFinite(item.opacity)\n ? 1\n : Math.min(1, Math.max(0, item.opacity)),\n showActiveMarker: item.showActiveMarker ?? true,\n })\n );\n const visibleSeries =\n selectedIds == null || selectedIds.size === 0\n ? displaySeries\n : displaySeries.filter((item) => selectedIds.has(item.id));\n const xValues = visibleSeries.flatMap((item) =>\n item.points.map((point) => point.x)\n );\n const resolvedXDomain = getNumericDomain(xValues, xDomain);\n const uniqueXValues = Array.from(\n new Set(\n xValues.filter(\n (value) => value >= resolvedXDomain[0] && value <= resolvedXDomain[1]\n )\n )\n ).sort((left, right) => left - right);\n const renderedSeries =\n xScaleType === 'band'\n ? visibleSeries.map((item) => ({\n ...item,\n points: item.points.filter(\n (point) =>\n point.x >= resolvedXDomain[0] && point.x <= resolvedXDomain[1]\n ),\n }))\n : visibleSeries;\n const renderedActiveX =\n xScaleType !== 'band' ||\n (activeX != null &&\n activeX >= resolvedXDomain[0] &&\n activeX <= resolvedXDomain[1])\n ? activeX\n : undefined;\n // A band scale extrapolates past its outer buckets, so a marker just outside\n // the domain can still project inside the plot.\n const renderedVerticalMarkers =\n xScaleType === 'band'\n ? verticalMarkers.filter(\n (marker) =>\n marker.x >= resolvedXDomain[0] && marker.x <= resolvedXDomain[1]\n )\n : verticalMarkers;\n const stackedSeries =\n variant === 'stacked-area'\n ? stackLineChartSeries(renderedSeries)\n : undefined;\n const axisLayouts = resolveAxisLayouts(\n stackedSeries == null ? renderedSeries : getStackedEdges(stackedSeries),\n yAxes,\n resolvedXDomain,\n connectNulls\n );\n const chartMargin = {\n top: CHART_MARGIN_TOP,\n right:\n CHART_MARGIN_RIGHT +\n axisLayouts.slice(1).reduce((total, axis) => total + axis.thickness, 0),\n bottom: CHART_MARGIN_BOTTOM,\n left: axisLayouts[0]?.thickness ?? LINE_CHART_VALUE_AXIS_THICKNESS,\n };\n const innerWidth = Math.max(\n 0,\n dimensions.width - chartMargin.left - chartMargin.right\n );\n const innerHeight = Math.max(\n 0,\n dimensions.height - chartMargin.top - chartMargin.bottom\n );\n const xScaleAdapter = createLineChartXScaleAdapter({\n type: xScaleType,\n domain: resolvedXDomain,\n values: uniqueXValues,\n width: innerWidth,\n nice: xDomain == null,\n });\n const axes = resolveAxes(axisLayouts, innerHeight);\n\n const activeXPos =\n renderedActiveX == null ? null : xScaleAdapter.getPosition(renderedActiveX);\n const overlayX =\n activeXPos != null && activeXPos >= 0 && activeXPos <= innerWidth\n ? chartMargin.left + activeXPos\n : null;\n\n const legendItems: readonly ChartLegendItem[] = displaySeries.map((item) => ({\n id: item.id,\n label: item.label,\n markerColor: item.color,\n selected: selectedIds?.has(item.id) ?? false,\n }));\n const hasLegend =\n (showLegend ?? legendItems.length > 1) && legendItems.length > 0;\n const legendLayout = legendProps?.layout ?? 'inline';\n const requestedActiveLegendItemId =\n (hasLegend ? activeBuiltInLegendItemId : null) ?? activeLegendItemId;\n const renderedActiveLegendItemId = renderedSeries.some((item) => {\n if (item.id !== requestedActiveLegendItemId) return false;\n\n const [domainMinimum, domainMaximum] = resolvedXDomain;\n const hasVisiblePoint =\n showPoints &&\n item.points.some(\n (point) =>\n point.y != null &&\n point.x >= domainMinimum &&\n point.x <= domainMaximum\n );\n if (hasVisiblePoint) return true;\n\n return getLineSegments(item.points, connectNulls).some((segment) =>\n segment.some((point, index) => {\n const nextPoint = segment[index + 1];\n return (\n nextPoint != null &&\n point.x <= domainMaximum &&\n nextPoint.x >= domainMinimum\n );\n })\n );\n })\n ? requestedActiveLegendItemId\n : null;\n const showGridRows = grid === false ? false : (grid?.rows ?? true);\n const showGridColumns = grid === false ? false : (grid?.columns ?? true);\n\n const plot = (\n <div ref={containerRef} className=\"relative size-full min-h-0 min-w-0\">\n <LineChartPlot\n width={dimensions.width}\n height={dimensions.height}\n innerWidth={innerWidth}\n innerHeight={innerHeight}\n chartMargin={chartMargin}\n xScale={xScaleAdapter.scale}\n getXPosition={xScaleAdapter.getPosition}\n getXValue={xScaleAdapter.getValue}\n getXRangePosition={xScaleAdapter.getRangePosition}\n uniqueXValues={uniqueXValues}\n axes={axes}\n series={renderedSeries}\n stackedSeries={stackedSeries}\n formatXValue={formatXValue}\n xTickCount={xTickCount}\n xTickValues={xTickValues}\n showPoints={showPoints}\n connectNulls={connectNulls}\n showGridRows={showGridRows}\n showGridColumns={showGridColumns}\n activeX={renderedActiveX}\n activeLegendItemId={renderedActiveLegendItemId}\n selectionRange={selectionRange}\n yBands={yBands}\n verticalMarkers={renderedVerticalMarkers}\n shouldAnimate={shouldAnimate}\n isRendering={isRendering}\n {...ariaProps}\n onDatumPointerDown={onDatumPointerDown}\n onDatumPointerMove={onDatumPointerMove}\n onDatumPointerOut={onDatumPointerOut}\n onDatumPointerUp={onDatumPointerUp}\n />\n {renderActiveOverlay != null &&\n overlayX != null &&\n renderedActiveX != null &&\n renderActiveOverlay({ xPosition: overlayX, activeX: renderedActiveX })}\n </div>\n );\n\n const legend = (\n <ChartLegend\n aria-label={`${ariaProps['aria-label']} legend`}\n {...legendProps}\n layout={legendLayout}\n items={legendItems}\n onItemActiveChange={(item) => {\n setActiveBuiltInLegendItemId(item?.id ?? null);\n legendProps?.onItemActiveChange?.(item);\n }}\n />\n );\n\n return (\n <div\n className={cn('size-full min-h-0 min-w-0 @container', className)}\n {...rootProps}\n >\n {hasLegend ? (\n <div\n className={cn(\n 'grid size-full min-h-0 min-w-0 grid-cols-1',\n legendLayout === 'list'\n ? 'grid-rows-[minmax(0,1fr)_minmax(0,35%)] gap-space-3 @[560px]:grid-cols-[minmax(0,1fr)_minmax(10rem,30%)] @[560px]:grid-rows-1 @[560px]:gap-space-5'\n : 'grid-rows-[minmax(0,1fr)_auto] gap-space-2'\n )}\n >\n {plot}\n {legendLayout === 'list' ? (\n <div className=\"scroll-mask-t scroll-mask-b min-h-0 min-w-0 overflow-y-auto overflow-x-hidden\">\n {legend}\n </div>\n ) : (\n legend\n )}\n </div>\n ) : (\n plot\n )}\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;AA+DA,IAAM,kBAAkB;AACxB,IA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U;EAAlC,UAAA,CACE,oBAAC,eAAD;GACE,OAAO,WAAW;GAClB,QAAQ,WAAW;GACP;GACC;GACA;GACb,QAAQ,cAAc;GACtB,cAAc,cAAc;GAC5B,WAAW,cAAc;GACzB,mBAAmB,cAAc;GAClB;GACT;GACN,QAAQ;GACO;GACD;GACF;GACC;GACD;GACE;GACA;GACG;GACjB,SAAS;GACT,oBAAoB;GACJ;GACR;GACR,iBAAiB;GACF;GACF;GACb,GAAI;GACgB;GACA;GACD;GACD;EACnB,CAAA,GACA,uBAAuB,QACtB,YAAY,QACZ,mBAAmB,QACnB,oBAAoB;GAAE,WAAW;GAAU,SAAS;EAAgB,CAAC,CACpE;;CAGP,MAAM,SACJ,oBAAC,aAAD;EACE,cAAY,GAAG,UAAU,cAAc;EACvC,GAAI;EACJ,QAAQ;EACR,OAAO;EACP,qBAAqB,SAAS;GAC5B,6BAA6B,MAAM,MAAM,IAAI;GAC7C,aAAa,qBAAqB,IAAI;EACxC;CACD,CAAA;CAGH,OACE,oBAAC,OAAD;EACE,WAAW,GAAG,wCAAwC,SAAS;EAC/D,GAAI;EAEH,UAAA,YACC,qBAAC,OAAD;GACE,WAAW,GACT,8CACA,iBAAiB,SACb,uJACA,4CACN;GANF,UAAA,CAQG,MACA,iBAAiB,SAChB,oBAAC,OAAD;IAAK,WAAU;IACZ,UAAA;GACE,CAAA,IAEL,MAEC;EAEL,CAAA,IAAA;CAEC,CAAA;AAET"}
|
|
1
|
+
{"version":3,"file":"LineChart.js","names":[],"sources":["../../../src/components/LineChart/LineChart.tsx"],"sourcesContent":["import { useState, type HTMLAttributes } from 'react';\n\nimport { useResizeObserver } from '@mantine/hooks';\nimport { scaleLinear } from '@visx/scale';\n\nimport {\n getCategoricalFillColor,\n getCategoricalLineChartColor,\n} from '../../utils/chartColors';\nimport {\n CHART_AXIS_LABEL_THICKNESS,\n CHART_TICK_FONT_SIZE,\n CHART_VALUE_AXIS_TICK_LENGTH,\n} from '../../utils/chartConstants';\nimport { cn } from '../../utils/cn';\nimport { getYAxisLeftMargin } from '../../utils/getYAxisLeftMargin';\nimport { ChartLegend, type ChartLegendItem } from '../ChartLegend';\nimport {\n LINE_CHART_DEFAULT_TICK_COUNT,\n LINE_CHART_VALUE_AXIS_THICKNESS,\n} from './constants';\nimport type {\n LineChartDisplayAxis,\n LineChartDisplaySeries,\n LineChartProps,\n LineChartStackedSeries,\n LineChartVariant,\n LineChartYAxis,\n} from './LineChart.types';\nimport {\n createLineChartXScaleAdapter,\n getLineChartYDomainValues,\n getLineSegments,\n getNumericDomain,\n normalizeLineChartSeries,\n stackLineChartSeries,\n} from './LineChart.utils';\nimport { LineChartPlot } from './LineChartPlot';\n\nexport type {\n LineChartDisplayAxis,\n LineChartDisplaySeries,\n LineChartGrid,\n LineChartInteractionDatum,\n LineChartInteractionPoint,\n LineChartPoint,\n LineChartProps,\n LineChartSelectionRange,\n LineChartSeries,\n LineChartVariant,\n LineChartVerticalMarker,\n LineChartXScale,\n LineChartYBand,\n LineChartYAxis,\n} from './LineChart.types';\n\ntype LineChartAxisLayout = {\n config: LineChartYAxis;\n domain: [number, number];\n nice: boolean;\n thickness: number;\n};\n\nconst DEFAULT_AXIS_ID = 'line-chart-default-axis';\nconst CHART_MARGIN_TOP = 8;\nconst CHART_MARGIN_BOTTOM = 28;\nconst CHART_MARGIN_RIGHT = 8;\nconst DEFAULT_STROKE_WIDTH = 2;\nconst NUMBER_FORMATTER = new Intl.NumberFormat('en-US', {\n maximumFractionDigits: 2,\n});\n\nconst defaultFormatValue = (value: number) => NUMBER_FORMATTER.format(value);\n\n// Areas are filled marks, so line-palette colors switch to their fill pair.\nconst getSeriesColor = (color: string, variant: LineChartVariant) =>\n variant === 'stacked-area' ? getCategoricalFillColor(color) : color;\n\nconst resolveAxisLayouts = (\n series: readonly Pick<LineChartDisplaySeries, 'yAxisId' | 'points'>[],\n configuredAxes: readonly LineChartYAxis[] | undefined,\n xDomain: readonly [number, number],\n connectNulls: boolean\n): readonly LineChartAxisLayout[] => {\n const axisConfigs = new Map(\n configuredAxes?.map((axis) => [axis.id, axis]) ?? []\n );\n const axisIds = Array.from(\n new Set(configuredAxes?.map((axis) => axis.id) ?? [])\n );\n\n for (const item of series) {\n if (!axisIds.includes(item.yAxisId)) axisIds.push(item.yAxisId);\n }\n if (axisIds.length === 0) axisIds.push(DEFAULT_AXIS_ID);\n\n return axisIds.map((axisId): LineChartAxisLayout => {\n const config = axisConfigs.get(axisId) ?? { id: axisId };\n const values = series\n .filter((item) => item.yAxisId === axisId)\n .flatMap((item) =>\n getLineChartYDomainValues(item.points, xDomain, connectNulls)\n );\n const domain = getNumericDomain(values, config.domain);\n const nice = config.domain == null;\n const tickLabelThickness = getYAxisLeftMargin({\n yDomain: domain,\n formatTick: config.formatValue ?? defaultFormatValue,\n fontSize: CHART_TICK_FONT_SIZE,\n numTicks: config.tickCount ?? LINE_CHART_DEFAULT_TICK_COUNT,\n tickValues: config.tickValues,\n tickLength: CHART_VALUE_AXIS_TICK_LENGTH,\n nice,\n });\n return {\n config,\n domain,\n nice,\n thickness:\n Math.max(LINE_CHART_VALUE_AXIS_THICKNESS, tickLabelThickness) +\n (config.label == null ? 0 : CHART_AXIS_LABEL_THICKNESS),\n };\n });\n};\n\n// A stacked band spans y0 to y1, so both edges bound its axis.\nconst getStackedEdges = (series: readonly LineChartStackedSeries[]) =>\n series.flatMap(({ yAxisId, points }) => [\n { yAxisId, points: points.map(({ x, y0 }) => ({ x, y: y0 })) },\n { yAxisId, points: points.map(({ x, y1 }) => ({ x, y: y1 })) },\n ]);\n\nconst resolveAxes = (\n layouts: readonly LineChartAxisLayout[],\n innerHeight: number\n): readonly LineChartDisplayAxis[] =>\n layouts.map(({ config, domain, nice, thickness }) => ({\n ...config,\n thickness,\n scale: scaleLinear<number>({\n domain,\n range: [innerHeight, 0],\n nice,\n }),\n }));\n\n/**\n * Responsive numeric line or stacked-area chart with nullable observations,\n * multiple axes, legend filtering, configurable grids and x scales, brushing,\n * and consumer-owned tooltip interactions.\n */\nexport const LineChart = ({\n series,\n variant = 'line',\n yAxes,\n xDomain,\n formatXValue = defaultFormatValue,\n xScale: xScaleType = 'linear',\n xTickCount,\n xTickValues,\n selectedIds,\n excludedIds,\n showPoints = false,\n connectNulls = true,\n grid,\n activeX,\n activeLegendItemId,\n selectionRange,\n yBands = [],\n verticalMarkers = [],\n renderActiveOverlay,\n shouldAnimate = true,\n isRendering = true,\n showLegend,\n legendProps,\n onDatumPointerDown,\n onDatumPointerMove,\n onDatumPointerOut,\n onDatumPointerUp,\n className,\n ...rest\n}: LineChartProps) => {\n const [activeBuiltInLegendItemId, setActiveBuiltInLegendItemId] = useState<\n string | null\n >(null);\n const ariaProps = {\n 'aria-describedby': rest['aria-describedby'],\n 'aria-label': rest['aria-label'],\n };\n const rootProps: HTMLAttributes<HTMLDivElement> = { ...rest };\n delete rootProps['aria-describedby'];\n delete rootProps['aria-label'];\n\n const [containerRef, dimensions] = useResizeObserver();\n const normalizedSeries = normalizeLineChartSeries(series);\n const defaultAxisId = yAxes?.[0]?.id ?? DEFAULT_AXIS_ID;\n const displaySeries: readonly LineChartDisplaySeries[] = normalizedSeries.map(\n (item, index) => ({\n ...item,\n color: getSeriesColor(\n item.color ?? getCategoricalLineChartColor(index),\n variant\n ),\n yAxisId: item.yAxisId ?? defaultAxisId,\n strokeWidth:\n item.strokeWidth == null || !Number.isFinite(item.strokeWidth)\n ? DEFAULT_STROKE_WIDTH\n : Math.max(0, item.strokeWidth),\n opacity:\n item.opacity == null || !Number.isFinite(item.opacity)\n ? 1\n : Math.min(1, Math.max(0, item.opacity)),\n showActiveMarker: item.showActiveMarker ?? true,\n })\n );\n const visibleSeries = displaySeries.filter(\n (item) =>\n (selectedIds == null ||\n selectedIds.size === 0 ||\n selectedIds.has(item.id)) &&\n !excludedIds?.has(item.id)\n );\n const xValues = visibleSeries.flatMap((item) =>\n item.points.map((point) => point.x)\n );\n const resolvedXDomain = getNumericDomain(xValues, xDomain);\n const uniqueXValues = Array.from(\n new Set(\n xValues.filter(\n (value) => value >= resolvedXDomain[0] && value <= resolvedXDomain[1]\n )\n )\n ).sort((left, right) => left - right);\n const renderedSeries =\n xScaleType === 'band'\n ? visibleSeries.map((item) => ({\n ...item,\n points: item.points.filter(\n (point) =>\n point.x >= resolvedXDomain[0] && point.x <= resolvedXDomain[1]\n ),\n }))\n : visibleSeries;\n const renderedActiveX =\n xScaleType !== 'band' ||\n (activeX != null &&\n activeX >= resolvedXDomain[0] &&\n activeX <= resolvedXDomain[1])\n ? activeX\n : undefined;\n // A band scale extrapolates past its outer buckets, so a marker just outside\n // the domain can still project inside the plot.\n const renderedVerticalMarkers =\n xScaleType === 'band'\n ? verticalMarkers.filter(\n (marker) =>\n marker.x >= resolvedXDomain[0] && marker.x <= resolvedXDomain[1]\n )\n : verticalMarkers;\n const stackedSeries =\n variant === 'stacked-area'\n ? stackLineChartSeries(renderedSeries)\n : undefined;\n const axisLayouts = resolveAxisLayouts(\n stackedSeries == null ? renderedSeries : getStackedEdges(stackedSeries),\n yAxes,\n resolvedXDomain,\n connectNulls\n );\n const chartMargin = {\n top: CHART_MARGIN_TOP,\n right:\n CHART_MARGIN_RIGHT +\n axisLayouts.slice(1).reduce((total, axis) => total + axis.thickness, 0),\n bottom: CHART_MARGIN_BOTTOM,\n left: axisLayouts[0]?.thickness ?? LINE_CHART_VALUE_AXIS_THICKNESS,\n };\n const innerWidth = Math.max(\n 0,\n dimensions.width - chartMargin.left - chartMargin.right\n );\n const innerHeight = Math.max(\n 0,\n dimensions.height - chartMargin.top - chartMargin.bottom\n );\n const xScaleAdapter = createLineChartXScaleAdapter({\n type: xScaleType,\n domain: resolvedXDomain,\n values: uniqueXValues,\n width: innerWidth,\n nice: xDomain == null,\n });\n const axes = resolveAxes(axisLayouts, innerHeight);\n\n const activeXPos =\n renderedActiveX == null ? null : xScaleAdapter.getPosition(renderedActiveX);\n const overlayX =\n activeXPos != null && activeXPos >= 0 && activeXPos <= innerWidth\n ? chartMargin.left + activeXPos\n : null;\n\n const legendItems: readonly ChartLegendItem[] = displaySeries.map((item) => ({\n id: item.id,\n label: item.label,\n markerColor: item.color,\n selected: selectedIds?.has(item.id) ?? false,\n excluded: excludedIds?.has(item.id) ?? false,\n }));\n const hasLegend =\n (showLegend ?? legendItems.length > 1) && legendItems.length > 0;\n const legendLayout = legendProps?.layout ?? 'inline';\n const requestedActiveLegendItemId =\n (hasLegend ? activeBuiltInLegendItemId : null) ?? activeLegendItemId;\n const renderedActiveLegendItemId = renderedSeries.some((item) => {\n if (item.id !== requestedActiveLegendItemId) return false;\n\n const [domainMinimum, domainMaximum] = resolvedXDomain;\n const hasVisiblePoint =\n showPoints &&\n item.points.some(\n (point) =>\n point.y != null &&\n point.x >= domainMinimum &&\n point.x <= domainMaximum\n );\n if (hasVisiblePoint) return true;\n\n return getLineSegments(item.points, connectNulls).some((segment) =>\n segment.some((point, index) => {\n const nextPoint = segment[index + 1];\n return (\n nextPoint != null &&\n point.x <= domainMaximum &&\n nextPoint.x >= domainMinimum\n );\n })\n );\n })\n ? requestedActiveLegendItemId\n : null;\n const showGridRows = grid === false ? false : (grid?.rows ?? true);\n const showGridColumns = grid === false ? false : (grid?.columns ?? true);\n\n const plot = (\n <div ref={containerRef} className=\"relative size-full min-h-0 min-w-0\">\n <LineChartPlot\n width={dimensions.width}\n height={dimensions.height}\n innerWidth={innerWidth}\n innerHeight={innerHeight}\n chartMargin={chartMargin}\n xScale={xScaleAdapter.scale}\n getXPosition={xScaleAdapter.getPosition}\n getXValue={xScaleAdapter.getValue}\n getXRangePosition={xScaleAdapter.getRangePosition}\n uniqueXValues={uniqueXValues}\n axes={axes}\n series={renderedSeries}\n stackedSeries={stackedSeries}\n formatXValue={formatXValue}\n xTickCount={xTickCount}\n xTickValues={xTickValues}\n showPoints={showPoints}\n connectNulls={connectNulls}\n showGridRows={showGridRows}\n showGridColumns={showGridColumns}\n activeX={renderedActiveX}\n activeLegendItemId={renderedActiveLegendItemId}\n selectionRange={selectionRange}\n yBands={yBands}\n verticalMarkers={renderedVerticalMarkers}\n shouldAnimate={shouldAnimate}\n isRendering={isRendering}\n {...ariaProps}\n onDatumPointerDown={onDatumPointerDown}\n onDatumPointerMove={onDatumPointerMove}\n onDatumPointerOut={onDatumPointerOut}\n onDatumPointerUp={onDatumPointerUp}\n />\n {renderActiveOverlay != null &&\n overlayX != null &&\n renderedActiveX != null &&\n renderActiveOverlay({ xPosition: overlayX, activeX: renderedActiveX })}\n </div>\n );\n\n const legend = (\n <ChartLegend\n aria-label={`${ariaProps['aria-label']} legend`}\n {...legendProps}\n layout={legendLayout}\n items={legendItems}\n onItemActiveChange={(item) => {\n setActiveBuiltInLegendItemId(item?.id ?? null);\n legendProps?.onItemActiveChange?.(item);\n }}\n />\n );\n\n return (\n <div\n className={cn('size-full min-h-0 min-w-0 @container', className)}\n {...rootProps}\n >\n {hasLegend ? (\n <div\n className={cn(\n 'grid size-full min-h-0 min-w-0 grid-cols-1',\n legendLayout === 'list'\n ? 'grid-rows-[minmax(0,1fr)_minmax(0,35%)] gap-space-3 @[560px]:grid-cols-[minmax(0,1fr)_minmax(10rem,30%)] @[560px]:grid-rows-1 @[560px]:gap-space-5'\n : 'grid-rows-[minmax(0,1fr)_auto] gap-space-2'\n )}\n >\n {plot}\n {legendLayout === 'list' ? (\n <div className=\"scroll-mask-t scroll-mask-b min-h-0 min-w-0 overflow-y-auto overflow-x-hidden\">\n {legend}\n </div>\n ) : (\n legend\n )}\n </div>\n ) : (\n plot\n )}\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;AA+DA,IAAM,kBAAkB;AACxB,IAAM,mBAAmB;AACzB,IAAM,sBAAsB;AAC5B,IAAM,qBAAqB;AAC3B,IAAM,uBAAuB;AAC7B,IAAM,mBAAmB,IAAI,KAAK,aAAa,SAAS,EACtD,uBAAuB,EACzB,CAAC;AAED,IAAM,sBAAsB,UAAkB,iBAAiB,OAAO,KAAK;AAG3E,IAAM,kBAAkB,OAAe,YACrC,YAAY,iBA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GACT;GACN,QAAQ;GACO;GACD;GACF;GACC;GACD;GACE;GACA;GACG;GACjB,SAAS;GACT,oBAAoB;GACJ;GACR;GACR,iBAAiB;GACF;GACF;GACb,GAAI;GACgB;GACA;GACD;GACD;EACnB,CAAA,GACA,uBAAuB,QACtB,YAAY,QACZ,mBAAmB,QACnB,oBAAoB;GAAE,WAAW;GAAU,SAAS;EAAgB,CAAC,CACpE;;CAGP,MAAM,SACJ,oBAAC,aAAD;EACE,cAAY,GAAG,UAAU,cAAc;EACvC,GAAI;EACJ,QAAQ;EACR,OAAO;EACP,qBAAqB,SAAS;GAC5B,6BAA6B,MAAM,MAAM,IAAI;GAC7C,aAAa,qBAAqB,IAAI;EACxC;CACD,CAAA;CAGH,OACE,oBAAC,OAAD;EACE,WAAW,GAAG,wCAAwC,SAAS;EAC/D,GAAI;EAEH,UAAA,YACC,qBAAC,OAAD;GACE,WAAW,GACT,8CACA,iBAAiB,SACb,uJACA,4CACN;GANF,UAAA,CAQG,MACA,iBAAiB,SAChB,oBAAC,OAAD;IAAK,WAAU;IACZ,UAAA;GACE,CAAA,IAEL,MAEC;EAEL,CAAA,IAAA;CAEC,CAAA;AAET"}
|
|
@@ -134,7 +134,14 @@ export type LineChartProps = Omit<HTMLAttributes<HTMLDivElement>, 'children' | '
|
|
|
134
134
|
xScale?: LineChartXScale;
|
|
135
135
|
xTickCount?: number;
|
|
136
136
|
xTickValues?: readonly number[];
|
|
137
|
+
/** Controlled legend filter. An empty set renders every series. */
|
|
137
138
|
selectedIds?: ReadonlySet<string>;
|
|
139
|
+
/**
|
|
140
|
+
* Series left out, whatever `selectedIds` holds. Their legend items stay,
|
|
141
|
+
* marked excluded; to toggle them from the legend, set
|
|
142
|
+
* `legendProps.itemClickAction` to `exclude` and wire `onItemClick`.
|
|
143
|
+
*/
|
|
144
|
+
excludedIds?: ReadonlySet<string>;
|
|
138
145
|
showPoints?: boolean;
|
|
139
146
|
/** Connects valid observations across null values. Defaults to true. */
|
|
140
147
|
connectNulls?: boolean;
|
|
@@ -53,6 +53,7 @@ export type RadarChartSingleSeriesProps = RadarChartBaseProps & {
|
|
|
53
53
|
series?: never;
|
|
54
54
|
renderAxisTooltip?: never;
|
|
55
55
|
selectedIds?: never;
|
|
56
|
+
excludedIds?: never;
|
|
56
57
|
activeLegendItemId?: never;
|
|
57
58
|
};
|
|
58
59
|
export type RadarChartMultiSeriesProps = RadarChartBaseProps & {
|
|
@@ -70,6 +71,8 @@ export type RadarChartMultiSeriesProps = RadarChartBaseProps & {
|
|
|
70
71
|
renderAxisTooltip?: (axis: RadarChartAxisValues) => ReactNode;
|
|
71
72
|
/** When non-empty, only these series are drawn. Colors keep their series order. */
|
|
72
73
|
selectedIds?: ReadonlySet<string>;
|
|
74
|
+
/** Series left out, whatever `selectedIds` holds. */
|
|
75
|
+
excludedIds?: ReadonlySet<string>;
|
|
73
76
|
/** Emphasizes one series from an external legend and dims the rest. */
|
|
74
77
|
activeLegendItemId?: string | null;
|
|
75
78
|
data?: never;
|
|
@@ -73,7 +73,7 @@ var getMaximum = (values, maxValue) => maxValue !== void 0 && Number.isFinite(ma
|
|
|
73
73
|
* overlapping areas identified by an external legend.
|
|
74
74
|
*/
|
|
75
75
|
var RadarChart = (props) => {
|
|
76
|
-
const { data: _data, axes: _axes, series: _series, renderTooltip: _renderTooltip, renderAxisTooltip: _renderAxisTooltip, selectedIds, activeLegendItemId, maxValue, formatValue = formatNumber, className, "aria-label": ariaLabel = "Radar chart", "aria-labelledby": ariaLabelledBy, "aria-describedby": ariaDescribedBy, ...divProps } = props;
|
|
76
|
+
const { data: _data, axes: _axes, series: _series, renderTooltip: _renderTooltip, renderAxisTooltip: _renderAxisTooltip, selectedIds, excludedIds, activeLegendItemId, maxValue, formatValue = formatNumber, className, "aria-label": ariaLabel = "Radar chart", "aria-labelledby": ariaLabelledBy, "aria-describedby": ariaDescribedBy, ...divProps } = props;
|
|
77
77
|
const summaryId = useId();
|
|
78
78
|
const [activeTooltip, setActiveTooltip] = useState(null);
|
|
79
79
|
const isPointerDownRef = useRef(false);
|
|
@@ -208,7 +208,7 @@ var RadarChart = (props) => {
|
|
|
208
208
|
};
|
|
209
209
|
const renderMultiSeries = (axes, series, renderAxisTooltip) => {
|
|
210
210
|
const layouts = getAxisLayouts(axes, LABEL_LINE_HEIGHT);
|
|
211
|
-
const
|
|
211
|
+
const visibleSeries = series.map((item, index) => {
|
|
212
212
|
const color = item.color ?? getCategoricalLineChartColor(index);
|
|
213
213
|
return {
|
|
214
214
|
id: item.id,
|
|
@@ -217,8 +217,7 @@ var RadarChart = (props) => {
|
|
|
217
217
|
fill: getCategoricalFillColor(color),
|
|
218
218
|
values: axes.map(({ id }) => sanitize(item.values[id]))
|
|
219
219
|
};
|
|
220
|
-
});
|
|
221
|
-
const visibleSeries = selectedIds === void 0 || selectedIds.size === 0 ? resolvedSeries : resolvedSeries.filter(({ id }) => selectedIds.has(id));
|
|
220
|
+
}).filter(({ id }) => (selectedIds === void 0 || selectedIds.size === 0 || selectedIds.has(id)) && !excludedIds?.has(id));
|
|
222
221
|
const maximum = getMaximum(visibleSeries.flatMap(({ values }) => values), maxValue);
|
|
223
222
|
const plottedSeries = visibleSeries.map((item) => ({
|
|
224
223
|
...item,
|