@langchain/macaw-components 1.2.0 → 1.2.2
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 +492 -492
- package/dist/components/Input/inputStyles.js +2 -2
- package/dist/components/Input/inputStyles.js.map +1 -1
- package/dist/components/LineChart/LineChart.d.ts +5 -5
- package/dist/components/LineChart/LineChart.js +24 -8
- package/dist/components/LineChart/LineChart.js.map +1 -1
- package/dist/components/LineChart/LineChart.types.d.ts +18 -0
- package/dist/components/LineChart/LineChart.utils.d.ts +7 -1
- package/dist/components/LineChart/LineChart.utils.js +35 -1
- package/dist/components/LineChart/LineChart.utils.js.map +1 -1
- package/dist/components/LineChart/LineChartPlot.d.ts +4 -2
- package/dist/components/LineChart/LineChartPlot.js +29 -5
- package/dist/components/LineChart/LineChartPlot.js.map +1 -1
- package/dist/components/LineChart/index.d.ts +1 -1
- package/dist/components/Select/Select.js +1 -1
- package/dist/components/Select/Select.js.map +1 -1
- package/dist/components/Select/SelectPrimitive.js +3 -3
- package/dist/components/Select/SelectPrimitive.js.map +1 -1
- package/dist/components/Textarea/Textarea.js +2 -2
- package/dist/components/Textarea/Textarea.js.map +1 -1
- package/dist/components/TopList/TopList.d.ts +1 -1
- package/dist/components/TopList/TopList.js +5 -3
- package/dist/components/TopList/TopList.js.map +1 -1
- package/dist/components/TopList/TopList.types.d.ts +2 -0
- package/dist/components/Typeahead/TypeaheadView.js +1 -1
- package/dist/components/Typeahead/TypeaheadView.js.map +1 -1
- package/dist/utilities.css +1 -1
- package/dist/utils/cn.js +3 -0
- package/dist/utils/cn.js.map +1 -1
- package/docs/DESIGN.md +3 -0
- package/docs/STYLES.md +42 -6
- package/package.json +2 -2
- package/tailwind.preset.cjs +3 -0
|
@@ -26,9 +26,9 @@ var INPUT_TEXT_CLASSES = {
|
|
|
26
26
|
function getInputContainerClasses({ size, variant, isError = false, disabled = false, className }) {
|
|
27
27
|
const outlined = variant === "outlined";
|
|
28
28
|
return cn("box-border flex w-full items-center gap-space-2 transition-[border-color,box-shadow,background-color]", CONTROL_SIZES[size].heightClassName, INPUT_HORIZONTAL_PADDING_CLASSES[size], INPUT_RADIUS_CLASSES[size], "focus-within:outline-hidden", {
|
|
29
|
-
"border border-
|
|
29
|
+
"border border-input bg-input": variant === "outlined",
|
|
30
30
|
"border border-transparent bg-input": variant === "plain"
|
|
31
|
-
}, outlined && !disabled && !isError && "[&:hover:not(:focus-within)]:border-
|
|
31
|
+
}, outlined && !disabled && !isError && "[&:hover:not(:focus-within)]:border-input-hover", !disabled && !isError && (outlined ? "focus-within:border-focus focus-within:shadow-[0_0_0_1px_var(--border-focus)]" : "focus-within:border-focus"), !disabled && isError && (outlined ? "border-error-strong focus-within:border-error-strong focus-within:shadow-[0_0_0_1px_var(--border-error-strong)]" : "border-error-strong focus-within:border-error-strong"), disabled && "cursor-not-allowed border-muted bg-input-disabled text-disabled", className);
|
|
32
32
|
}
|
|
33
33
|
/**
|
|
34
34
|
* Shared styling for the inner input element (unstyled, fills container).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"inputStyles.js","names":[],"sources":["../../../src/components/Input/inputStyles.ts"],"sourcesContent":["import { cn } from '../../utils/cn';\nimport { CONTROL_SIZES, type ControlSize } from '../../utils/componentSizes';\n\nexport type InputSize = ControlSize;\nexport type InputVariant = 'outlined' | 'plain';\n\nexport const INPUT_HORIZONTAL_PADDING_CLASSES: Record<InputSize, string> = {\n xs: 'px-space-1',\n sm: 'px-space-2',\n md: 'px-space-3',\n lg: 'px-space-3',\n};\n\nexport const INPUT_RADIUS_CLASSES: Record<InputSize, string> = {\n xs: 'rounded-xs',\n sm: 'rounded-sm',\n md: 'rounded-md',\n lg: 'rounded-md',\n};\n\nexport const INPUT_TEXT_CLASSES: Record<InputSize, string> = {\n xs: 'text-xxs leading-[1.15]',\n sm: 'text-xs',\n md: 'text-sm leading-normal',\n lg: 'text-sm leading-normal',\n};\n\n/**\n * Shared styling for input containers (border, padding, rounding, variant).\n * Used by both the design system Input and CommandInput.\n */\nexport function getInputContainerClasses({\n size,\n variant,\n isError = false,\n disabled = false,\n className,\n}: {\n size: InputSize;\n variant: InputVariant;\n isError?: boolean;\n disabled?: boolean;\n className?: string;\n}) {\n const outlined = variant === 'outlined';\n return cn(\n 'box-border flex w-full items-center gap-space-2 transition-[border-color,box-shadow,background-color]',\n CONTROL_SIZES[size].heightClassName,\n INPUT_HORIZONTAL_PADDING_CLASSES[size],\n INPUT_RADIUS_CLASSES[size],\n 'focus-within:outline-hidden',\n {\n 'border border-
|
|
1
|
+
{"version":3,"file":"inputStyles.js","names":[],"sources":["../../../src/components/Input/inputStyles.ts"],"sourcesContent":["import { cn } from '../../utils/cn';\nimport { CONTROL_SIZES, type ControlSize } from '../../utils/componentSizes';\n\nexport type InputSize = ControlSize;\nexport type InputVariant = 'outlined' | 'plain';\n\nexport const INPUT_HORIZONTAL_PADDING_CLASSES: Record<InputSize, string> = {\n xs: 'px-space-1',\n sm: 'px-space-2',\n md: 'px-space-3',\n lg: 'px-space-3',\n};\n\nexport const INPUT_RADIUS_CLASSES: Record<InputSize, string> = {\n xs: 'rounded-xs',\n sm: 'rounded-sm',\n md: 'rounded-md',\n lg: 'rounded-md',\n};\n\nexport const INPUT_TEXT_CLASSES: Record<InputSize, string> = {\n xs: 'text-xxs leading-[1.15]',\n sm: 'text-xs',\n md: 'text-sm leading-normal',\n lg: 'text-sm leading-normal',\n};\n\n/**\n * Shared styling for input containers (border, padding, rounding, variant).\n * Used by both the design system Input and CommandInput.\n */\nexport function getInputContainerClasses({\n size,\n variant,\n isError = false,\n disabled = false,\n className,\n}: {\n size: InputSize;\n variant: InputVariant;\n isError?: boolean;\n disabled?: boolean;\n className?: string;\n}) {\n const outlined = variant === 'outlined';\n return cn(\n 'box-border flex w-full items-center gap-space-2 transition-[border-color,box-shadow,background-color]',\n CONTROL_SIZES[size].heightClassName,\n INPUT_HORIZONTAL_PADDING_CLASSES[size],\n INPUT_RADIUS_CLASSES[size],\n 'focus-within:outline-hidden',\n {\n 'border border-input bg-input': variant === 'outlined',\n 'border border-transparent bg-input': variant === 'plain',\n },\n outlined &&\n !disabled &&\n !isError &&\n '[&:hover:not(:focus-within)]:border-input-hover',\n !disabled &&\n !isError &&\n (outlined\n ? 'focus-within:border-focus focus-within:shadow-[0_0_0_1px_var(--border-focus)]'\n : 'focus-within:border-focus'),\n !disabled &&\n isError &&\n (outlined\n ? 'border-error-strong focus-within:border-error-strong focus-within:shadow-[0_0_0_1px_var(--border-error-strong)]'\n : 'border-error-strong focus-within:border-error-strong'),\n disabled &&\n 'cursor-not-allowed border-muted bg-input-disabled text-disabled',\n className\n );\n}\n\n/**\n * Shared styling for the inner input element (unstyled, fills container).\n * Used by both the design system Input and CommandInput.\n */\nexport function getInputElementClasses({\n size,\n disabled = false,\n className,\n}: {\n size: InputSize;\n disabled?: boolean;\n className?: string;\n}) {\n return cn(\n 'min-w-0 max-w-full flex-1 border-none bg-transparent p-0 outline-hidden',\n INPUT_TEXT_CLASSES[size],\n 'placeholder:text-placeholder',\n disabled && 'cursor-not-allowed text-disabled placeholder:text-disabled',\n className\n );\n}\n\n/** Shared styling for decorator wrappers. */\nexport const DECORATOR_CLASSES = 'flex items-center text-tertiary';\n"],"mappings":";;;AAMA,IAAa,mCAA8D;CACzE,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;AACN;AAEA,IAAa,uBAAkD;CAC7D,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;AACN;AAEA,IAAa,qBAAgD;CAC3D,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;AACN;;;;;AAMA,SAAgB,yBAAyB,EACvC,MACA,SACA,UAAU,OACV,WAAW,OACX,aAOC;CACD,MAAM,WAAW,YAAY;CAC7B,OAAO,GACL,yGACA,cAAc,KAAK,CAAC,iBACpB,iCAAiC,OACjC,qBAAqB,OACrB,+BACA;EACE,gCAAgC,YAAY;EAC5C,sCAAsC,YAAY;CACpD,GACA,YACE,CAAC,YACD,CAAC,WACD,mDACF,CAAC,YACC,CAAC,YACA,WACG,kFACA,8BACN,CAAC,YACC,YACC,WACG,oHACA,yDACN,YACE,mEACF,SACF;AACF;;;;;AAMA,SAAgB,uBAAuB,EACrC,MACA,WAAW,OACX,aAKC;CACD,OAAO,GACL,2EACA,mBAAmB,OACnB,gCACA,YAAY,8DACZ,SACF;AACF;;AAGA,IAAa,oBAAoB"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import type { LineChartProps } from './LineChart.types.js';
|
|
2
|
-
export type { LineChartDisplayAxis, LineChartDisplaySeries, LineChartGrid, LineChartInteractionDatum, LineChartInteractionPoint, LineChartPoint, LineChartProps, LineChartSelectionRange, LineChartSeries, LineChartVerticalMarker, LineChartXScale, LineChartYBand, LineChartYAxis, } from './LineChart.types.js';
|
|
2
|
+
export type { LineChartDisplayAxis, LineChartDisplaySeries, LineChartGrid, LineChartInteractionDatum, LineChartInteractionPoint, LineChartPoint, LineChartProps, LineChartSelectionRange, LineChartSeries, LineChartVariant, LineChartVerticalMarker, LineChartXScale, LineChartYBand, LineChartYAxis, } from './LineChart.types.js';
|
|
3
3
|
/**
|
|
4
|
-
* Responsive numeric line chart with nullable observations,
|
|
5
|
-
* legend filtering, configurable grids and x scales, brushing,
|
|
6
|
-
* consumer-owned tooltip interactions.
|
|
4
|
+
* Responsive numeric line or stacked-area chart with nullable observations,
|
|
5
|
+
* multiple axes, legend filtering, configurable grids and x scales, brushing,
|
|
6
|
+
* and consumer-owned tooltip interactions.
|
|
7
7
|
*/
|
|
8
|
-
export declare const LineChart: ({ series, 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, showPoints, connectNulls, grid, activeX, activeLegendItemId, selectionRange, yBands, verticalMarkers, renderActiveOverlay, shouldAnimate, isRendering, showLegend, legendProps, onDatumPointerDown, onDatumPointerMove, onDatumPointerOut, onDatumPointerUp, className, ...rest }: LineChartProps) => import("react").JSX.Element;
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { cn } from "../../utils/cn.js";
|
|
2
2
|
import "../../utils/chartConstants.js";
|
|
3
|
-
import { getCategoricalLineChartColor } from "../../utils/chartColors.js";
|
|
3
|
+
import { getCategoricalFillColor, getCategoricalLineChartColor } from "../../utils/chartColors.js";
|
|
4
4
|
import { getYAxisLeftMargin } from "../../utils/getYAxisLeftMargin.js";
|
|
5
5
|
import { ChartLegend } from "../ChartLegend/ChartLegend.js";
|
|
6
6
|
import "./constants.js";
|
|
7
|
-
import { createLineChartXScaleAdapter, getLineChartYDomainValues, getLineSegments, getNumericDomain, normalizeLineChartSeries } from "./LineChart.utils.js";
|
|
7
|
+
import { createLineChartXScaleAdapter, getLineChartYDomainValues, getLineSegments, getNumericDomain, normalizeLineChartSeries, stackLineChartSeries } from "./LineChart.utils.js";
|
|
8
8
|
import { LineChartPlot } from "./LineChartPlot.js";
|
|
9
9
|
import { useState } from "react";
|
|
10
10
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
@@ -18,6 +18,7 @@ var CHART_MARGIN_RIGHT = 8;
|
|
|
18
18
|
var DEFAULT_STROKE_WIDTH = 2;
|
|
19
19
|
var NUMBER_FORMATTER = new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 });
|
|
20
20
|
var defaultFormatValue = (value) => NUMBER_FORMATTER.format(value);
|
|
21
|
+
var getSeriesColor = (color, variant) => variant === "stacked-area" ? getCategoricalFillColor(color) : color;
|
|
21
22
|
var resolveAxisLayouts = (series, configuredAxes, xDomain, connectNulls) => {
|
|
22
23
|
const axisConfigs = new Map(configuredAxes?.map((axis) => [axis.id, axis]) ?? []);
|
|
23
24
|
const axisIds = Array.from(new Set(configuredAxes?.map((axis) => axis.id) ?? []));
|
|
@@ -45,6 +46,19 @@ var resolveAxisLayouts = (series, configuredAxes, xDomain, connectNulls) => {
|
|
|
45
46
|
};
|
|
46
47
|
});
|
|
47
48
|
};
|
|
49
|
+
var getStackedEdges = (series) => series.flatMap(({ yAxisId, points }) => [{
|
|
50
|
+
yAxisId,
|
|
51
|
+
points: points.map(({ x, y0 }) => ({
|
|
52
|
+
x,
|
|
53
|
+
y: y0
|
|
54
|
+
}))
|
|
55
|
+
}, {
|
|
56
|
+
yAxisId,
|
|
57
|
+
points: points.map(({ x, y1 }) => ({
|
|
58
|
+
x,
|
|
59
|
+
y: y1
|
|
60
|
+
}))
|
|
61
|
+
}]);
|
|
48
62
|
var resolveAxes = (layouts, innerHeight) => layouts.map(({ config, domain, nice, thickness }) => ({
|
|
49
63
|
...config,
|
|
50
64
|
thickness,
|
|
@@ -55,11 +69,11 @@ var resolveAxes = (layouts, innerHeight) => layouts.map(({ config, domain, nice,
|
|
|
55
69
|
})
|
|
56
70
|
}));
|
|
57
71
|
/**
|
|
58
|
-
* Responsive numeric line chart with nullable observations,
|
|
59
|
-
* legend filtering, configurable grids and x scales, brushing,
|
|
60
|
-
* consumer-owned tooltip interactions.
|
|
72
|
+
* Responsive numeric line or stacked-area chart with nullable observations,
|
|
73
|
+
* multiple axes, legend filtering, configurable grids and x scales, brushing,
|
|
74
|
+
* and consumer-owned tooltip interactions.
|
|
61
75
|
*/
|
|
62
|
-
var LineChart = ({ series, 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, showPoints = false, connectNulls = true, grid, activeX, activeLegendItemId, selectionRange, yBands = [], verticalMarkers = [], renderActiveOverlay, shouldAnimate = true, isRendering = true, showLegend, legendProps, onDatumPointerDown, onDatumPointerMove, onDatumPointerOut, onDatumPointerUp, className, ...rest }) => {
|
|
63
77
|
const [activeBuiltInLegendItemId, setActiveBuiltInLegendItemId] = useState(null);
|
|
64
78
|
const ariaProps = {
|
|
65
79
|
"aria-describedby": rest["aria-describedby"],
|
|
@@ -73,7 +87,7 @@ var LineChart = ({ series, yAxes, xDomain, formatXValue = defaultFormatValue, xS
|
|
|
73
87
|
const defaultAxisId = yAxes?.[0]?.id ?? DEFAULT_AXIS_ID;
|
|
74
88
|
const displaySeries = normalizedSeries.map((item, index) => ({
|
|
75
89
|
...item,
|
|
76
|
-
color: item.color ?? getCategoricalLineChartColor(index),
|
|
90
|
+
color: getSeriesColor(item.color ?? getCategoricalLineChartColor(index), variant),
|
|
77
91
|
yAxisId: item.yAxisId ?? defaultAxisId,
|
|
78
92
|
strokeWidth: item.strokeWidth == null || !Number.isFinite(item.strokeWidth) ? DEFAULT_STROKE_WIDTH : Math.max(0, item.strokeWidth),
|
|
79
93
|
opacity: item.opacity == null || !Number.isFinite(item.opacity) ? 1 : Math.min(1, Math.max(0, item.opacity)),
|
|
@@ -89,7 +103,8 @@ var LineChart = ({ series, yAxes, xDomain, formatXValue = defaultFormatValue, xS
|
|
|
89
103
|
})) : visibleSeries;
|
|
90
104
|
const renderedActiveX = xScaleType !== "band" || activeX != null && activeX >= resolvedXDomain[0] && activeX <= resolvedXDomain[1] ? activeX : void 0;
|
|
91
105
|
const renderedVerticalMarkers = xScaleType === "band" ? verticalMarkers.filter((marker) => marker.x >= resolvedXDomain[0] && marker.x <= resolvedXDomain[1]) : verticalMarkers;
|
|
92
|
-
const
|
|
106
|
+
const stackedSeries = variant === "stacked-area" ? stackLineChartSeries(renderedSeries) : void 0;
|
|
107
|
+
const axisLayouts = resolveAxisLayouts(stackedSeries == null ? renderedSeries : getStackedEdges(stackedSeries), yAxes, resolvedXDomain, connectNulls);
|
|
93
108
|
const chartMargin = {
|
|
94
109
|
top: CHART_MARGIN_TOP,
|
|
95
110
|
right: CHART_MARGIN_RIGHT + axisLayouts.slice(1).reduce((total, axis) => total + axis.thickness, 0),
|
|
@@ -144,6 +159,7 @@ var LineChart = ({ series, yAxes, xDomain, formatXValue = defaultFormatValue, xS
|
|
|
144
159
|
uniqueXValues,
|
|
145
160
|
axes,
|
|
146
161
|
series: renderedSeries,
|
|
162
|
+
stackedSeries,
|
|
147
163
|
formatXValue,
|
|
148
164
|
xTickCount,
|
|
149
165
|
xTickValues,
|
|
@@ -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 { getCategoricalLineChartColor } 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 LineChartYAxis,\n} from './LineChart.types';\nimport {\n createLineChartXScaleAdapter,\n getLineChartYDomainValues,\n getLineSegments,\n getNumericDomain,\n normalizeLineChartSeries,\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 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\nconst resolveAxisLayouts = (\n series: readonly LineChartDisplaySeries[],\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\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 chart with nullable observations, multiple axes,\n * legend filtering, configurable grids and x scales, brushing, and\n * consumer-owned tooltip interactions.\n */\nexport const LineChart = ({\n series,\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: item.color ?? getCategoricalLineChartColor(index),\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 axisLayouts = resolveAxisLayouts(\n renderedSeries,\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 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":";;;;;;;;;;;;;AAw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;;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 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,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,iBAAiB,wBAAwB,KAAK,IAAI;AAEhE,IAAM,sBACJ,QACA,gBACA,SACA,iBACmC;CACnC,MAAM,cAAc,IAAI,IACtB,gBAAgB,KAAK,SAAS,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,CACrD;CACA,MAAM,UAAU,MAAM,KACpB,IAAI,IAAI,gBAAgB,KAAK,SAAS,KAAK,EAAE,KAAK,CAAC,CAAC,CACtD;CAEA,KAAK,MAAM,QAAQ,QACjB,IAAI,CAAC,QAAQ,SAAS,KAAK,OAAO,GAAG,QAAQ,KAAK,KAAK,OAAO;CAEhE,IAAI,QAAQ,WAAW,GAAG,QAAQ,KAAK,eAAe;CAEtD,OAAO,QAAQ,KAAK,WAAgC;EAClD,MAAM,SAAS,YAAY,IAAI,MAAM,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,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"}
|
|
@@ -47,6 +47,7 @@ export type LineChartInteractionDatum = {
|
|
|
47
47
|
points: readonly LineChartInteractionPoint[];
|
|
48
48
|
};
|
|
49
49
|
export type LineChartXScale = 'linear' | 'band';
|
|
50
|
+
export type LineChartVariant = 'line' | 'stacked-area';
|
|
50
51
|
export type LineChartSelectionRange = {
|
|
51
52
|
from: number;
|
|
52
53
|
to: number;
|
|
@@ -95,6 +96,14 @@ export type LineChartDisplaySeries = {
|
|
|
95
96
|
opacity: number;
|
|
96
97
|
showActiveMarker: boolean;
|
|
97
98
|
};
|
|
99
|
+
/** A stacked-area point. `y` keeps the series' own value; `y0` and `y1` bound its band. */
|
|
100
|
+
export type LineChartStackedPoint = LineChartPoint & {
|
|
101
|
+
y0: number;
|
|
102
|
+
y1: number;
|
|
103
|
+
};
|
|
104
|
+
export type LineChartStackedSeries = Omit<LineChartDisplaySeries, 'points'> & {
|
|
105
|
+
points: readonly LineChartStackedPoint[];
|
|
106
|
+
};
|
|
98
107
|
export type LineChartDisplayAxis = LineChartYAxis & {
|
|
99
108
|
thickness: number;
|
|
100
109
|
scale: ReturnType<typeof scaleLinear<number>>;
|
|
@@ -109,6 +118,15 @@ type LineChartLegendConfig = {
|
|
|
109
118
|
};
|
|
110
119
|
export type LineChartProps = Omit<HTMLAttributes<HTMLDivElement>, 'children' | 'onPointerLeave' | 'onPointerMove' | 'onPointerOut' | 'onPointerUp' | 'aria-describedby' | 'aria-label'> & LineChartLegendConfig & {
|
|
111
120
|
series: readonly LineChartSeries[];
|
|
121
|
+
/**
|
|
122
|
+
* `line` compares how individual series change. `stacked-area` shows a
|
|
123
|
+
* total and each series' contribution, so use it only for same-unit values
|
|
124
|
+
* that add up, such as counts, never averages, rates, latency, or
|
|
125
|
+
* percentiles. It stacks series that share a y axis as solid areas, using
|
|
126
|
+
* the fill palette and ignoring stroke styles. A missing or null value adds
|
|
127
|
+
* nothing to its stack. Defaults to line.
|
|
128
|
+
*/
|
|
129
|
+
variant?: LineChartVariant;
|
|
112
130
|
yAxes?: readonly LineChartYAxis[];
|
|
113
131
|
xDomain?: readonly [number, number];
|
|
114
132
|
formatXValue?: (value: number) => string;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { scaleBand, scaleLinear } from '@visx/scale';
|
|
2
|
-
import type { LineChartPoint, LineChartSeries, LineChartXScale } from './LineChart.types.js';
|
|
2
|
+
import type { LineChartDisplaySeries, LineChartPoint, LineChartSeries, LineChartStackedSeries, LineChartXScale } from './LineChart.types.js';
|
|
3
3
|
export type NormalizedLineChartSeries = Omit<LineChartSeries, 'points'> & {
|
|
4
4
|
points: readonly LineChartPoint[];
|
|
5
5
|
};
|
|
@@ -26,4 +26,10 @@ export declare const getNumericDomain: (values: readonly number[], configuredDom
|
|
|
26
26
|
export declare const normalizeLineChartSeries: (series: readonly LineChartSeries[]) => readonly NormalizedLineChartSeries[];
|
|
27
27
|
export declare const getLineSegments: (points: readonly LineChartPoint[], connectNulls?: boolean) => readonly LineChartPoint[][];
|
|
28
28
|
export declare const getLineChartYDomainValues: (points: readonly LineChartPoint[], domain: readonly [number, number], connectNulls?: boolean) => number[];
|
|
29
|
+
/**
|
|
30
|
+
* Stacks series per y axis in input order, at every x value on that axis.
|
|
31
|
+
* Positive values stack up from zero and negative values down, matching
|
|
32
|
+
* stacked bars.
|
|
33
|
+
*/
|
|
34
|
+
export declare const stackLineChartSeries: (series: readonly LineChartDisplaySeries[]) => readonly LineChartStackedSeries[];
|
|
29
35
|
export {};
|
|
@@ -117,7 +117,41 @@ var getLineChartYDomainValues = (points, domain, connectNulls = true) => {
|
|
|
117
117
|
}
|
|
118
118
|
return values;
|
|
119
119
|
};
|
|
120
|
+
/**
|
|
121
|
+
* Stacks series per y axis in input order, at every x value on that axis.
|
|
122
|
+
* Positive values stack up from zero and negative values down, matching
|
|
123
|
+
* stacked bars.
|
|
124
|
+
*/
|
|
125
|
+
var stackLineChartSeries = (series) => {
|
|
126
|
+
const xValuesByAxis = /* @__PURE__ */ new Map();
|
|
127
|
+
for (const item of series) {
|
|
128
|
+
const xValues = xValuesByAxis.get(item.yAxisId) ?? /* @__PURE__ */ new Set();
|
|
129
|
+
for (const point of item.points) xValues.add(point.x);
|
|
130
|
+
xValuesByAxis.set(item.yAxisId, xValues);
|
|
131
|
+
}
|
|
132
|
+
const totals = /* @__PURE__ */ new Map();
|
|
133
|
+
return series.map((item) => {
|
|
134
|
+
const values = new Map(item.points.map((point) => [point.x, point.y]));
|
|
135
|
+
const xValues = Array.from(xValuesByAxis.get(item.yAxisId) ?? []).sort((left, right) => left - right);
|
|
136
|
+
return {
|
|
137
|
+
...item,
|
|
138
|
+
points: xValues.map((x) => {
|
|
139
|
+
const y = values.get(x) ?? null;
|
|
140
|
+
const key = `${item.yAxisId}:${(y ?? 0) < 0 ? "-" : "+"}:${x}`;
|
|
141
|
+
const y0 = totals.get(key) ?? 0;
|
|
142
|
+
const y1 = y0 + (y ?? 0);
|
|
143
|
+
totals.set(key, y1);
|
|
144
|
+
return {
|
|
145
|
+
x,
|
|
146
|
+
y,
|
|
147
|
+
y0,
|
|
148
|
+
y1
|
|
149
|
+
};
|
|
150
|
+
})
|
|
151
|
+
};
|
|
152
|
+
});
|
|
153
|
+
};
|
|
120
154
|
//#endregion
|
|
121
|
-
export { createLineChartXScaleAdapter, getLineChartYDomainValues, getLineSegments, getNumericDomain, getSelectionBounds, normalizeLineChartSeries };
|
|
155
|
+
export { createLineChartXScaleAdapter, getLineChartYDomainValues, getLineSegments, getNumericDomain, getSelectionBounds, normalizeLineChartSeries, stackLineChartSeries };
|
|
122
156
|
|
|
123
157
|
//# sourceMappingURL=LineChart.utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LineChart.utils.js","names":[],"sources":["../../../src/components/LineChart/LineChart.utils.ts"],"sourcesContent":["import { scaleBand, scaleLinear } from '@visx/scale';\n\nimport type {\n LineChartPoint,\n LineChartSeries,\n LineChartXScale,\n} from './LineChart.types';\n\nexport type NormalizedLineChartSeries = Omit<LineChartSeries, 'points'> & {\n points: readonly LineChartPoint[];\n};\n\ntype CreateLineChartXScaleAdapterArgs = {\n type: LineChartXScale;\n domain: readonly [number, number];\n values: readonly number[];\n width: number;\n nice: boolean;\n};\n\nexport type LineChartScale =\n | ReturnType<typeof scaleBand<number>>\n | ReturnType<typeof scaleLinear<number>>;\n\nexport type LineChartXScaleAdapter = {\n scale: LineChartScale;\n getPosition: (value: number) => number;\n getValue: (position: number) => number;\n getRangePosition: (value: number) => number;\n};\n\nexport const getSelectionBounds = (\n start: number | null,\n end: number | null,\n maximum: number\n) => {\n if (\n start == null ||\n end == null ||\n !Number.isFinite(start) ||\n !Number.isFinite(end)\n ) {\n return null;\n }\n const clampedStart = Math.max(0, Math.min(maximum, start));\n const clampedEnd = Math.max(0, Math.min(maximum, end));\n return {\n x: Math.min(clampedStart, clampedEnd),\n width: Math.abs(clampedEnd - clampedStart),\n };\n};\n\nconst expandFlatDomain = (value: number): [number, number] => {\n const padding = Math.max(Math.abs(value) * 0.05, 1);\n return [value - padding, value + padding];\n};\n\nconst interpolateValue = (\n value: number,\n inputs: readonly number[],\n outputs: readonly number[]\n): number => {\n const firstInput = inputs[0];\n const firstOutput = outputs[0];\n if (firstInput == null || firstOutput == null) return 0;\n if (inputs.length === 1) return firstOutput;\n\n const lastInput = inputs.at(-1);\n const lastOutput = outputs.at(-1);\n if (lastInput == null || lastOutput == null) return firstOutput;\n\n const upperIndex = inputs.findIndex(\n (input, index) => index > 0 && value <= input\n );\n const resolvedUpperIndex = upperIndex === -1 ? inputs.length - 1 : upperIndex;\n const input = inputs[resolvedUpperIndex];\n const previousInput = inputs[resolvedUpperIndex - 1];\n const output = outputs[resolvedUpperIndex];\n const previousOutput = outputs[resolvedUpperIndex - 1];\n if (\n input == null ||\n previousInput == null ||\n output == null ||\n previousOutput == null\n ) {\n return lastOutput;\n }\n\n const inputDistance = input - previousInput;\n if (inputDistance === 0) return previousOutput;\n const ratio = (value - previousInput) / inputDistance;\n return previousOutput + ratio * (output - previousOutput);\n};\n\nexport const createLineChartXScaleAdapter = ({\n type,\n domain,\n values,\n width,\n nice,\n}: CreateLineChartXScaleAdapterArgs): LineChartXScaleAdapter => {\n if (type === 'band') {\n const scale = scaleBand<number>({\n domain: Array.from(values),\n range: [0, width],\n padding: 0.1,\n });\n const positions = values.map(\n (value) => (scale(value) ?? 0) + scale.bandwidth() / 2\n );\n const getBandPosition = (value: number) => {\n const firstValue = values[0];\n if (firstValue == null) return Number.NaN;\n if (values.length === 1 && value !== firstValue) {\n return value < firstValue ? -scale.step() : width + scale.step();\n }\n return interpolateValue(value, values, positions);\n };\n return {\n scale,\n getPosition: getBandPosition,\n getValue: (position: number) =>\n Math.max(\n domain[0],\n Math.min(domain[1], interpolateValue(position, positions, values))\n ),\n getRangePosition: getBandPosition,\n };\n }\n\n const scale = scaleLinear<number>({\n domain: Array.from(domain),\n range: [0, width],\n nice,\n });\n return {\n scale,\n getPosition: (value: number) => scale(value),\n getValue: (position: number) => scale.invert(position),\n getRangePosition: (value: number) => scale(value),\n };\n};\n\nexport const getNumericDomain = (\n values: readonly number[],\n configuredDomain?: readonly [number, number]\n): [number, number] => {\n if (\n configuredDomain != null &&\n Number.isFinite(configuredDomain[0]) &&\n Number.isFinite(configuredDomain[1])\n ) {\n const minimum = Math.min(configuredDomain[0], configuredDomain[1]);\n const maximum = Math.max(configuredDomain[0], configuredDomain[1]);\n return minimum === maximum ? expandFlatDomain(minimum) : [minimum, maximum];\n }\n\n const finiteValues = values.filter(Number.isFinite);\n if (finiteValues.length === 0) return [0, 1];\n\n const minimum = Math.min(...finiteValues);\n const maximum = Math.max(...finiteValues);\n return minimum === maximum ? expandFlatDomain(minimum) : [minimum, maximum];\n};\n\nexport const normalizeLineChartSeries = (\n series: readonly LineChartSeries[]\n): readonly NormalizedLineChartSeries[] =>\n series.map((item) => ({\n ...item,\n points: item.points\n .reduce<LineChartPoint[]>((points, point) => {\n if (!Number.isFinite(point.x)) return points;\n points.push({\n x: point.x,\n y: point.y != null && Number.isFinite(point.y) ? point.y : null,\n });\n return points;\n }, [])\n .sort((left, right) => left.x - right.x),\n }));\n\nexport const getLineSegments = (\n points: readonly LineChartPoint[],\n connectNulls = true\n): readonly LineChartPoint[][] => {\n if (connectNulls) {\n const validPoints = points.filter((point) => point.y != null);\n return validPoints.length === 0 ? [] : [validPoints];\n }\n\n const segments: LineChartPoint[][] = [];\n let current: LineChartPoint[] = [];\n\n for (const point of points) {\n if (point.y == null) {\n if (current.length > 0) segments.push(current);\n current = [];\n } else {\n current.push(point);\n }\n }\n\n if (current.length > 0) segments.push(current);\n return segments;\n};\n\nexport const getLineChartYDomainValues = (\n points: readonly LineChartPoint[],\n domain: readonly [number, number],\n connectNulls = true\n): number[] => {\n const values = points.flatMap((point) =>\n point.x >= domain[0] && point.x <= domain[1] && point.y != null\n ? [point.y]\n : []\n );\n const renderedPoints = connectNulls\n ? points.filter((point) => point.y != null)\n : points;\n\n for (let index = 1; index < renderedPoints.length; index += 1) {\n const previousPoint = renderedPoints[index - 1];\n const point = renderedPoints[index];\n if (\n previousPoint?.y == null ||\n point?.y == null ||\n previousPoint.x === point.x\n ) {\n continue;\n }\n\n for (const boundary of domain) {\n if (previousPoint.x >= boundary || point.x <= boundary) continue;\n const ratio = (boundary - previousPoint.x) / (point.x - previousPoint.x);\n values.push(previousPoint.y + ratio * (point.y - previousPoint.y));\n }\n }\n\n return values;\n};\n"],"mappings":";;AA+BA,IAAa,sBACX,OACA,KACA,YACG;CACH,IACE,SAAS,QACT,OAAO,QACP,CAAC,OAAO,SAAS,KAAK,KACtB,CAAC,OAAO,SAAS,GAAG,GAEpB,OAAO;CAET,MAAM,eAAe,KAAK,IAAI,GAAG,K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AAe,KAAK,QACpB,OAAO,KAAK,QACZ,cAAc,MAAM,MAAM,GAE1B;EAGF,KAAK,MAAM,YAAY,QAAQ;GAC7B,IAAI,cAAc,KAAK,YAAY,MAAM,KAAK,UAAU;GACxD,MAAM,SAAS,WAAW,cAAc,MAAM,MAAM,IAAI,cAAc;GACtE,OAAO,KAAK,cAAc,IAAI,SAAS,MAAM,IAAI,cAAc,EAAE;EACnE;CACF;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"LineChart.utils.js","names":[],"sources":["../../../src/components/LineChart/LineChart.utils.ts"],"sourcesContent":["import { scaleBand, scaleLinear } from '@visx/scale';\n\nimport type {\n LineChartDisplaySeries,\n LineChartPoint,\n LineChartSeries,\n LineChartStackedSeries,\n LineChartXScale,\n} from './LineChart.types';\n\nexport type NormalizedLineChartSeries = Omit<LineChartSeries, 'points'> & {\n points: readonly LineChartPoint[];\n};\n\ntype CreateLineChartXScaleAdapterArgs = {\n type: LineChartXScale;\n domain: readonly [number, number];\n values: readonly number[];\n width: number;\n nice: boolean;\n};\n\nexport type LineChartScale =\n | ReturnType<typeof scaleBand<number>>\n | ReturnType<typeof scaleLinear<number>>;\n\nexport type LineChartXScaleAdapter = {\n scale: LineChartScale;\n getPosition: (value: number) => number;\n getValue: (position: number) => number;\n getRangePosition: (value: number) => number;\n};\n\nexport const getSelectionBounds = (\n start: number | null,\n end: number | null,\n maximum: number\n) => {\n if (\n start == null ||\n end == null ||\n !Number.isFinite(start) ||\n !Number.isFinite(end)\n ) {\n return null;\n }\n const clampedStart = Math.max(0, Math.min(maximum, start));\n const clampedEnd = Math.max(0, Math.min(maximum, end));\n return {\n x: Math.min(clampedStart, clampedEnd),\n width: Math.abs(clampedEnd - clampedStart),\n };\n};\n\nconst expandFlatDomain = (value: number): [number, number] => {\n const padding = Math.max(Math.abs(value) * 0.05, 1);\n return [value - padding, value + padding];\n};\n\nconst interpolateValue = (\n value: number,\n inputs: readonly number[],\n outputs: readonly number[]\n): number => {\n const firstInput = inputs[0];\n const firstOutput = outputs[0];\n if (firstInput == null || firstOutput == null) return 0;\n if (inputs.length === 1) return firstOutput;\n\n const lastInput = inputs.at(-1);\n const lastOutput = outputs.at(-1);\n if (lastInput == null || lastOutput == null) return firstOutput;\n\n const upperIndex = inputs.findIndex(\n (input, index) => index > 0 && value <= input\n );\n const resolvedUpperIndex = upperIndex === -1 ? inputs.length - 1 : upperIndex;\n const input = inputs[resolvedUpperIndex];\n const previousInput = inputs[resolvedUpperIndex - 1];\n const output = outputs[resolvedUpperIndex];\n const previousOutput = outputs[resolvedUpperIndex - 1];\n if (\n input == null ||\n previousInput == null ||\n output == null ||\n previousOutput == null\n ) {\n return lastOutput;\n }\n\n const inputDistance = input - previousInput;\n if (inputDistance === 0) return previousOutput;\n const ratio = (value - previousInput) / inputDistance;\n return previousOutput + ratio * (output - previousOutput);\n};\n\nexport const createLineChartXScaleAdapter = ({\n type,\n domain,\n values,\n width,\n nice,\n}: CreateLineChartXScaleAdapterArgs): LineChartXScaleAdapter => {\n if (type === 'band') {\n const scale = scaleBand<number>({\n domain: Array.from(values),\n range: [0, width],\n padding: 0.1,\n });\n const positions = values.map(\n (value) => (scale(value) ?? 0) + scale.bandwidth() / 2\n );\n const getBandPosition = (value: number) => {\n const firstValue = values[0];\n if (firstValue == null) return Number.NaN;\n if (values.length === 1 && value !== firstValue) {\n return value < firstValue ? -scale.step() : width + scale.step();\n }\n return interpolateValue(value, values, positions);\n };\n return {\n scale,\n getPosition: getBandPosition,\n getValue: (position: number) =>\n Math.max(\n domain[0],\n Math.min(domain[1], interpolateValue(position, positions, values))\n ),\n getRangePosition: getBandPosition,\n };\n }\n\n const scale = scaleLinear<number>({\n domain: Array.from(domain),\n range: [0, width],\n nice,\n });\n return {\n scale,\n getPosition: (value: number) => scale(value),\n getValue: (position: number) => scale.invert(position),\n getRangePosition: (value: number) => scale(value),\n };\n};\n\nexport const getNumericDomain = (\n values: readonly number[],\n configuredDomain?: readonly [number, number]\n): [number, number] => {\n if (\n configuredDomain != null &&\n Number.isFinite(configuredDomain[0]) &&\n Number.isFinite(configuredDomain[1])\n ) {\n const minimum = Math.min(configuredDomain[0], configuredDomain[1]);\n const maximum = Math.max(configuredDomain[0], configuredDomain[1]);\n return minimum === maximum ? expandFlatDomain(minimum) : [minimum, maximum];\n }\n\n const finiteValues = values.filter(Number.isFinite);\n if (finiteValues.length === 0) return [0, 1];\n\n const minimum = Math.min(...finiteValues);\n const maximum = Math.max(...finiteValues);\n return minimum === maximum ? expandFlatDomain(minimum) : [minimum, maximum];\n};\n\nexport const normalizeLineChartSeries = (\n series: readonly LineChartSeries[]\n): readonly NormalizedLineChartSeries[] =>\n series.map((item) => ({\n ...item,\n points: item.points\n .reduce<LineChartPoint[]>((points, point) => {\n if (!Number.isFinite(point.x)) return points;\n points.push({\n x: point.x,\n y: point.y != null && Number.isFinite(point.y) ? point.y : null,\n });\n return points;\n }, [])\n .sort((left, right) => left.x - right.x),\n }));\n\nexport const getLineSegments = (\n points: readonly LineChartPoint[],\n connectNulls = true\n): readonly LineChartPoint[][] => {\n if (connectNulls) {\n const validPoints = points.filter((point) => point.y != null);\n return validPoints.length === 0 ? [] : [validPoints];\n }\n\n const segments: LineChartPoint[][] = [];\n let current: LineChartPoint[] = [];\n\n for (const point of points) {\n if (point.y == null) {\n if (current.length > 0) segments.push(current);\n current = [];\n } else {\n current.push(point);\n }\n }\n\n if (current.length > 0) segments.push(current);\n return segments;\n};\n\nexport const getLineChartYDomainValues = (\n points: readonly LineChartPoint[],\n domain: readonly [number, number],\n connectNulls = true\n): number[] => {\n const values = points.flatMap((point) =>\n point.x >= domain[0] && point.x <= domain[1] && point.y != null\n ? [point.y]\n : []\n );\n const renderedPoints = connectNulls\n ? points.filter((point) => point.y != null)\n : points;\n\n for (let index = 1; index < renderedPoints.length; index += 1) {\n const previousPoint = renderedPoints[index - 1];\n const point = renderedPoints[index];\n if (\n previousPoint?.y == null ||\n point?.y == null ||\n previousPoint.x === point.x\n ) {\n continue;\n }\n\n for (const boundary of domain) {\n if (previousPoint.x >= boundary || point.x <= boundary) continue;\n const ratio = (boundary - previousPoint.x) / (point.x - previousPoint.x);\n values.push(previousPoint.y + ratio * (point.y - previousPoint.y));\n }\n }\n\n return values;\n};\n\n/**\n * Stacks series per y axis in input order, at every x value on that axis.\n * Positive values stack up from zero and negative values down, matching\n * stacked bars.\n */\nexport const stackLineChartSeries = (\n series: readonly LineChartDisplaySeries[]\n): readonly LineChartStackedSeries[] => {\n const xValuesByAxis = new Map<string, Set<number>>();\n for (const item of series) {\n const xValues = xValuesByAxis.get(item.yAxisId) ?? new Set<number>();\n for (const point of item.points) xValues.add(point.x);\n xValuesByAxis.set(item.yAxisId, xValues);\n }\n // Running stack heights keyed by axis, sign, and x.\n const totals = new Map<string, number>();\n\n return series.map((item) => {\n const values = new Map(item.points.map((point) => [point.x, point.y]));\n const xValues = Array.from(xValuesByAxis.get(item.yAxisId) ?? []).sort(\n (left, right) => left - right\n );\n return {\n ...item,\n points: xValues.map((x) => {\n const y = values.get(x) ?? null;\n const key = `${item.yAxisId}:${(y ?? 0) < 0 ? '-' : '+'}:${x}`;\n const y0 = totals.get(key) ?? 0;\n const y1 = y0 + (y ?? 0);\n totals.set(key, y1);\n return { x, y, y0, y1 };\n }),\n };\n });\n};\n"],"mappings":";;AAiCA,IAAa,sBACX,OACA,KACA,YACG;CACH,IACE,SAAS,QACT,OAAO,QACP,CAAC,OAAO,SAAS,KAAK,KACtB,CAAC,OAAO,SAAS,GAAG,GAEpB,OAAO;CAET,MAAM,eAAe,KAAK,IAAI,GAAG,KAAK,IAAI,SAAS,KAAK,CAAC;CACzD,MAAM,aAAa,KAAK,IAAI,GAAG,KAAK,IAAI,SAAS,GAAG,CAAC;CACrD,OAAO;EACL,GAAG,KAAK,IAAI,cAAc,UAAU;EACpC,OAAO,KAAK,IAAI,aAAa,YAAY;CAC3C;AACF;AAEA,IAAM,oBAAoB,UAAoC;CAC5D,MAAM,UAAU,KAAK,IAA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c,EAAE;EACnE;CACF;CAEA,OAAO;AACT;;;;;;AAOA,IAAa,wBACX,WACsC;CACtC,MAAM,gCAAgB,IAAI,IAAyB;CACnD,KAAK,MAAM,QAAQ,QAAQ;EACzB,MAAM,UAAU,cAAc,IAAI,KAAK,OAAO,qBAAK,IAAI,IAAY;EACnE,KAAK,MAAM,SAAS,KAAK,QAAQ,QAAQ,IAAI,MAAM,CAAC;EACpD,cAAc,IAAI,KAAK,SAAS,OAAO;CACzC;CAEA,MAAM,yBAAS,IAAI,IAAoB;CAEvC,OAAO,OAAO,KAAK,SAAS;EAC1B,MAAM,SAAS,IAAI,IAAI,KAAK,OAAO,KAAK,UAAU,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC,CAAC;EACrE,MAAM,UAAU,MAAM,KAAK,cAAc,IAAI,KAAK,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,MAC/D,MAAM,UAAU,OAAO,KAC1B;EACA,OAAO;GACL,GAAG;GACH,QAAQ,QAAQ,KAAK,MAAM;IACzB,MAAM,IAAI,OAAO,IAAI,CAAC,KAAK;IAC3B,MAAM,MAAM,GAAG,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,MAAM,IAAI,GAAG;IAC3D,MAAM,KAAK,OAAO,IAAI,GAAG,KAAK;IAC9B,MAAM,KAAK,MAAM,KAAK;IACtB,OAAO,IAAI,KAAK,EAAE;IAClB,OAAO;KAAE;KAAG;KAAG;KAAI;IAAG;GACxB,CAAC;EACH;CACF,CAAC;AACH"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type AriaAttributes, type PointerEvent } from 'react';
|
|
2
2
|
import type { scaleBand, scaleLinear } from '@visx/scale';
|
|
3
|
-
import type { LineChartDisplayAxis, LineChartDisplaySeries, LineChartInteractionDatum, LineChartSelectionRange, LineChartVerticalMarker, LineChartYBand } from './LineChart.types.js';
|
|
3
|
+
import type { LineChartDisplayAxis, LineChartDisplaySeries, LineChartInteractionDatum, LineChartSelectionRange, LineChartStackedSeries, LineChartVerticalMarker, LineChartYBand } from './LineChart.types.js';
|
|
4
4
|
type LineChartPlotProps = {
|
|
5
5
|
width: number;
|
|
6
6
|
height: number;
|
|
@@ -19,6 +19,8 @@ type LineChartPlotProps = {
|
|
|
19
19
|
uniqueXValues: readonly number[];
|
|
20
20
|
axes: readonly LineChartDisplayAxis[];
|
|
21
21
|
series: readonly LineChartDisplaySeries[];
|
|
22
|
+
/** Replaces the series lines with areas when set. */
|
|
23
|
+
stackedSeries?: readonly LineChartStackedSeries[];
|
|
22
24
|
formatXValue: (value: number) => string;
|
|
23
25
|
xTickCount?: number;
|
|
24
26
|
xTickValues?: readonly number[];
|
|
@@ -40,5 +42,5 @@ type LineChartPlotProps = {
|
|
|
40
42
|
onDatumPointerOut?: () => void;
|
|
41
43
|
onDatumPointerUp?: (datum: LineChartInteractionDatum, event: PointerEvent<SVGSVGElement>) => void;
|
|
42
44
|
};
|
|
43
|
-
export declare const LineChartPlot: ({ width, height, innerWidth, innerHeight, chartMargin, xScale, getXPosition, getXValue, getXRangePosition, uniqueXValues, axes, series, formatXValue, xTickCount, xTickValues, showPoints, connectNulls, showGridRows, showGridColumns, activeX, activeLegendItemId, selectionRange, yBands, verticalMarkers, shouldAnimate, isRendering, onDatumPointerDown, onDatumPointerMove, onDatumPointerOut, onDatumPointerUp, ...ariaProps }: LineChartPlotProps) => import("react").JSX.Element;
|
|
45
|
+
export declare const LineChartPlot: ({ width, height, innerWidth, innerHeight, chartMargin, xScale, getXPosition, getXValue, getXRangePosition, uniqueXValues, axes, series, stackedSeries, formatXValue, xTickCount, xTickValues, showPoints, connectNulls, showGridRows, showGridColumns, activeX, activeLegendItemId, selectionRange, yBands, verticalMarkers, shouldAnimate, isRendering, onDatumPointerDown, onDatumPointerMove, onDatumPointerOut, onDatumPointerUp, ...ariaProps }: LineChartPlotProps) => import("react").JSX.Element;
|
|
44
46
|
export {};
|
|
@@ -12,7 +12,7 @@ import { animated, useReducedMotion, useSpring } from "@react-spring/web";
|
|
|
12
12
|
import { Group } from "@visx/group";
|
|
13
13
|
import { AxisBottom, AxisLeft, AxisRight } from "@visx/axis";
|
|
14
14
|
import { GridColumns, GridRows } from "@visx/grid";
|
|
15
|
-
import { LinePath } from "@visx/shape";
|
|
15
|
+
import { Area, LinePath } from "@visx/shape";
|
|
16
16
|
import { curveLinear } from "@visx/curve";
|
|
17
17
|
//#region packages/components/src/components/LineChart/LineChartPlot.tsx
|
|
18
18
|
var defaultFormatValue = new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 }).format;
|
|
@@ -27,7 +27,7 @@ var getInteractionDatum = (nearestX, series, xPosition, pointerX) => ({
|
|
|
27
27
|
value: item.points.find((point) => point.x === nearestX)?.y ?? null
|
|
28
28
|
}))
|
|
29
29
|
});
|
|
30
|
-
var LineChartPlot = ({ width, height, innerWidth, innerHeight, chartMargin, xScale, getXPosition, getXValue, getXRangePosition, uniqueXValues, axes, series, formatXValue, xTickCount, xTickValues, showPoints, connectNulls, showGridRows, showGridColumns, activeX, activeLegendItemId, selectionRange, yBands, verticalMarkers, shouldAnimate, isRendering, onDatumPointerDown, onDatumPointerMove, onDatumPointerOut, onDatumPointerUp, ...ariaProps }) => {
|
|
30
|
+
var LineChartPlot = ({ width, height, innerWidth, innerHeight, chartMargin, xScale, getXPosition, getXValue, getXRangePosition, uniqueXValues, axes, series, stackedSeries, formatXValue, xTickCount, xTickValues, showPoints, connectNulls, showGridRows, showGridColumns, activeX, activeLegendItemId, selectionRange, yBands, verticalMarkers, shouldAnimate, isRendering, onDatumPointerDown, onDatumPointerMove, onDatumPointerOut, onDatumPointerUp, ...ariaProps }) => {
|
|
31
31
|
const activePointerId = useRef(null);
|
|
32
32
|
const clipPathId = `line-chart-${useId().replace(/:/g, "")}`;
|
|
33
33
|
const revealClipPathId = `${clipPathId}-reveal`;
|
|
@@ -42,6 +42,13 @@ var LineChartPlot = ({ width, height, innerWidth, innerHeight, chartMargin, xSca
|
|
|
42
42
|
const isReducedMotion = (useReducedMotion() ?? false) || !shouldAnimate;
|
|
43
43
|
const hasRenderedSeries = canRender && series.length > 0;
|
|
44
44
|
const getSeriesOpacity = (item) => item.opacity * (activeLegendItemId != null && activeLegendItemId !== item.id ? CHART_DIMMED_OPACITY : 1);
|
|
45
|
+
const markSeries = stackedSeries?.map((item) => ({
|
|
46
|
+
...item,
|
|
47
|
+
points: item.points.map(({ x, y, y1 }) => ({
|
|
48
|
+
x,
|
|
49
|
+
y: y == null ? null : y1
|
|
50
|
+
}))
|
|
51
|
+
})) ?? series;
|
|
45
52
|
const visibleSeriesKey = JSON.stringify(series.map((item) => item.id));
|
|
46
53
|
const [animation] = useSpring(() => ({
|
|
47
54
|
from: { progress: 0 },
|
|
@@ -205,7 +212,7 @@ var LineChartPlot = ({ width, height, innerWidth, innerHeight, chartMargin, xSca
|
|
|
205
212
|
children: [
|
|
206
213
|
/* @__PURE__ */ jsxs("g", {
|
|
207
214
|
clipPath: `url(#${revealClipPathId})`,
|
|
208
|
-
children: [series.map((item) => {
|
|
215
|
+
children: [stackedSeries == null ? series.map((item) => {
|
|
209
216
|
const axis = axisById.get(item.yAxisId);
|
|
210
217
|
if (axis == null) return null;
|
|
211
218
|
return /* @__PURE__ */ jsx("g", {
|
|
@@ -226,7 +233,24 @@ var LineChartPlot = ({ width, height, innerWidth, innerHeight, chartMargin, xSca
|
|
|
226
233
|
y: (point) => axis.scale(point.y ?? 0)
|
|
227
234
|
}, index))
|
|
228
235
|
}, item.id);
|
|
229
|
-
})
|
|
236
|
+
}) : stackedSeries.map((item) => {
|
|
237
|
+
const axis = axisById.get(item.yAxisId);
|
|
238
|
+
if (axis == null) return null;
|
|
239
|
+
return /* @__PURE__ */ jsx("g", {
|
|
240
|
+
role: "group",
|
|
241
|
+
"aria-label": `${item["aria-label"] ?? item.id} series`,
|
|
242
|
+
children: /* @__PURE__ */ jsx(Area, {
|
|
243
|
+
data: Array.from(item.points),
|
|
244
|
+
curve: curveLinear,
|
|
245
|
+
fill: item.color,
|
|
246
|
+
opacity: getSeriesOpacity(item),
|
|
247
|
+
className: "transition-opacity duration-fast motion-reduce:transition-none",
|
|
248
|
+
x: (point) => getXPosition(point.x),
|
|
249
|
+
y0: (point) => axis.scale(point.y0),
|
|
250
|
+
y1: (point) => axis.scale(point.y1)
|
|
251
|
+
})
|
|
252
|
+
}, item.id);
|
|
253
|
+
}), showPoints && markSeries.flatMap((item) => {
|
|
230
254
|
const axis = axisById.get(item.yAxisId);
|
|
231
255
|
if (axis == null) return [];
|
|
232
256
|
return item.points.flatMap((point, pointIndex) => point.y == null ? [] : [/* @__PURE__ */ jsx("circle", {
|
|
@@ -263,7 +287,7 @@ var LineChartPlot = ({ width, height, innerWidth, innerHeight, chartMargin, xSca
|
|
|
263
287
|
strokeWidth: 1,
|
|
264
288
|
strokeDasharray: "4 2",
|
|
265
289
|
className: "text-quaternary"
|
|
266
|
-
}),
|
|
290
|
+
}), markSeries.flatMap((item) => {
|
|
267
291
|
if (!item.showActiveMarker) return [];
|
|
268
292
|
const axis = axisById.get(item.yAxisId);
|
|
269
293
|
const point = item.points.find((candidate) => candidate.x === activeX);
|