@tetrascience-npm/tetrascience-react-ui 1.0.0-beta.147.1 → 1.0.0-beta.149.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/README.md +65 -7
- package/dist/components/charts/AreaPlot/AreaPlot.cjs +1 -1
- package/dist/components/charts/AreaPlot/AreaPlot.cjs.map +1 -1
- package/dist/components/charts/AreaPlot/AreaPlot.js +166 -148
- package/dist/components/charts/AreaPlot/AreaPlot.js.map +1 -1
- package/dist/components/charts/BarChart/BarChart.cjs +1 -1
- package/dist/components/charts/BarChart/BarChart.cjs.map +1 -1
- package/dist/components/charts/BarChart/BarChart.d.ts +7 -0
- package/dist/components/charts/BarChart/BarChart.js +151 -120
- package/dist/components/charts/BarChart/BarChart.js.map +1 -1
- package/dist/components/charts/BoxPlot/BoxPlot.cjs +1 -1
- package/dist/components/charts/BoxPlot/BoxPlot.cjs.map +1 -1
- package/dist/components/charts/BoxPlot/BoxPlot.d.ts +4 -0
- package/dist/components/charts/BoxPlot/BoxPlot.js +133 -102
- package/dist/components/charts/BoxPlot/BoxPlot.js.map +1 -1
- package/dist/components/charts/ChartTooltip/lines.cjs.map +1 -1
- package/dist/components/charts/ChartTooltip/lines.d.ts +2 -0
- package/dist/components/charts/ChartTooltip/lines.js.map +1 -1
- package/dist/components/charts/Chromatogram/Chromatogram.cjs +1 -1
- package/dist/components/charts/Chromatogram/Chromatogram.cjs.map +1 -1
- package/dist/components/charts/Chromatogram/Chromatogram.js +111 -114
- package/dist/components/charts/Chromatogram/Chromatogram.js.map +1 -1
- package/dist/components/charts/Chromatogram/plotBuilder.cjs +4 -1
- package/dist/components/charts/Chromatogram/plotBuilder.cjs.map +1 -1
- package/dist/components/charts/Chromatogram/plotBuilder.d.ts +32 -2
- package/dist/components/charts/Chromatogram/plotBuilder.js +170 -127
- package/dist/components/charts/Chromatogram/plotBuilder.js.map +1 -1
- package/dist/components/charts/Chromatogram/regionOverlays.cjs +1 -1
- package/dist/components/charts/Chromatogram/regionOverlays.cjs.map +1 -1
- package/dist/components/charts/Chromatogram/regionOverlays.js +11 -11
- package/dist/components/charts/Chromatogram/regionOverlays.js.map +1 -1
- package/dist/components/charts/Chromatogram/types.d.ts +4 -2
- package/dist/components/charts/Electropherogram/Electropherogram.cjs +1 -1
- package/dist/components/charts/Electropherogram/Electropherogram.cjs.map +1 -1
- package/dist/components/charts/Electropherogram/Electropherogram.js +84 -83
- package/dist/components/charts/Electropherogram/Electropherogram.js.map +1 -1
- package/dist/components/charts/Histogram/Histogram.cjs +1 -1
- package/dist/components/charts/Histogram/Histogram.cjs.map +1 -1
- package/dist/components/charts/Histogram/Histogram.js +42 -42
- package/dist/components/charts/Histogram/Histogram.js.map +1 -1
- package/dist/components/charts/ScatterPlotInteractive/ScatterPlotInteractive.cjs +1 -1
- package/dist/components/charts/ScatterPlotInteractive/ScatterPlotInteractive.cjs.map +1 -1
- package/dist/components/charts/ScatterPlotInteractive/ScatterPlotInteractive.js +4 -5
- package/dist/components/charts/ScatterPlotInteractive/ScatterPlotInteractive.js.map +1 -1
- package/dist/components/charts/chart-scale.cjs +2 -0
- package/dist/components/charts/chart-scale.cjs.map +1 -0
- package/dist/components/charts/chart-scale.d.ts +61 -0
- package/dist/components/charts/chart-scale.js +61 -0
- package/dist/components/charts/chart-scale.js.map +1 -0
- package/dist/index.css +1 -1
- package/dist/index.scoped.css +6 -0
- package/dist/index.tailwind.css +1 -1
- package/dist/ui/skeleton.cjs +1 -1
- package/dist/ui/skeleton.cjs.map +1 -1
- package/dist/ui/skeleton.js +1 -1
- package/dist/ui/skeleton.js.map +1 -1
- package/package.json +8 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Histogram.cjs","sources":["../../../../src/components/charts/Histogram/Histogram.tsx"],"sourcesContent":["import React, { useEffect, useRef, useMemo } from \"react\";\n\nimport { useChartTooltip } from \"../ChartTooltip\";\nimport { getLoadedPlotly, loadPlotly } from \"../plotly-loader\";\n\nimport { useElementSize } from \"@/hooks/use-element-size\";\nimport { CHART_FONT_FAMILY, usePlotlyTheme } from \"@/hooks/use-plotly-theme\";\nimport { cn } from \"@/lib/utils\";\nimport { CHART_COLORS } from \"@/utils/colors\";\nimport \"./Histogram.scss\";\n\n/** Exponent coefficient for normal distribution calculation */\nconst NORMAL_DISTRIBUTION_EXPONENT_COEFF = -0.5;\n\ninterface HistogramDataSeries {\n x: number[];\n name: string;\n color?: string;\n autobinx?: boolean;\n xbins?: {\n start: number;\n end: number;\n size: number;\n };\n opacity?: number;\n showDistributionLine?: boolean;\n lineWidth?: number;\n}\n\ntype HistogramProps = {\n dataSeries: HistogramDataSeries | HistogramDataSeries[];\n /**\n * Fixed width in pixels. When omitted, the chart fills its container and\n * tracks the container's width via a `ResizeObserver`.\n */\n width?: number;\n /**\n * Fixed height in pixels. When omitted, the chart fills its container and\n * tracks the container's height via a `ResizeObserver`.\n */\n height?: number;\n title?: string;\n xTitle?: string;\n yTitle?: string;\n bargap?: number;\n showDistributionLine?: boolean;\n};\n\nconst calculateMean = (data: number[]): number => {\n const sum = data.reduce((acc, val) => acc + val, 0);\n return sum / data.length;\n};\n\nconst calculateStdDev = (data: number[], mean: number): number => {\n const squaredDiffs = data.map((value) => Math.pow(value - mean, 2));\n const variance =\n squaredDiffs.reduce((acc, val) => acc + val, 0) / data.length;\n return Math.sqrt(variance);\n};\n\nconst generateNormalDistributionPoints = (\n mean: number,\n stdDev: number,\n start: number,\n end: number,\n points = 100\n): { x: number[]; y: number[] } => {\n const xValues: number[] = [];\n const yValues: number[] = [];\n\n const step = (end - start) / (points - 1);\n\n for (let i = 0; i < points; i++) {\n const x = start + i * step;\n xValues.push(x);\n\n const exponent = NORMAL_DISTRIBUTION_EXPONENT_COEFF * Math.pow((x - mean) / stdDev, 2);\n const y = (1 / (stdDev * Math.sqrt(2 * Math.PI))) * Math.exp(exponent);\n yValues.push(y);\n }\n\n return { x: xValues, y: yValues };\n};\n\nconst scaleDistributionCurve = (\n yValues: number[],\n histogramData: number[],\n bins: { start: number; end: number; size: number }\n): number[] => {\n const binCount = Math.ceil((bins.end - bins.start) / bins.size);\n const binFrequencies = Array(binCount).fill(0);\n\n histogramData.forEach((value) => {\n if (value >= bins.start && value <= bins.end) {\n const binIndex = Math.floor((value - bins.start) / bins.size);\n binFrequencies[binIndex]++;\n }\n });\n\n const maxBinFrequency = Math.max(...binFrequencies);\n const maxCurveValue = Math.max(...yValues);\n\n const scaleFactor = maxBinFrequency / maxCurveValue;\n\n return yValues.map((y) => y * scaleFactor);\n};\n\nconst Histogram: React.FC<HistogramProps> = ({\n dataSeries,\n width,\n height,\n title = \"Histogram\",\n xTitle = \"X Axis\",\n yTitle = \"Frequency\",\n bargap = 0.2,\n showDistributionLine = false,\n}) => {\n const plotRef = useRef<HTMLDivElement>(null);\n const theme = usePlotlyTheme();\n const { bindTooltip, tooltipElement } = useChartTooltip({ xLabel: xTitle, yLabel: yTitle });\n\n // Omitted width/height → fill the container and track its measured size;\n // explicit pixel values override. Histogram has its own HTML title + legend,\n // so we measure a wrapper around just the Plotly canvas. See AreaPlot for\n // the reference pattern.\n const [plotAreaRef, measured] = useElementSize<HTMLDivElement>();\n const resolvedWidth = width ?? measured.width;\n const resolvedHeight = height ?? measured.height;\n const hasSize = resolvedWidth > 0 && resolvedHeight > 0;\n // Fill is per-dimension: omit width to fill the container width, omit height\n // to fill its height (so e.g. a fixed width with a container-driven height works).\n const fillWidth = width === undefined;\n const fillHeight = height === undefined;\n const sizeRef = useRef({ width: resolvedWidth, height: resolvedHeight });\n sizeRef.current = { width: resolvedWidth, height: resolvedHeight };\n const plotInitedRef = useRef(false);\n // Size last applied to the plot, so the resize effect can skip a redundant\n // relayout right after newPlot already drew at that size.\n const appliedSizeRef = useRef({ width: 0, height: 0 });\n const seriesArray = useMemo(\n () => (Array.isArray(dataSeries) ? dataSeries : [dataSeries]),\n [dataSeries],\n );\n const effectiveBarMode = useMemo<\n \"stack\" | \"group\" | \"overlay\" | \"relative\" | undefined\n >(() => (seriesArray.length > 1 ? \"stack\" : undefined), [seriesArray.length]);\n\n const defaultColors = CHART_COLORS;\n\n const seriesWithColors = useMemo(() => {\n return seriesArray.map((series, index) => {\n const hasDistributionLine =\n typeof series.showDistributionLine === \"undefined\"\n ? showDistributionLine\n : series.showDistributionLine;\n\n return {\n ...series,\n color: series.color || defaultColors[index % defaultColors.length],\n opacity: hasDistributionLine ? 0.5 : series.opacity || 1,\n showDistributionLine: hasDistributionLine,\n lineWidth: series.lineWidth || 3,\n };\n });\n }, [seriesArray, showDistributionLine, defaultColors]);\n\n const gridColor = theme.gridColor;\n\n const histogramData = useMemo(\n () =>\n seriesWithColors.map((series) => ({\n type: \"histogram\" as const,\n x: series.x,\n name: series.name,\n marker: {\n color: series.color,\n line: {\n color: theme.paperBg,\n width: 1,\n },\n opacity: series.opacity,\n },\n autobinx: series.autobinx,\n xbins: series.xbins,\n hoverinfo: \"none\" as const,\n })),\n [seriesWithColors, theme],\n );\n\n const distributionLines = useMemo(\n () =>\n seriesWithColors\n .filter((series) => series.showDistributionLine)\n .map((series) => {\n const mean = calculateMean(series.x);\n const stdDev = calculateStdDev(series.x, mean);\n\n const min = Math.min(...series.x);\n const max = Math.max(...series.x);\n const range = max - min;\n const start = min - range * 0.1;\n const end = max + range * 0.1;\n\n const bins = series.xbins || {\n start: start,\n end: end,\n size: range / 10,\n };\n\n const curvePoints = generateNormalDistributionPoints(\n mean,\n stdDev,\n start,\n end,\n 100,\n );\n\n const scaledYValues = scaleDistributionCurve(\n curvePoints.y,\n series.x,\n bins,\n );\n\n return {\n type: \"scatter\" as const,\n x: curvePoints.x,\n y: scaledYValues,\n mode: \"lines\" as const,\n name: `${series.name} Distribution`,\n line: {\n color: series.color,\n width: series.lineWidth,\n },\n hoverinfo: \"none\" as const,\n };\n }),\n [seriesWithColors],\n );\n\n const plotData = useMemo(\n () => [...histogramData, ...distributionLines],\n [histogramData, distributionLines],\n );\n\n useEffect(() => {\n if (!plotRef.current || !hasSize) return;\n\n const layout = {\n width: sizeRef.current.width,\n height: sizeRef.current.height,\n font: {\n family: CHART_FONT_FAMILY,\n },\n showlegend: false,\n margin: { l: 90, r: 40, b: 80, t: 40 },\n xaxis: {\n title: {\n text: xTitle,\n font: {\n size: 16,\n color: theme.textSecondary,\n family: CHART_FONT_FAMILY,\n weight: 400,\n },\n standoff: 20,\n },\n gridcolor: gridColor,\n tickcolor: theme.tickColor,\n ticklen: 8,\n tickwidth: 1,\n ticks: \"outside\" as const,\n linecolor: theme.lineColor,\n linewidth: 1,\n zeroline: false,\n automargin: true,\n },\n yaxis: {\n title: {\n text: yTitle,\n font: {\n size: 16,\n color: theme.textSecondary,\n family: CHART_FONT_FAMILY,\n weight: 400,\n },\n standoff: 20,\n },\n gridcolor: gridColor,\n tickcolor: theme.tickColor,\n ticklen: 8,\n tickwidth: 1,\n ticks: \"outside\" as const,\n linecolor: theme.lineColor,\n linewidth: 1,\n zeroline: false,\n rangemode: \"tozero\" as const,\n automargin: true,\n },\n barmode: effectiveBarMode,\n bargap: bargap,\n paper_bgcolor: theme.paperBg,\n plot_bgcolor: theme.plotBg,\n };\n\n const config = {\n // Sizing is driven from the measured container; disable Plotly's own\n // window-resize responsiveness (it can't see container resizes).\n responsive: false,\n displayModeBar: false,\n displaylogo: false,\n };\n\n // Plotly is loaded lazily so it stays out of the consumer's main chunk\n // (SW-2007); the draw is skipped if the effect re-runs or unmounts first.\n let cancelled = false;\n let plotElement: HTMLDivElement | null = null;\n void loadPlotly().then((plotly) => {\n if (cancelled || !plotRef.current) return;\n plotly.newPlot(plotRef.current, plotData, layout, config);\n bindTooltip(plotRef.current);\n\n // Capture ref value for cleanup\n plotElement = plotRef.current;\n plotInitedRef.current = true;\n appliedSizeRef.current = { ...sizeRef.current };\n });\n\n return () => {\n cancelled = true;\n if (plotElement) {\n getLoadedPlotly().purge(plotElement);\n plotInitedRef.current = false;\n }\n };\n }, [hasSize, xTitle, yTitle, bargap, plotData, effectiveBarMode, gridColor, theme, bindTooltip]);\n\n // Resize in place when the measured/overridden size changes — cheaper than\n // recreating the plot, and it preserves tooltip/event bindings.\n useEffect(() => {\n const plotElement = plotRef.current;\n if (!plotElement || !plotInitedRef.current || resolvedWidth <= 0 || resolvedHeight <= 0) {\n return;\n }\n // newPlot already drew at the current size; skip the redundant relayout\n // (it would queue an automargin redraw that can reject if we unmount first).\n if (\n appliedSizeRef.current.width === resolvedWidth &&\n appliedSizeRef.current.height === resolvedHeight\n ) {\n return;\n }\n appliedSizeRef.current = { width: resolvedWidth, height: resolvedHeight };\n // Swallow rejections from a relayout that races an unmount/purge.\n // plotInitedRef guarantees Plotly finished loading, so sync access is safe.\n void getLoadedPlotly()\n .relayout(plotElement, { width: resolvedWidth, height: resolvedHeight })\n .catch(() => {});\n }, [resolvedWidth, resolvedHeight]);\n\n const ChartLegend: React.FC<{\n series: Array<{ name: string; color: string }>;\n }> = ({ series }) => {\n const items = series.map((item, i) => (\n <React.Fragment key={item.name}>\n <div className=\"legend-item\">\n <span className=\"color-box\" style={{ background: item.color }} />\n {item.name}\n {i < series.length - 1 && <span className=\"divider\" />}\n </div>\n </React.Fragment>\n ));\n\n const rows = [];\n const rowSize = 6;\n for (let i = 0; i < items.length; i += rowSize) {\n rows.push(\n <div className=\"legend-row\" key={i}>\n {items.slice(i, i + rowSize)}\n </div>\n );\n }\n\n return <div className=\"legend-container\">{rows}</div>;\n };\n\n return (\n <div\n className={cn(\"histogram-container relative\", fillWidth && \"w-full\", fillHeight && \"h-full\")}\n style={width === undefined ? undefined : { width }}\n >\n <div className={cn(\"chart-container\", fillHeight && \"flex h-full flex-col\")}>\n {title && (\n <div className=\"title-container\">\n <h2 className=\"title\">{title}</h2>\n </div>\n )}\n {/* Measured plot area — flexes to fill the space left by the title and\n legend in fill mode, so the Plotly canvas tracks it. */}\n <div ref={plotAreaRef} className={cn(fillHeight && \"min-h-0 flex-1\")}>\n <div\n ref={plotRef}\n style={{\n width: \"100%\",\n height: \"100%\",\n margin: \"0\",\n }}\n />\n </div>\n <ChartLegend series={seriesWithColors} />\n </div>\n {tooltipElement}\n </div>\n );\n};\n\nexport { Histogram };\nexport type { HistogramDataSeries, HistogramProps };\n"],"names":["NORMAL_DISTRIBUTION_EXPONENT_COEFF","calculateMean","data","acc","val","calculateStdDev","mean","variance","value","generateNormalDistributionPoints","stdDev","start","end","points","xValues","yValues","step","i","x","exponent","y","scaleDistributionCurve","histogramData","bins","binCount","binFrequencies","binIndex","maxBinFrequency","maxCurveValue","scaleFactor","Histogram","dataSeries","width","height","title","xTitle","yTitle","bargap","showDistributionLine","plotRef","useRef","theme","usePlotlyTheme","bindTooltip","tooltipElement","useChartTooltip","plotAreaRef","measured","useElementSize","resolvedWidth","resolvedHeight","hasSize","fillWidth","fillHeight","sizeRef","plotInitedRef","appliedSizeRef","seriesArray","useMemo","effectiveBarMode","defaultColors","CHART_COLORS","seriesWithColors","series","index","hasDistributionLine","gridColor","distributionLines","min","max","range","curvePoints","scaledYValues","plotData","useEffect","layout","CHART_FONT_FAMILY","config","cancelled","plotElement","loadPlotly","plotly","getLoadedPlotly","ChartLegend","items","item","jsx","React","jsxs","rows","rowSize","cn"],"mappings":"qaAYA,MAAMA,EAAqC,IAoCrCC,EAAiBC,GACTA,EAAK,OAAO,CAACC,EAAKC,IAAQD,EAAMC,EAAK,CAAC,EACrCF,EAAK,OAGdG,EAAkB,CAACH,EAAgBI,IAAyB,CAEhE,MAAMC,EADeL,EAAK,IAAKM,GAAU,KAAK,IAAIA,EAAQF,EAAM,CAAC,CAAC,EAEnD,OAAO,CAACH,EAAKC,IAAQD,EAAMC,EAAK,CAAC,EAAIF,EAAK,OACzD,OAAO,KAAK,KAAKK,CAAQ,CAC3B,EAEME,EAAmC,CACvCH,EACAI,EACAC,EACAC,EACAC,EAAS,MACwB,CACjC,MAAMC,EAAoB,CAAA,EACpBC,EAAoB,CAAA,EAEpBC,GAAQJ,EAAMD,IAAUE,EAAS,GAEvC,QAASI,EAAI,EAAGA,EAA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gBAAgB,EACjE,SAAAiC,EAAAA,IAAC,MAAA,CACC,IAAK/C,EACL,MAAO,CACL,MAAO,OACP,OAAQ,OACR,OAAQ,GAAA,CACV,CAAA,EAEJ,EACA+C,EAAAA,IAACH,EAAA,CAAY,OAAQrB,CAAA,CAAkB,CAAA,EACzC,EACClB,CAAA,CAAA,CAAA,CAGP"}
|
|
1
|
+
{"version":3,"file":"Histogram.cjs","sources":["../../../../src/components/charts/Histogram/Histogram.tsx"],"sourcesContent":["import React, { useEffect, useRef, useMemo } from \"react\";\n\nimport { useChartTooltip } from \"../ChartTooltip\";\nimport { getLoadedPlotly, loadPlotly } from \"../plotly-loader\";\n\nimport { useElementSize } from \"@/hooks/use-element-size\";\nimport { CHART_FONT_FAMILY, usePlotlyTheme } from \"@/hooks/use-plotly-theme\";\nimport { cn } from \"@/lib/utils\";\nimport { CHART_COLORS } from \"@/utils/colors\";\nimport \"./Histogram.scss\";\n\n/** Exponent coefficient for normal distribution calculation */\nconst NORMAL_DISTRIBUTION_EXPONENT_COEFF = -0.5;\n\ninterface HistogramDataSeries {\n x: number[];\n name: string;\n color?: string;\n autobinx?: boolean;\n xbins?: {\n start: number;\n end: number;\n size: number;\n };\n opacity?: number;\n showDistributionLine?: boolean;\n lineWidth?: number;\n}\n\ntype HistogramProps = {\n dataSeries: HistogramDataSeries | HistogramDataSeries[];\n /**\n * Fixed width in pixels. When omitted, the chart fills its container and\n * tracks the container's width via a `ResizeObserver`.\n */\n width?: number;\n /**\n * Fixed height in pixels. When omitted, the chart fills its container and\n * tracks the container's height via a `ResizeObserver`.\n */\n height?: number;\n title?: string;\n xTitle?: string;\n yTitle?: string;\n bargap?: number;\n showDistributionLine?: boolean;\n};\n\nconst calculateMean = (data: number[]): number => {\n const sum = data.reduce((acc, val) => acc + val, 0);\n return sum / data.length;\n};\n\nconst calculateStdDev = (data: number[], mean: number): number => {\n const squaredDiffs = data.map((value) => Math.pow(value - mean, 2));\n const variance =\n squaredDiffs.reduce((acc, val) => acc + val, 0) / data.length;\n return Math.sqrt(variance);\n};\n\nconst generateNormalDistributionPoints = (\n mean: number,\n stdDev: number,\n start: number,\n end: number,\n points = 100\n): { x: number[]; y: number[] } => {\n const xValues: number[] = [];\n const yValues: number[] = [];\n\n const step = (end - start) / (points - 1);\n\n for (let i = 0; i < points; i++) {\n const x = start + i * step;\n xValues.push(x);\n\n const exponent = NORMAL_DISTRIBUTION_EXPONENT_COEFF * Math.pow((x - mean) / stdDev, 2);\n const y = (1 / (stdDev * Math.sqrt(2 * Math.PI))) * Math.exp(exponent);\n yValues.push(y);\n }\n\n return { x: xValues, y: yValues };\n};\n\nconst scaleDistributionCurve = (\n yValues: number[],\n histogramData: number[],\n bins: { start: number; end: number; size: number }\n): number[] => {\n const binCount = Math.ceil((bins.end - bins.start) / bins.size);\n const binFrequencies = Array(binCount).fill(0);\n\n histogramData.forEach((value) => {\n if (value >= bins.start && value <= bins.end) {\n const binIndex = Math.floor((value - bins.start) / bins.size);\n binFrequencies[binIndex]++;\n }\n });\n\n const maxBinFrequency = Math.max(...binFrequencies);\n const maxCurveValue = Math.max(...yValues);\n\n const scaleFactor = maxBinFrequency / maxCurveValue;\n\n return yValues.map((y) => y * scaleFactor);\n};\n\nconst Histogram: React.FC<HistogramProps> = ({\n dataSeries,\n width,\n height,\n title = \"Histogram\",\n xTitle = \"X Axis\",\n yTitle = \"Frequency\",\n bargap = 0.2,\n showDistributionLine = false,\n}) => {\n const plotRef = useRef<HTMLDivElement>(null);\n const theme = usePlotlyTheme();\n const { bindTooltip, tooltipElement } = useChartTooltip({ xLabel: xTitle, yLabel: yTitle });\n\n // Omitted width/height → fill the container and track its measured size;\n // explicit pixel values override. Histogram has its own HTML title + legend,\n // so we measure a wrapper around just the Plotly canvas. See AreaPlot for\n // the reference pattern.\n const [plotAreaRef, measured] = useElementSize<HTMLDivElement>();\n const resolvedWidth = width ?? measured.width;\n const resolvedHeight = height ?? measured.height;\n const hasSize = resolvedWidth > 0 && resolvedHeight > 0;\n // Fill is per-dimension: omit width to fill the container width, omit height\n // to fill its height (so e.g. a fixed width with a container-driven height works).\n const fillWidth = width === undefined;\n const fillHeight = height === undefined;\n const sizeRef = useRef({ width: resolvedWidth, height: resolvedHeight });\n sizeRef.current = { width: resolvedWidth, height: resolvedHeight };\n const plotInitedRef = useRef(false);\n // Size last applied to the plot, so the resize effect can skip a redundant\n // relayout right after newPlot already drew at that size.\n const appliedSizeRef = useRef({ width: 0, height: 0 });\n const seriesArray = useMemo(\n () => (Array.isArray(dataSeries) ? dataSeries : [dataSeries]),\n [dataSeries],\n );\n const effectiveBarMode = useMemo<\n \"stack\" | \"group\" | \"overlay\" | \"relative\" | undefined\n >(() => (seriesArray.length > 1 ? \"stack\" : undefined), [seriesArray.length]);\n\n const defaultColors = CHART_COLORS;\n\n const seriesWithColors = useMemo(() => {\n return seriesArray.map((series, index) => {\n const hasDistributionLine =\n typeof series.showDistributionLine === \"undefined\"\n ? showDistributionLine\n : series.showDistributionLine;\n\n return {\n ...series,\n color: series.color || defaultColors[index % defaultColors.length],\n opacity: hasDistributionLine ? 0.5 : series.opacity || 1,\n showDistributionLine: hasDistributionLine,\n lineWidth: series.lineWidth || 3,\n };\n });\n }, [seriesArray, showDistributionLine, defaultColors]);\n\n const gridColor = theme.gridColor;\n\n const histogramData = useMemo(\n () =>\n seriesWithColors.map((series) => ({\n type: \"histogram\" as const,\n x: series.x,\n name: series.name,\n marker: {\n color: series.color,\n line: {\n color: theme.paperBg,\n width: 1,\n },\n opacity: series.opacity,\n },\n autobinx: series.autobinx,\n xbins: series.xbins,\n hoverinfo: \"none\" as const,\n })),\n [seriesWithColors, theme],\n );\n\n const distributionLines = useMemo(\n () =>\n seriesWithColors\n .filter((series) => series.showDistributionLine)\n .map((series) => {\n const mean = calculateMean(series.x);\n const stdDev = calculateStdDev(series.x, mean);\n\n const min = Math.min(...series.x);\n const max = Math.max(...series.x);\n const range = max - min;\n const start = min - range * 0.1;\n const end = max + range * 0.1;\n\n const bins = series.xbins || {\n start: start,\n end: end,\n size: range / 10,\n };\n\n const curvePoints = generateNormalDistributionPoints(\n mean,\n stdDev,\n start,\n end,\n 100,\n );\n\n const scaledYValues = scaleDistributionCurve(\n curvePoints.y,\n series.x,\n bins,\n );\n\n return {\n type: \"scatter\" as const,\n x: curvePoints.x,\n y: scaledYValues,\n mode: \"lines\" as const,\n name: `${series.name} Distribution`,\n line: {\n color: series.color,\n width: series.lineWidth,\n },\n hoverinfo: \"none\" as const,\n };\n }),\n [seriesWithColors],\n );\n\n const plotData = useMemo(\n () => [...histogramData, ...distributionLines],\n [histogramData, distributionLines],\n );\n\n useEffect(() => {\n if (!plotRef.current || !hasSize) return;\n\n const layout = {\n width: sizeRef.current.width,\n height: sizeRef.current.height,\n font: {\n family: CHART_FONT_FAMILY,\n },\n showlegend: false,\n margin: { l: 90, r: 40, b: 80, t: 40 },\n xaxis: {\n title: {\n text: xTitle,\n font: {\n size: 16,\n color: theme.textSecondary,\n family: CHART_FONT_FAMILY,\n weight: 400,\n },\n standoff: 20,\n },\n gridcolor: gridColor,\n tickcolor: theme.tickColor,\n ticklen: 8,\n tickwidth: 1,\n ticks: \"outside\" as const,\n linecolor: theme.lineColor,\n linewidth: 1,\n zeroline: false,\n automargin: true,\n },\n yaxis: {\n title: {\n text: yTitle,\n font: {\n size: 16,\n color: theme.textSecondary,\n family: CHART_FONT_FAMILY,\n weight: 400,\n },\n standoff: 20,\n },\n gridcolor: gridColor,\n tickcolor: theme.tickColor,\n ticklen: 8,\n tickwidth: 1,\n ticks: \"outside\" as const,\n linecolor: theme.lineColor,\n linewidth: 1,\n zeroline: false,\n rangemode: \"tozero\" as const,\n automargin: true,\n },\n barmode: effectiveBarMode,\n bargap: bargap,\n paper_bgcolor: theme.paperBg,\n plot_bgcolor: theme.plotBg,\n };\n\n const config = {\n // Sizing is driven from the measured container; disable Plotly's own\n // window-resize responsiveness (it can't see container resizes).\n responsive: false,\n displayModeBar: false,\n displaylogo: false,\n };\n\n // Plotly is loaded lazily so it stays out of the consumer's main chunk\n // (SW-2007); the draw is skipped if the effect re-runs or unmounts first.\n let cancelled = false;\n let plotElement: HTMLDivElement | null = null;\n void loadPlotly().then((plotly) => {\n if (cancelled || !plotRef.current) return;\n plotly.newPlot(plotRef.current, plotData, layout, config);\n bindTooltip(plotRef.current);\n\n // Capture ref value for cleanup\n plotElement = plotRef.current;\n plotInitedRef.current = true;\n appliedSizeRef.current = { ...sizeRef.current };\n });\n\n return () => {\n cancelled = true;\n if (plotElement) {\n getLoadedPlotly().purge(plotElement);\n plotInitedRef.current = false;\n }\n };\n }, [hasSize, xTitle, yTitle, bargap, plotData, effectiveBarMode, gridColor, theme, bindTooltip]);\n\n // Resize in place when the measured/overridden size changes — cheaper than\n // recreating the plot, and it preserves tooltip/event bindings.\n useEffect(() => {\n const plotElement = plotRef.current;\n if (!plotElement || !plotInitedRef.current || resolvedWidth <= 0 || resolvedHeight <= 0) {\n return;\n }\n // newPlot already drew at the current size; skip the redundant relayout\n // (it would queue an automargin redraw that can reject if we unmount first).\n if (\n appliedSizeRef.current.width === resolvedWidth &&\n appliedSizeRef.current.height === resolvedHeight\n ) {\n return;\n }\n appliedSizeRef.current = { width: resolvedWidth, height: resolvedHeight };\n // Swallow rejections from a relayout that races an unmount/purge.\n // plotInitedRef guarantees Plotly finished loading, so sync access is safe.\n void getLoadedPlotly()\n .relayout(plotElement, { width: resolvedWidth, height: resolvedHeight })\n .catch(() => {});\n }, [resolvedWidth, resolvedHeight]);\n\n const ChartLegend: React.FC<{\n series: Array<{ name: string; color: string }>;\n }> = ({ series }) => {\n const items = series.map((item, i) => (\n <React.Fragment key={item.name}>\n <div className=\"histogram-legend-item\">\n <span className=\"histogram-legend-swatch\" style={{ background: item.color }} />\n {item.name}\n {i < series.length - 1 && <span className=\"histogram-legend-divider\" />}\n </div>\n </React.Fragment>\n ));\n\n const rows = [];\n const rowSize = 6;\n for (let i = 0; i < items.length; i += rowSize) {\n rows.push(\n <div className=\"histogram-legend-row\" key={i}>\n {items.slice(i, i + rowSize)}\n </div>\n );\n }\n\n return <div className=\"histogram-legend\">{rows}</div>;\n };\n\n return (\n <div\n className={cn(\"histogram-container relative\", fillWidth && \"w-full\", fillHeight && \"h-full\")}\n style={width === undefined ? undefined : { width }}\n >\n <div className={cn(\"histogram-chart\", fillHeight && \"flex h-full flex-col\")}>\n {title && (\n <div className=\"histogram-title-container\">\n <h2 className=\"histogram-title\">{title}</h2>\n </div>\n )}\n {/* Measured plot area — flexes to fill the space left by the title and\n legend in fill mode, so the Plotly canvas tracks it. */}\n <div ref={plotAreaRef} className={cn(fillHeight && \"min-h-0 flex-1\")}>\n <div\n ref={plotRef}\n style={{\n width: \"100%\",\n height: \"100%\",\n margin: \"0\",\n }}\n />\n </div>\n <ChartLegend series={seriesWithColors} />\n </div>\n {tooltipElement}\n </div>\n );\n};\n\nexport { Histogram };\nexport type { HistogramDataSeries, HistogramProps };\n"],"names":["NORMAL_DISTRIBUTION_EXPONENT_COEFF","calculateMean","data","acc","val","calculateStdDev","mean","variance","value","generateNormalDistributionPoints","stdDev","start","end","points","xValues","yValues","step","i","x","exponent","y","scaleDistributionCurve","histogramData","bins","binCount","binFrequencies","binIndex","maxBinFrequency","maxCurveValue","scaleFactor","Histogram","dataSeries","width","height","title","xTitle","yTitle","bargap","showDistributionLine","plotRef","useRef","theme","usePlotlyTheme","bindTooltip","tooltipElement","useChartTooltip","plotAreaRef","measured","useElementSize","resolvedWidth","resolvedHeight","hasSize","fillWidth","fillHeight","sizeRef","plotInitedRef","appliedSizeRef","seriesArray","useMemo","effectiveBarMode","defaultColors","CHART_COLORS","seriesWithColors","series","index","hasDistributionLine","gridColor","distributionLines","min","max","range","curvePoints","scaledYValues","plotData","useEffect","layout","CHART_FONT_FAMILY","config","cancelled","plotElement","loadPlotly","plotly","getLoadedPlotly","ChartLegend","items","item","jsx","React","jsxs","rows","rowSize","cn"],"mappings":"qaAYA,MAAMA,EAAqC,IAoCrCC,EAAiBC,GACTA,EAAK,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AAI,UAAU,mBAAoB,SAAAG,EAAK,CACjD,EAEA,OACED,EAAAA,KAAC,MAAA,CACC,UAAWG,EAAAA,GAAG,+BAAgCvC,GAAa,SAAUC,GAAc,QAAQ,EAC3F,MAAOrB,IAAU,OAAY,OAAY,CAAE,MAAAA,CAAA,EAE3C,SAAA,CAAAwD,OAAC,OAAI,UAAWG,EAAAA,GAAG,kBAAmBtC,GAAc,sBAAsB,EACvE,SAAA,CAAAnB,GACCoD,EAAAA,IAAC,OAAI,UAAU,4BACb,eAAC,KAAA,CAAG,UAAU,kBAAmB,SAAApD,CAAA,CAAM,CAAA,CACzC,EAIFoD,EAAAA,IAAC,OAAI,IAAKxC,EAAa,UAAW6C,EAAAA,GAAGtC,GAAc,gBAAgB,EACjE,SAAAiC,EAAAA,IAAC,MAAA,CACC,IAAK/C,EACL,MAAO,CACL,MAAO,OACP,OAAQ,OACR,OAAQ,GAAA,CACV,CAAA,EAEJ,EACA+C,EAAAA,IAACH,EAAA,CAAY,OAAQrB,CAAA,CAAkB,CAAA,EACzC,EACClB,CAAA,CAAA,CAAA,CAGP"}
|
|
@@ -7,44 +7,44 @@ import { usePlotlyTheme as tt, CHART_FONT_FAMILY as E } from "../../../hooks/use
|
|
|
7
7
|
import { cn as F } from "../../../lib/utils.js";
|
|
8
8
|
import { CHART_COLORS as ot } from "../../../utils/colors.js";
|
|
9
9
|
/* empty css */
|
|
10
|
-
const et = -0.5, nt = (r) => r.reduce((n, a) => n + a, 0) / r.length, rt = (r,
|
|
11
|
-
const a = r.map((
|
|
10
|
+
const et = -0.5, nt = (r) => r.reduce((n, a) => n + a, 0) / r.length, rt = (r, c) => {
|
|
11
|
+
const a = r.map((l) => Math.pow(l - c, 2)).reduce((l, s) => l + s, 0) / r.length;
|
|
12
12
|
return Math.sqrt(a);
|
|
13
|
-
}, it = (r,
|
|
14
|
-
const s = [],
|
|
15
|
-
for (let o = 0; o <
|
|
13
|
+
}, it = (r, c, n, a, l = 100) => {
|
|
14
|
+
const s = [], p = [], x = (a - n) / (l - 1);
|
|
15
|
+
for (let o = 0; o < l; o++) {
|
|
16
16
|
const e = n + o * x;
|
|
17
17
|
s.push(e);
|
|
18
|
-
const b = et * Math.pow((e - r) /
|
|
19
|
-
|
|
18
|
+
const b = et * Math.pow((e - r) / c, 2), z = 1 / (c * Math.sqrt(2 * Math.PI)) * Math.exp(b);
|
|
19
|
+
p.push(z);
|
|
20
20
|
}
|
|
21
|
-
return { x: s, y:
|
|
22
|
-
},
|
|
23
|
-
const a = Math.ceil((n.end - n.start) / n.size),
|
|
24
|
-
|
|
21
|
+
return { x: s, y: p };
|
|
22
|
+
}, lt = (r, c, n) => {
|
|
23
|
+
const a = Math.ceil((n.end - n.start) / n.size), l = Array(a).fill(0);
|
|
24
|
+
c.forEach((o) => {
|
|
25
25
|
if (o >= n.start && o <= n.end) {
|
|
26
26
|
const e = Math.floor((o - n.start) / n.size);
|
|
27
|
-
|
|
27
|
+
l[e]++;
|
|
28
28
|
}
|
|
29
29
|
});
|
|
30
|
-
const s = Math.max(...
|
|
30
|
+
const s = Math.max(...l), p = Math.max(...r), x = s / p;
|
|
31
31
|
return r.map((o) => o * x);
|
|
32
|
-
},
|
|
32
|
+
}, pt = ({
|
|
33
33
|
dataSeries: r,
|
|
34
|
-
width:
|
|
34
|
+
width: c,
|
|
35
35
|
height: n,
|
|
36
36
|
title: a = "Histogram",
|
|
37
|
-
xTitle:
|
|
37
|
+
xTitle: l = "X Axis",
|
|
38
38
|
yTitle: s = "Frequency",
|
|
39
|
-
bargap:
|
|
39
|
+
bargap: p = 0.2,
|
|
40
40
|
showDistributionLine: x = !1
|
|
41
41
|
}) => {
|
|
42
|
-
const o = k(null), e = tt(), { bindTooltip: b, tooltipElement: z } = K({ xLabel:
|
|
43
|
-
M.current = { width: f, height:
|
|
42
|
+
const o = k(null), e = tt(), { bindTooltip: b, tooltipElement: z } = K({ xLabel: l, yLabel: s }), [X, P] = Z(), f = c ?? P.width, g = n ?? P.height, q = f > 0 && g > 0, Y = c === void 0, D = n === void 0, M = k({ width: f, height: g });
|
|
43
|
+
M.current = { width: f, height: g };
|
|
44
44
|
const L = k(!1), C = k({ width: 0, height: 0 }), N = y(
|
|
45
45
|
() => Array.isArray(r) ? r : [r],
|
|
46
46
|
[r]
|
|
47
|
-
), B = y(() => N.length > 1 ? "stack" : void 0, [N.length]), R = ot,
|
|
47
|
+
), B = y(() => N.length > 1 ? "stack" : void 0, [N.length]), R = ot, w = y(() => N.map((t, u) => {
|
|
48
48
|
const h = typeof t.showDistributionLine > "u" ? x : t.showDistributionLine;
|
|
49
49
|
return {
|
|
50
50
|
...t,
|
|
@@ -54,7 +54,7 @@ const et = -0.5, nt = (r) => r.reduce((n, a) => n + a, 0) / r.length, rt = (r, l
|
|
|
54
54
|
lineWidth: t.lineWidth || 3
|
|
55
55
|
};
|
|
56
56
|
}), [N, x, R]), A = e.gridColor, I = y(
|
|
57
|
-
() =>
|
|
57
|
+
() => w.map((t) => ({
|
|
58
58
|
type: "histogram",
|
|
59
59
|
x: t.x,
|
|
60
60
|
name: t.name,
|
|
@@ -70,20 +70,20 @@ const et = -0.5, nt = (r) => r.reduce((n, a) => n + a, 0) / r.length, rt = (r, l
|
|
|
70
70
|
xbins: t.xbins,
|
|
71
71
|
hoverinfo: "none"
|
|
72
72
|
})),
|
|
73
|
-
[
|
|
73
|
+
[w, e]
|
|
74
74
|
), O = y(
|
|
75
|
-
() =>
|
|
76
|
-
const u = nt(t.x), h = rt(t.x, u), m = Math.min(...t.x), i = Math.max(...t.x),
|
|
75
|
+
() => w.filter((t) => t.showDistributionLine).map((t) => {
|
|
76
|
+
const u = nt(t.x), h = rt(t.x, u), m = Math.min(...t.x), i = Math.max(...t.x), v = i - m, S = m - v * 0.1, W = i + v * 0.1, $ = t.xbins || {
|
|
77
77
|
start: S,
|
|
78
78
|
end: W,
|
|
79
|
-
size:
|
|
79
|
+
size: v / 10
|
|
80
80
|
}, T = it(
|
|
81
81
|
u,
|
|
82
82
|
h,
|
|
83
83
|
S,
|
|
84
84
|
W,
|
|
85
85
|
100
|
|
86
|
-
), G =
|
|
86
|
+
), G = lt(
|
|
87
87
|
T.y,
|
|
88
88
|
t.x,
|
|
89
89
|
$
|
|
@@ -101,7 +101,7 @@ const et = -0.5, nt = (r) => r.reduce((n, a) => n + a, 0) / r.length, rt = (r, l
|
|
|
101
101
|
hoverinfo: "none"
|
|
102
102
|
};
|
|
103
103
|
}),
|
|
104
|
-
[
|
|
104
|
+
[w]
|
|
105
105
|
), H = y(
|
|
106
106
|
() => [...I, ...O],
|
|
107
107
|
[I, O]
|
|
@@ -118,7 +118,7 @@ const et = -0.5, nt = (r) => r.reduce((n, a) => n + a, 0) / r.length, rt = (r, l
|
|
|
118
118
|
margin: { l: 90, r: 40, b: 80, t: 40 },
|
|
119
119
|
xaxis: {
|
|
120
120
|
title: {
|
|
121
|
-
text:
|
|
121
|
+
text: l,
|
|
122
122
|
font: {
|
|
123
123
|
size: 16,
|
|
124
124
|
color: e.textSecondary,
|
|
@@ -160,7 +160,7 @@ const et = -0.5, nt = (r) => r.reduce((n, a) => n + a, 0) / r.length, rt = (r, l
|
|
|
160
160
|
automargin: !0
|
|
161
161
|
},
|
|
162
162
|
barmode: B,
|
|
163
|
-
bargap:
|
|
163
|
+
bargap: p,
|
|
164
164
|
paper_bgcolor: e.paperBg,
|
|
165
165
|
plot_bgcolor: e.plotBg
|
|
166
166
|
}, u = {
|
|
@@ -176,31 +176,31 @@ const et = -0.5, nt = (r) => r.reduce((n, a) => n + a, 0) / r.length, rt = (r, l
|
|
|
176
176
|
}), () => {
|
|
177
177
|
h = !0, m && (j().purge(m), L.current = !1);
|
|
178
178
|
};
|
|
179
|
-
}, [q,
|
|
179
|
+
}, [q, l, s, p, H, B, A, e, b]), V(() => {
|
|
180
180
|
const t = o.current;
|
|
181
|
-
!t || !L.current || f <= 0 ||
|
|
181
|
+
!t || !L.current || f <= 0 || g <= 0 || C.current.width === f && C.current.height === g || (C.current = { width: f, height: g }, j().relayout(t, { width: f, height: g }).catch(() => {
|
|
182
182
|
}));
|
|
183
|
-
}, [f,
|
|
183
|
+
}, [f, g]);
|
|
184
184
|
const U = ({ series: t }) => {
|
|
185
|
-
const u = t.map((i,
|
|
186
|
-
/* @__PURE__ */ d("span", { className: "
|
|
185
|
+
const u = t.map((i, v) => /* @__PURE__ */ d(J.Fragment, { children: /* @__PURE__ */ _("div", { className: "histogram-legend-item", children: [
|
|
186
|
+
/* @__PURE__ */ d("span", { className: "histogram-legend-swatch", style: { background: i.color } }),
|
|
187
187
|
i.name,
|
|
188
|
-
|
|
188
|
+
v < t.length - 1 && /* @__PURE__ */ d("span", { className: "histogram-legend-divider" })
|
|
189
189
|
] }) }, i.name)), h = [], m = 6;
|
|
190
190
|
for (let i = 0; i < u.length; i += m)
|
|
191
191
|
h.push(
|
|
192
|
-
/* @__PURE__ */ d("div", { className: "legend-row", children: u.slice(i, i + m) }, i)
|
|
192
|
+
/* @__PURE__ */ d("div", { className: "histogram-legend-row", children: u.slice(i, i + m) }, i)
|
|
193
193
|
);
|
|
194
|
-
return /* @__PURE__ */ d("div", { className: "legend
|
|
194
|
+
return /* @__PURE__ */ d("div", { className: "histogram-legend", children: h });
|
|
195
195
|
};
|
|
196
196
|
return /* @__PURE__ */ _(
|
|
197
197
|
"div",
|
|
198
198
|
{
|
|
199
199
|
className: F("histogram-container relative", Y && "w-full", D && "h-full"),
|
|
200
|
-
style:
|
|
200
|
+
style: c === void 0 ? void 0 : { width: c },
|
|
201
201
|
children: [
|
|
202
|
-
/* @__PURE__ */ _("div", { className: F("chart
|
|
203
|
-
a && /* @__PURE__ */ d("div", { className: "title-container", children: /* @__PURE__ */ d("h2", { className: "title", children: a }) }),
|
|
202
|
+
/* @__PURE__ */ _("div", { className: F("histogram-chart", D && "flex h-full flex-col"), children: [
|
|
203
|
+
a && /* @__PURE__ */ d("div", { className: "histogram-title-container", children: /* @__PURE__ */ d("h2", { className: "histogram-title", children: a }) }),
|
|
204
204
|
/* @__PURE__ */ d("div", { ref: X, className: F(D && "min-h-0 flex-1"), children: /* @__PURE__ */ d(
|
|
205
205
|
"div",
|
|
206
206
|
{
|
|
@@ -212,7 +212,7 @@ const et = -0.5, nt = (r) => r.reduce((n, a) => n + a, 0) / r.length, rt = (r, l
|
|
|
212
212
|
}
|
|
213
213
|
}
|
|
214
214
|
) }),
|
|
215
|
-
/* @__PURE__ */ d(U, { series:
|
|
215
|
+
/* @__PURE__ */ d(U, { series: w })
|
|
216
216
|
] }),
|
|
217
217
|
z
|
|
218
218
|
]
|
|
@@ -220,6 +220,6 @@ const et = -0.5, nt = (r) => r.reduce((n, a) => n + a, 0) / r.length, rt = (r, l
|
|
|
220
220
|
);
|
|
221
221
|
};
|
|
222
222
|
export {
|
|
223
|
-
|
|
223
|
+
pt as Histogram
|
|
224
224
|
};
|
|
225
225
|
//# sourceMappingURL=Histogram.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Histogram.js","sources":["../../../../src/components/charts/Histogram/Histogram.tsx"],"sourcesContent":["import React, { useEffect, useRef, useMemo } from \"react\";\n\nimport { useChartTooltip } from \"../ChartTooltip\";\nimport { getLoadedPlotly, loadPlotly } from \"../plotly-loader\";\n\nimport { useElementSize } from \"@/hooks/use-element-size\";\nimport { CHART_FONT_FAMILY, usePlotlyTheme } from \"@/hooks/use-plotly-theme\";\nimport { cn } from \"@/lib/utils\";\nimport { CHART_COLORS } from \"@/utils/colors\";\nimport \"./Histogram.scss\";\n\n/** Exponent coefficient for normal distribution calculation */\nconst NORMAL_DISTRIBUTION_EXPONENT_COEFF = -0.5;\n\ninterface HistogramDataSeries {\n x: number[];\n name: string;\n color?: string;\n autobinx?: boolean;\n xbins?: {\n start: number;\n end: number;\n size: number;\n };\n opacity?: number;\n showDistributionLine?: boolean;\n lineWidth?: number;\n}\n\ntype HistogramProps = {\n dataSeries: HistogramDataSeries | HistogramDataSeries[];\n /**\n * Fixed width in pixels. When omitted, the chart fills its container and\n * tracks the container's width via a `ResizeObserver`.\n */\n width?: number;\n /**\n * Fixed height in pixels. When omitted, the chart fills its container and\n * tracks the container's height via a `ResizeObserver`.\n */\n height?: number;\n title?: string;\n xTitle?: string;\n yTitle?: string;\n bargap?: number;\n showDistributionLine?: boolean;\n};\n\nconst calculateMean = (data: number[]): number => {\n const sum = data.reduce((acc, val) => acc + val, 0);\n return sum / data.length;\n};\n\nconst calculateStdDev = (data: number[], mean: number): number => {\n const squaredDiffs = data.map((value) => Math.pow(value - mean, 2));\n const variance =\n squaredDiffs.reduce((acc, val) => acc + val, 0) / data.length;\n return Math.sqrt(variance);\n};\n\nconst generateNormalDistributionPoints = (\n mean: number,\n stdDev: number,\n start: number,\n end: number,\n points = 100\n): { x: number[]; y: number[] } => {\n const xValues: number[] = [];\n const yValues: number[] = [];\n\n const step = (end - start) / (points - 1);\n\n for (let i = 0; i < points; i++) {\n const x = start + i * step;\n xValues.push(x);\n\n const exponent = NORMAL_DISTRIBUTION_EXPONENT_COEFF * Math.pow((x - mean) / stdDev, 2);\n const y = (1 / (stdDev * Math.sqrt(2 * Math.PI))) * Math.exp(exponent);\n yValues.push(y);\n }\n\n return { x: xValues, y: yValues };\n};\n\nconst scaleDistributionCurve = (\n yValues: number[],\n histogramData: number[],\n bins: { start: number; end: number; size: number }\n): number[] => {\n const binCount = Math.ceil((bins.end - bins.start) / bins.size);\n const binFrequencies = Array(binCount).fill(0);\n\n histogramData.forEach((value) => {\n if (value >= bins.start && value <= bins.end) {\n const binIndex = Math.floor((value - bins.start) / bins.size);\n binFrequencies[binIndex]++;\n }\n });\n\n const maxBinFrequency = Math.max(...binFrequencies);\n const maxCurveValue = Math.max(...yValues);\n\n const scaleFactor = maxBinFrequency / maxCurveValue;\n\n return yValues.map((y) => y * scaleFactor);\n};\n\nconst Histogram: React.FC<HistogramProps> = ({\n dataSeries,\n width,\n height,\n title = \"Histogram\",\n xTitle = \"X Axis\",\n yTitle = \"Frequency\",\n bargap = 0.2,\n showDistributionLine = false,\n}) => {\n const plotRef = useRef<HTMLDivElement>(null);\n const theme = usePlotlyTheme();\n const { bindTooltip, tooltipElement } = useChartTooltip({ xLabel: xTitle, yLabel: yTitle });\n\n // Omitted width/height → fill the container and track its measured size;\n // explicit pixel values override. Histogram has its own HTML title + legend,\n // so we measure a wrapper around just the Plotly canvas. See AreaPlot for\n // the reference pattern.\n const [plotAreaRef, measured] = useElementSize<HTMLDivElement>();\n const resolvedWidth = width ?? measured.width;\n const resolvedHeight = height ?? measured.height;\n const hasSize = resolvedWidth > 0 && resolvedHeight > 0;\n // Fill is per-dimension: omit width to fill the container width, omit height\n // to fill its height (so e.g. a fixed width with a container-driven height works).\n const fillWidth = width === undefined;\n const fillHeight = height === undefined;\n const sizeRef = useRef({ width: resolvedWidth, height: resolvedHeight });\n sizeRef.current = { width: resolvedWidth, height: resolvedHeight };\n const plotInitedRef = useRef(false);\n // Size last applied to the plot, so the resize effect can skip a redundant\n // relayout right after newPlot already drew at that size.\n const appliedSizeRef = useRef({ width: 0, height: 0 });\n const seriesArray = useMemo(\n () => (Array.isArray(dataSeries) ? dataSeries : [dataSeries]),\n [dataSeries],\n );\n const effectiveBarMode = useMemo<\n \"stack\" | \"group\" | \"overlay\" | \"relative\" | undefined\n >(() => (seriesArray.length > 1 ? \"stack\" : undefined), [seriesArray.length]);\n\n const defaultColors = CHART_COLORS;\n\n const seriesWithColors = useMemo(() => {\n return seriesArray.map((series, index) => {\n const hasDistributionLine =\n typeof series.showDistributionLine === \"undefined\"\n ? showDistributionLine\n : series.showDistributionLine;\n\n return {\n ...series,\n color: series.color || defaultColors[index % defaultColors.length],\n opacity: hasDistributionLine ? 0.5 : series.opacity || 1,\n showDistributionLine: hasDistributionLine,\n lineWidth: series.lineWidth || 3,\n };\n });\n }, [seriesArray, showDistributionLine, defaultColors]);\n\n const gridColor = theme.gridColor;\n\n const histogramData = useMemo(\n () =>\n seriesWithColors.map((series) => ({\n type: \"histogram\" as const,\n x: series.x,\n name: series.name,\n marker: {\n color: series.color,\n line: {\n color: theme.paperBg,\n width: 1,\n },\n opacity: series.opacity,\n },\n autobinx: series.autobinx,\n xbins: series.xbins,\n hoverinfo: \"none\" as const,\n })),\n [seriesWithColors, theme],\n );\n\n const distributionLines = useMemo(\n () =>\n seriesWithColors\n .filter((series) => series.showDistributionLine)\n .map((series) => {\n const mean = calculateMean(series.x);\n const stdDev = calculateStdDev(series.x, mean);\n\n const min = Math.min(...series.x);\n const max = Math.max(...series.x);\n const range = max - min;\n const start = min - range * 0.1;\n const end = max + range * 0.1;\n\n const bins = series.xbins || {\n start: start,\n end: end,\n size: range / 10,\n };\n\n const curvePoints = generateNormalDistributionPoints(\n mean,\n stdDev,\n start,\n end,\n 100,\n );\n\n const scaledYValues = scaleDistributionCurve(\n curvePoints.y,\n series.x,\n bins,\n );\n\n return {\n type: \"scatter\" as const,\n x: curvePoints.x,\n y: scaledYValues,\n mode: \"lines\" as const,\n name: `${series.name} Distribution`,\n line: {\n color: series.color,\n width: series.lineWidth,\n },\n hoverinfo: \"none\" as const,\n };\n }),\n [seriesWithColors],\n );\n\n const plotData = useMemo(\n () => [...histogramData, ...distributionLines],\n [histogramData, distributionLines],\n );\n\n useEffect(() => {\n if (!plotRef.current || !hasSize) return;\n\n const layout = {\n width: sizeRef.current.width,\n height: sizeRef.current.height,\n font: {\n family: CHART_FONT_FAMILY,\n },\n showlegend: false,\n margin: { l: 90, r: 40, b: 80, t: 40 },\n xaxis: {\n title: {\n text: xTitle,\n font: {\n size: 16,\n color: theme.textSecondary,\n family: CHART_FONT_FAMILY,\n weight: 400,\n },\n standoff: 20,\n },\n gridcolor: gridColor,\n tickcolor: theme.tickColor,\n ticklen: 8,\n tickwidth: 1,\n ticks: \"outside\" as const,\n linecolor: theme.lineColor,\n linewidth: 1,\n zeroline: false,\n automargin: true,\n },\n yaxis: {\n title: {\n text: yTitle,\n font: {\n size: 16,\n color: theme.textSecondary,\n family: CHART_FONT_FAMILY,\n weight: 400,\n },\n standoff: 20,\n },\n gridcolor: gridColor,\n tickcolor: theme.tickColor,\n ticklen: 8,\n tickwidth: 1,\n ticks: \"outside\" as const,\n linecolor: theme.lineColor,\n linewidth: 1,\n zeroline: false,\n rangemode: \"tozero\" as const,\n automargin: true,\n },\n barmode: effectiveBarMode,\n bargap: bargap,\n paper_bgcolor: theme.paperBg,\n plot_bgcolor: theme.plotBg,\n };\n\n const config = {\n // Sizing is driven from the measured container; disable Plotly's own\n // window-resize responsiveness (it can't see container resizes).\n responsive: false,\n displayModeBar: false,\n displaylogo: false,\n };\n\n // Plotly is loaded lazily so it stays out of the consumer's main chunk\n // (SW-2007); the draw is skipped if the effect re-runs or unmounts first.\n let cancelled = false;\n let plotElement: HTMLDivElement | null = null;\n void loadPlotly().then((plotly) => {\n if (cancelled || !plotRef.current) return;\n plotly.newPlot(plotRef.current, plotData, layout, config);\n bindTooltip(plotRef.current);\n\n // Capture ref value for cleanup\n plotElement = plotRef.current;\n plotInitedRef.current = true;\n appliedSizeRef.current = { ...sizeRef.current };\n });\n\n return () => {\n cancelled = true;\n if (plotElement) {\n getLoadedPlotly().purge(plotElement);\n plotInitedRef.current = false;\n }\n };\n }, [hasSize, xTitle, yTitle, bargap, plotData, effectiveBarMode, gridColor, theme, bindTooltip]);\n\n // Resize in place when the measured/overridden size changes — cheaper than\n // recreating the plot, and it preserves tooltip/event bindings.\n useEffect(() => {\n const plotElement = plotRef.current;\n if (!plotElement || !plotInitedRef.current || resolvedWidth <= 0 || resolvedHeight <= 0) {\n return;\n }\n // newPlot already drew at the current size; skip the redundant relayout\n // (it would queue an automargin redraw that can reject if we unmount first).\n if (\n appliedSizeRef.current.width === resolvedWidth &&\n appliedSizeRef.current.height === resolvedHeight\n ) {\n return;\n }\n appliedSizeRef.current = { width: resolvedWidth, height: resolvedHeight };\n // Swallow rejections from a relayout that races an unmount/purge.\n // plotInitedRef guarantees Plotly finished loading, so sync access is safe.\n void getLoadedPlotly()\n .relayout(plotElement, { width: resolvedWidth, height: resolvedHeight })\n .catch(() => {});\n }, [resolvedWidth, resolvedHeight]);\n\n const ChartLegend: React.FC<{\n series: Array<{ name: string; color: string }>;\n }> = ({ series }) => {\n const items = series.map((item, i) => (\n <React.Fragment key={item.name}>\n <div className=\"legend-item\">\n <span className=\"color-box\" style={{ background: item.color }} />\n {item.name}\n {i < series.length - 1 && <span className=\"divider\" />}\n </div>\n </React.Fragment>\n ));\n\n const rows = [];\n const rowSize = 6;\n for (let i = 0; i < items.length; i += rowSize) {\n rows.push(\n <div className=\"legend-row\" key={i}>\n {items.slice(i, i + rowSize)}\n </div>\n );\n }\n\n return <div className=\"legend-container\">{rows}</div>;\n };\n\n return (\n <div\n className={cn(\"histogram-container relative\", fillWidth && \"w-full\", fillHeight && \"h-full\")}\n style={width === undefined ? undefined : { width }}\n >\n <div className={cn(\"chart-container\", fillHeight && \"flex h-full flex-col\")}>\n {title && (\n <div className=\"title-container\">\n <h2 className=\"title\">{title}</h2>\n </div>\n )}\n {/* Measured plot area — flexes to fill the space left by the title and\n legend in fill mode, so the Plotly canvas tracks it. */}\n <div ref={plotAreaRef} className={cn(fillHeight && \"min-h-0 flex-1\")}>\n <div\n ref={plotRef}\n style={{\n width: \"100%\",\n height: \"100%\",\n margin: \"0\",\n }}\n />\n </div>\n <ChartLegend series={seriesWithColors} />\n </div>\n {tooltipElement}\n </div>\n );\n};\n\nexport { Histogram };\nexport type { HistogramDataSeries, HistogramProps };\n"],"names":["NORMAL_DISTRIBUTION_EXPONENT_COEFF","calculateMean","data","acc","val","calculateStdDev","mean","variance","value","generateNormalDistributionPoints","stdDev","start","end","points","xValues","yValues","step","i","x","exponent","y","scaleDistributionCurve","histogramData","bins","binCount","binFrequencies","binIndex","maxBinFrequency","maxCurveValue","scaleFactor","Histogram","dataSeries","width","height","title","xTitle","yTitle","bargap","showDistributionLine","plotRef","useRef","theme","usePlotlyTheme","bindTooltip","tooltipElement","useChartTooltip","plotAreaRef","measured","useElementSize","resolvedWidth","resolvedHeight","hasSize","fillWidth","fillHeight","sizeRef","plotInitedRef","appliedSizeRef","seriesArray","useMemo","effectiveBarMode","defaultColors","CHART_COLORS","seriesWithColors","series","index","hasDistributionLine","gridColor","distributionLines","min","max","range","curvePoints","scaledYValues","plotData","useEffect","layout","CHART_FONT_FAMILY","config","cancelled","plotElement","loadPlotly","plotly","getLoadedPlotly","ChartLegend","items","item","jsx","React","jsxs","rows","rowSize","cn"],"mappings":";;;;;;;;;AAYA,MAAMA,KAAqC,MAoCrCC,KAAgB,CAACC,MACTA,EAAK,OAAO,CAACC,GAAKC,MAAQD,IAAMC,GAAK,CAAC,IACrCF,EAAK,QAGdG,KAAkB,CAACH,GAAgBI,MAAyB;AAEhE,QAAMC,IADeL,EAAK,IAAI,CAACM,MAAU,KAAK,IAAIA,IAAQF,GAAM,CAAC,CAAC,EAEnD,OAAO,CAACH,GAAKC,MAAQD,IAAMC,GAAK,CAAC,IAAIF,EAAK;AACzD,SAAO,KAAK,KAAKK,CAAQ;AAC3B,GAEME,KAAmC,CACvCH,GACAI,GACAC,GACAC,GACAC,IAAS,QACwB;AACjC,QAAMC,IAAoB,CAAA,GACpBC,IAAoB,CAAA,GAEpBC,KAAQJ,IAAMD,MAAUE,IAAS;AAEvC,WAASI,IAAI,GAAGA,IAAIJ,GAAQI,KAAK;AAC/B,UAAMC,IAAIP,IAAQM,IAAID;AACtB,IAAAF,EAAQ,KAAKI,CAAC;AAEd,UAAMC,IAAWnB,KAAqC,KAAK,KAAKkB,IAAIZ,KAAQI,GAAQ,CAAC,GAC/EU,IAAK,KAAKV,IAAS,KAAK,KAAK,IAAI,KAAK,EAAE,KAAM,KAAK,IAAIS,CAAQ;AACrE,IAAAJ,EAAQ,KAAKK,CAAC;AAAA,EAChB;AAEA,SAAO,EAAE,GAAGN,GAAS,GAAGC,EAAA;AAC1B,GAEMM,KAAyB,CAC7BN,GACAO,GACAC,MACa;AACb,QAAMC,IAAW,KAAK,MAAMD,EAAK,MAAMA,EAAK,SAASA,EAAK,IAAI,GACxDE,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A,IAAA;AAAA,MACC,WAAWG,EAAG,gCAAgCvC,KAAa,UAAUC,KAAc,QAAQ;AAAA,MAC3F,OAAOrB,MAAU,SAAY,SAAY,EAAE,OAAAA,EAAA;AAAA,MAE3C,UAAA;AAAA,QAAA,gBAAAwD,EAAC,SAAI,WAAWG,EAAG,mBAAmBtC,KAAc,sBAAsB,GACvE,UAAA;AAAA,UAAAnB,KACC,gBAAAoD,EAAC,SAAI,WAAU,mBACb,4BAAC,MAAA,EAAG,WAAU,SAAS,UAAApD,EAAA,CAAM,EAAA,CAC/B;AAAA,UAIF,gBAAAoD,EAAC,SAAI,KAAKxC,GAAa,WAAW6C,EAAGtC,KAAc,gBAAgB,GACjE,UAAA,gBAAAiC;AAAA,YAAC;AAAA,YAAA;AAAA,cACC,KAAK/C;AAAA,cACL,OAAO;AAAA,gBACL,OAAO;AAAA,gBACP,QAAQ;AAAA,gBACR,QAAQ;AAAA,cAAA;AAAA,YACV;AAAA,UAAA,GAEJ;AAAA,UACA,gBAAA+C,EAACH,GAAA,EAAY,QAAQrB,EAAA,CAAkB;AAAA,QAAA,GACzC;AAAA,QACClB;AAAA,MAAA;AAAA,IAAA;AAAA,EAAA;AAGP;"}
|
|
1
|
+
{"version":3,"file":"Histogram.js","sources":["../../../../src/components/charts/Histogram/Histogram.tsx"],"sourcesContent":["import React, { useEffect, useRef, useMemo } from \"react\";\n\nimport { useChartTooltip } from \"../ChartTooltip\";\nimport { getLoadedPlotly, loadPlotly } from \"../plotly-loader\";\n\nimport { useElementSize } from \"@/hooks/use-element-size\";\nimport { CHART_FONT_FAMILY, usePlotlyTheme } from \"@/hooks/use-plotly-theme\";\nimport { cn } from \"@/lib/utils\";\nimport { CHART_COLORS } from \"@/utils/colors\";\nimport \"./Histogram.scss\";\n\n/** Exponent coefficient for normal distribution calculation */\nconst NORMAL_DISTRIBUTION_EXPONENT_COEFF = -0.5;\n\ninterface HistogramDataSeries {\n x: number[];\n name: string;\n color?: string;\n autobinx?: boolean;\n xbins?: {\n start: number;\n end: number;\n size: number;\n };\n opacity?: number;\n showDistributionLine?: boolean;\n lineWidth?: number;\n}\n\ntype HistogramProps = {\n dataSeries: HistogramDataSeries | HistogramDataSeries[];\n /**\n * Fixed width in pixels. When omitted, the chart fills its container and\n * tracks the container's width via a `ResizeObserver`.\n */\n width?: number;\n /**\n * Fixed height in pixels. When omitted, the chart fills its container and\n * tracks the container's height via a `ResizeObserver`.\n */\n height?: number;\n title?: string;\n xTitle?: string;\n yTitle?: string;\n bargap?: number;\n showDistributionLine?: boolean;\n};\n\nconst calculateMean = (data: number[]): number => {\n const sum = data.reduce((acc, val) => acc + val, 0);\n return sum / data.length;\n};\n\nconst calculateStdDev = (data: number[], mean: number): number => {\n const squaredDiffs = data.map((value) => Math.pow(value - mean, 2));\n const variance =\n squaredDiffs.reduce((acc, val) => acc + val, 0) / data.length;\n return Math.sqrt(variance);\n};\n\nconst generateNormalDistributionPoints = (\n mean: number,\n stdDev: number,\n start: number,\n end: number,\n points = 100\n): { x: number[]; y: number[] } => {\n const xValues: number[] = [];\n const yValues: number[] = [];\n\n const step = (end - start) / (points - 1);\n\n for (let i = 0; i < points; i++) {\n const x = start + i * step;\n xValues.push(x);\n\n const exponent = NORMAL_DISTRIBUTION_EXPONENT_COEFF * Math.pow((x - mean) / stdDev, 2);\n const y = (1 / (stdDev * Math.sqrt(2 * Math.PI))) * Math.exp(exponent);\n yValues.push(y);\n }\n\n return { x: xValues, y: yValues };\n};\n\nconst scaleDistributionCurve = (\n yValues: number[],\n histogramData: number[],\n bins: { start: number; end: number; size: number }\n): number[] => {\n const binCount = Math.ceil((bins.end - bins.start) / bins.size);\n const binFrequencies = Array(binCount).fill(0);\n\n histogramData.forEach((value) => {\n if (value >= bins.start && value <= bins.end) {\n const binIndex = Math.floor((value - bins.start) / bins.size);\n binFrequencies[binIndex]++;\n }\n });\n\n const maxBinFrequency = Math.max(...binFrequencies);\n const maxCurveValue = Math.max(...yValues);\n\n const scaleFactor = maxBinFrequency / maxCurveValue;\n\n return yValues.map((y) => y * scaleFactor);\n};\n\nconst Histogram: React.FC<HistogramProps> = ({\n dataSeries,\n width,\n height,\n title = \"Histogram\",\n xTitle = \"X Axis\",\n yTitle = \"Frequency\",\n bargap = 0.2,\n showDistributionLine = false,\n}) => {\n const plotRef = useRef<HTMLDivElement>(null);\n const theme = usePlotlyTheme();\n const { bindTooltip, tooltipElement } = useChartTooltip({ xLabel: xTitle, yLabel: yTitle });\n\n // Omitted width/height → fill the container and track its measured size;\n // explicit pixel values override. Histogram has its own HTML title + legend,\n // so we measure a wrapper around just the Plotly canvas. See AreaPlot for\n // the reference pattern.\n const [plotAreaRef, measured] = useElementSize<HTMLDivElement>();\n const resolvedWidth = width ?? measured.width;\n const resolvedHeight = height ?? measured.height;\n const hasSize = resolvedWidth > 0 && resolvedHeight > 0;\n // Fill is per-dimension: omit width to fill the container width, omit height\n // to fill its height (so e.g. a fixed width with a container-driven height works).\n const fillWidth = width === undefined;\n const fillHeight = height === undefined;\n const sizeRef = useRef({ width: resolvedWidth, height: resolvedHeight });\n sizeRef.current = { width: resolvedWidth, height: resolvedHeight };\n const plotInitedRef = useRef(false);\n // Size last applied to the plot, so the resize effect can skip a redundant\n // relayout right after newPlot already drew at that size.\n const appliedSizeRef = useRef({ width: 0, height: 0 });\n const seriesArray = useMemo(\n () => (Array.isArray(dataSeries) ? dataSeries : [dataSeries]),\n [dataSeries],\n );\n const effectiveBarMode = useMemo<\n \"stack\" | \"group\" | \"overlay\" | \"relative\" | undefined\n >(() => (seriesArray.length > 1 ? \"stack\" : undefined), [seriesArray.length]);\n\n const defaultColors = CHART_COLORS;\n\n const seriesWithColors = useMemo(() => {\n return seriesArray.map((series, index) => {\n const hasDistributionLine =\n typeof series.showDistributionLine === \"undefined\"\n ? showDistributionLine\n : series.showDistributionLine;\n\n return {\n ...series,\n color: series.color || defaultColors[index % defaultColors.length],\n opacity: hasDistributionLine ? 0.5 : series.opacity || 1,\n showDistributionLine: hasDistributionLine,\n lineWidth: series.lineWidth || 3,\n };\n });\n }, [seriesArray, showDistributionLine, defaultColors]);\n\n const gridColor = theme.gridColor;\n\n const histogramData = useMemo(\n () =>\n seriesWithColors.map((series) => ({\n type: \"histogram\" as const,\n x: series.x,\n name: series.name,\n marker: {\n color: series.color,\n line: {\n color: theme.paperBg,\n width: 1,\n },\n opacity: series.opacity,\n },\n autobinx: series.autobinx,\n xbins: series.xbins,\n hoverinfo: \"none\" as const,\n })),\n [seriesWithColors, theme],\n );\n\n const distributionLines = useMemo(\n () =>\n seriesWithColors\n .filter((series) => series.showDistributionLine)\n .map((series) => {\n const mean = calculateMean(series.x);\n const stdDev = calculateStdDev(series.x, mean);\n\n const min = Math.min(...series.x);\n const max = Math.max(...series.x);\n const range = max - min;\n const start = min - range * 0.1;\n const end = max + range * 0.1;\n\n const bins = series.xbins || {\n start: start,\n end: end,\n size: range / 10,\n };\n\n const curvePoints = generateNormalDistributionPoints(\n mean,\n stdDev,\n start,\n end,\n 100,\n );\n\n const scaledYValues = scaleDistributionCurve(\n curvePoints.y,\n series.x,\n bins,\n );\n\n return {\n type: \"scatter\" as const,\n x: curvePoints.x,\n y: scaledYValues,\n mode: \"lines\" as const,\n name: `${series.name} Distribution`,\n line: {\n color: series.color,\n width: series.lineWidth,\n },\n hoverinfo: \"none\" as const,\n };\n }),\n [seriesWithColors],\n );\n\n const plotData = useMemo(\n () => [...histogramData, ...distributionLines],\n [histogramData, distributionLines],\n );\n\n useEffect(() => {\n if (!plotRef.current || !hasSize) return;\n\n const layout = {\n width: sizeRef.current.width,\n height: sizeRef.current.height,\n font: {\n family: CHART_FONT_FAMILY,\n },\n showlegend: false,\n margin: { l: 90, r: 40, b: 80, t: 40 },\n xaxis: {\n title: {\n text: xTitle,\n font: {\n size: 16,\n color: theme.textSecondary,\n family: CHART_FONT_FAMILY,\n weight: 400,\n },\n standoff: 20,\n },\n gridcolor: gridColor,\n tickcolor: theme.tickColor,\n ticklen: 8,\n tickwidth: 1,\n ticks: \"outside\" as const,\n linecolor: theme.lineColor,\n linewidth: 1,\n zeroline: false,\n automargin: true,\n },\n yaxis: {\n title: {\n text: yTitle,\n font: {\n size: 16,\n color: theme.textSecondary,\n family: CHART_FONT_FAMILY,\n weight: 400,\n },\n standoff: 20,\n },\n gridcolor: gridColor,\n tickcolor: theme.tickColor,\n ticklen: 8,\n tickwidth: 1,\n ticks: \"outside\" as const,\n linecolor: theme.lineColor,\n linewidth: 1,\n zeroline: false,\n rangemode: \"tozero\" as const,\n automargin: true,\n },\n barmode: effectiveBarMode,\n bargap: bargap,\n paper_bgcolor: theme.paperBg,\n plot_bgcolor: theme.plotBg,\n };\n\n const config = {\n // Sizing is driven from the measured container; disable Plotly's own\n // window-resize responsiveness (it can't see container resizes).\n responsive: false,\n displayModeBar: false,\n displaylogo: false,\n };\n\n // Plotly is loaded lazily so it stays out of the consumer's main chunk\n // (SW-2007); the draw is skipped if the effect re-runs or unmounts first.\n let cancelled = false;\n let plotElement: HTMLDivElement | null = null;\n void loadPlotly().then((plotly) => {\n if (cancelled || !plotRef.current) return;\n plotly.newPlot(plotRef.current, plotData, layout, config);\n bindTooltip(plotRef.current);\n\n // Capture ref value for cleanup\n plotElement = plotRef.current;\n plotInitedRef.current = true;\n appliedSizeRef.current = { ...sizeRef.current };\n });\n\n return () => {\n cancelled = true;\n if (plotElement) {\n getLoadedPlotly().purge(plotElement);\n plotInitedRef.current = false;\n }\n };\n }, [hasSize, xTitle, yTitle, bargap, plotData, effectiveBarMode, gridColor, theme, bindTooltip]);\n\n // Resize in place when the measured/overridden size changes — cheaper than\n // recreating the plot, and it preserves tooltip/event bindings.\n useEffect(() => {\n const plotElement = plotRef.current;\n if (!plotElement || !plotInitedRef.current || resolvedWidth <= 0 || resolvedHeight <= 0) {\n return;\n }\n // newPlot already drew at the current size; skip the redundant relayout\n // (it would queue an automargin redraw that can reject if we unmount first).\n if (\n appliedSizeRef.current.width === resolvedWidth &&\n appliedSizeRef.current.height === resolvedHeight\n ) {\n return;\n }\n appliedSizeRef.current = { width: resolvedWidth, height: resolvedHeight };\n // Swallow rejections from a relayout that races an unmount/purge.\n // plotInitedRef guarantees Plotly finished loading, so sync access is safe.\n void getLoadedPlotly()\n .relayout(plotElement, { width: resolvedWidth, height: resolvedHeight })\n .catch(() => {});\n }, [resolvedWidth, resolvedHeight]);\n\n const ChartLegend: React.FC<{\n series: Array<{ name: string; color: string }>;\n }> = ({ series }) => {\n const items = series.map((item, i) => (\n <React.Fragment key={item.name}>\n <div className=\"histogram-legend-item\">\n <span className=\"histogram-legend-swatch\" style={{ background: item.color }} />\n {item.name}\n {i < series.length - 1 && <span className=\"histogram-legend-divider\" />}\n </div>\n </React.Fragment>\n ));\n\n const rows = [];\n const rowSize = 6;\n for (let i = 0; i < items.length; i += rowSize) {\n rows.push(\n <div className=\"histogram-legend-row\" key={i}>\n {items.slice(i, i + rowSize)}\n </div>\n );\n }\n\n return <div className=\"histogram-legend\">{rows}</div>;\n };\n\n return (\n <div\n className={cn(\"histogram-container relative\", fillWidth && \"w-full\", fillHeight && \"h-full\")}\n style={width === undefined ? undefined : { width }}\n >\n <div className={cn(\"histogram-chart\", fillHeight && \"flex h-full flex-col\")}>\n {title && (\n <div className=\"histogram-title-container\">\n <h2 className=\"histogram-title\">{title}</h2>\n </div>\n )}\n {/* Measured plot area — flexes to fill the space left by the title and\n legend in fill mode, so the Plotly canvas tracks it. */}\n <div ref={plotAreaRef} className={cn(fillHeight && \"min-h-0 flex-1\")}>\n <div\n ref={plotRef}\n style={{\n width: \"100%\",\n height: \"100%\",\n margin: \"0\",\n }}\n />\n </div>\n <ChartLegend series={seriesWithColors} />\n </div>\n {tooltipElement}\n </div>\n );\n};\n\nexport { Histogram };\nexport type { HistogramDataSeries, HistogramProps };\n"],"names":["NORMAL_DISTRIBUTION_EXPONENT_COEFF","calculateMean","data","acc","val","calculateStdDev","mean","variance","value","generateNormalDistributionPoints","stdDev","start","end","points","xValues","yValues","step","i","x","exponent","y","scaleDistributionCurve","histogramData","bins","binCount","binFrequencies","binIndex","maxBinFrequency","maxCurveValue","scaleFactor","Histogram","dataSeries","width","height","title","xTitle","yTitle","bargap","showDistributionLine","plotRef","useRef","theme","usePlotlyTheme","bindTooltip","tooltipElement","useChartTooltip","plotAreaRef","measured","useElementSize","resolvedWidth","resolvedHeight","hasSize","fillWidth","fillHeight","sizeRef","plotInitedRef","appliedSizeRef","seriesArray","useMemo","effectiveBarMode","defaultColors","CHART_COLORS","seriesWithColors","series","index","hasDistributionLine","gridColor","distributionLines","min","max","range","curvePoints","scaledYValues","plotData","useEffect","layout","CHART_FONT_FAMILY","config","cancelled","plotElement","loadPlotly","plotly","getLoadedPlotly","ChartLegend","items","item","jsx","React","jsxs","rows","rowSize","cn"],"mappings":";;;;;;;;;AAYA,MAAMA,KAAqC,MAoCrCC,KAAgB,CAACC,MACTA,EAAK,OAAO,CAACC,GAAKC,MAAQD,IAAMC,GAAK,CAAC,IACrCF,EAAK,QAGdG,KAAkB,CAACH,GAAgBI,MAAyB;AAEhE,QAAMC,IADeL,EAAK,IAAI,CAACM,MAAU,KAAK,IAAIA,IAAQF,GAAM,CAAC,CAAC,EAEnD,OAAO,CAACH,GAAKC,MAAQD,IAAMC,GAAK,CAAC,IAAIF,EAAK;AACzD,SAAO,KAAK,KAAKK,CAAQ;AAC3B,GAEME,KAAmC,CACvCH,GACAI,GACAC,GACAC,GACAC,IAAS,QACwB;AACjC,QAAMC,IAAoB,CAAA,GACpBC,IAAoB,CAAA,GAEpBC,KAAQJ,IAAMD,MAAUE,IAAS;AAEvC,WAASI,IAAI,GAAGA,IAAIJ,GAAQI,KAAK;AAC/B,UAAMC,IAAIP,IAAQM,IAAID;AACtB,IAAAF,EAAQ,KAAKI,CAAC;AAEd,UAAMC,IAAWnB,KAAqC,KAAK,KAAKkB,IAAIZ,KAAQI,GAAQ,CAAC,GAC/EU,IAAK,KAAKV,IAAS,KAAK,KAAK,IAAI,KAAK,EAAE,KAAM,KAAK,IAAIS,CAAQ;AAC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AH,EAAC,OAAA,EAAI,WAAU,wBACZ,UAAAF,EAAM,MAAM,GAAG,IAAIM,CAAO,EAAA,GADc,CAE3C;AAAA,MAAA;AAIJ,WAAO,gBAAAJ,EAAC,OAAA,EAAI,WAAU,oBAAoB,UAAAG,GAAK;AAAA,EACjD;AAEA,SACE,gBAAAD;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,WAAWG,EAAG,gCAAgCvC,KAAa,UAAUC,KAAc,QAAQ;AAAA,MAC3F,OAAOrB,MAAU,SAAY,SAAY,EAAE,OAAAA,EAAA;AAAA,MAE3C,UAAA;AAAA,QAAA,gBAAAwD,EAAC,SAAI,WAAWG,EAAG,mBAAmBtC,KAAc,sBAAsB,GACvE,UAAA;AAAA,UAAAnB,KACC,gBAAAoD,EAAC,SAAI,WAAU,6BACb,4BAAC,MAAA,EAAG,WAAU,mBAAmB,UAAApD,EAAA,CAAM,EAAA,CACzC;AAAA,UAIF,gBAAAoD,EAAC,SAAI,KAAKxC,GAAa,WAAW6C,EAAGtC,KAAc,gBAAgB,GACjE,UAAA,gBAAAiC;AAAA,YAAC;AAAA,YAAA;AAAA,cACC,KAAK/C;AAAA,cACL,OAAO;AAAA,gBACL,OAAO;AAAA,gBACP,QAAQ;AAAA,gBACR,QAAQ;AAAA,cAAA;AAAA,YACV;AAAA,UAAA,GAEJ;AAAA,UACA,gBAAA+C,EAACH,GAAA,EAAY,QAAQrB,EAAA,CAAkB;AAAA,QAAA,GACzC;AAAA,QACClB;AAAA,MAAA;AAAA,IAAA;AAAA,EAAA;AAGP;"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const de=require("react/jsx-runtime"),n=require("react")
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const de=require("react/jsx-runtime"),n=require("react"),Se=require("../ChartTooltip/ChartTooltip.cjs"),x=require("../plotly-loader.cjs"),E=require("./constants.cjs"),c=require("./utils.cjs"),Te=require("../../../hooks/use-plotly-theme.cjs"),fe={},Ie={enabled:!0},ve=({data:R,title:z,xAxis:u=fe,yAxis:i=fe,colorMapping:r,shapeMapping:V,sizeMapping:X,tooltip:a=Ie,enableClickSelection:$=!0,enableBoxSelection:g=!0,enableLassoSelection:p=!0,selectedIds:H,onSelectionChange:J,onPointClick:K,downsampling:N,width:w=800,height:L=600,showColorBar:Q=!0,className:W})=>{const S=n.useRef(null),Y=Te.usePlotlyTheme(),P=n.useRef(J),Z=n.useRef(K),M=n.useRef(new Set),_=n.useRef(!1);P.current=J,Z.current=K;const[me,k]=n.useState(new Set),ee=H!==void 0,q=ee?H:me;M.current=q,_.current=ee;const te=n.useMemo(()=>new Set([...q].map(String)),[q]),ne=n.useMemo(()=>new Map(R.map(e=>[String(e.id),e.id])),[R]),t=n.useMemo(()=>N?c.downsampleData(R,N):R,[R,N]),h=n.useMemo(()=>c.mapColors(t,r),[t,r]),re=n.useMemo(()=>c.mapShapes(t,V),[t,V]),se=n.useMemo(()=>c.mapSizes(t,X),[t,X]),oe=n.useMemo(()=>{if(u.range)return u.range;if(u.autoRange!==!1)return c.calculateAxisRange(t,"x",u.autoRangePadding??E.PLOT_CONSTANTS.AUTO_RANGE_PADDING,u.scale)},[t,u]),ce=n.useMemo(()=>{if(i.range)return i.range;if(i.autoRange!==!1)return c.calculateAxisRange(t,"y",i.autoRangePadding??E.PLOT_CONSTANTS.AUTO_RANGE_PADDING,i.scale)},[t,i]),f=a.enabled!==!1,C=a.native===!0,B=n.useMemo(()=>f?t.map(e=>a.content?a.content(e):c.generateTooltipContent(e,a.fields)):[],[t,a,f]),{bindTooltip:le,tooltipElement:ye}=Se.useChartTooltip({getLines:e=>{const s=e[0]?.pointIndex;return s===void 0?[]:(B[s]??"").split("<br>").filter(Boolean)}}),ue=n.useMemo(()=>r?.type==="continuous"&&r.field&&t.length>0?t.map(e=>{const s=e.metadata?.[r.field];return typeof s=="number"&&Number.isFinite(s)?s:0}):h,[t,r,h]),D=n.useMemo(()=>{if(r?.type==="continuous"){const e=r.colorScale||E.DEFAULT_COLOR_SCALE;return e}},[r]),ie=n.useMemo(()=>{const e={size:se,symbol:re,line:{width:0}};if(r?.type==="continuous"&&D){if(e.color=ue,e.colorscale=D,e.showscale=Q,r.field){const s=r.min!==void 0&&r.max!==void 0?{min:r.min,max:r.max}:c.calculateRange(t,r.field);e.cmin=s.min,e.cmax=s.max,e.colorbar={title:{text:r.field,side:"right"},thickness:20,len:.7}}}else e.color=h;return e},[se,re,r,D,ue,Q,t,h]);n.useEffect(()=>{const e=S.current;if(!e||t.length===0)return;const s=t.map(d=>d.x),T=t.map(d=>d.y),O=t.map(d=>String(d.id)),I=[{x:s,y:T,ids:O,mode:"markers",type:"scatter",marker:ie,hoverinfo:f?C?"text":"none":"skip",text:B,hovertemplate:f&&C?"%{text}<extra></extra>":void 0,showlegend:!1,unselected:{marker:{opacity:.3}},selected:{marker:{opacity:1,line:{color:E.COLORS.selected,width:2}}}}],G=c.getPlotlyLayoutConfig({title:z,xAxis:u,yAxis:i,width:w,height:L,xRange:oe,yRange:ce,enableLassoSelection:p,enableBoxSelection:g,theme:Y}),U={responsive:!0,displayModeBar:!0,displaylogo:!1,modeBarButtonsToAdd:[],modeBarButtonsToRemove:["toImage"]};g&&U.modeBarButtonsToAdd?.push("select2d"),p&&U.modeBarButtonsToAdd?.push("lasso2d");let ae=!1,b=null;return x.loadPlotly().then(d=>{if(ae||!S.current)return;d.newPlot(e,I,G,U);const j=e;$&&j.on("plotly_click",l=>{const m=l.points[0];if(m&&m.data.ids){const A=m.data.ids[m.pointIndex],y=t.find(o=>String(o.id)===A);if(y){Z.current?.(y,l.event);const o=c.getSelectionMode(l.event),v=c.applySelection(M.current,new Set([y.id]),o);_.current||k(v),P.current?.(v,o)}}}),(g||p)&&(j.on("plotly_selected",l=>{if(l&&l.points){const m=l.points.map(o=>{if(o.data.ids&&o.pointIndex!==void 0){const v=o.data.ids[o.pointIndex];return ne.get(v)??v}return null}).filter(o=>o!==null),A="replace",y=new Set(m);_.current||k(y),P.current?.(y,A)}}),j.on("plotly_deselect",()=>{const l=new Set;_.current||k(l),P.current?.(l,"replace")})),f&&!C&&le(e),b=e}),()=>{ae=!0,b&&x.getLoadedPlotly().purge(b)}},[t,ie,u,i,oe,ce,z,w,L,a,B,$,g,p,ne,f,C,le,Y]),n.useEffect(()=>{if(!S.current||t.length===0)return;let e=!1;return x.loadPlotly().then(s=>{const T=S.current;if(e||!T||!T._fullLayout)return;const O=T,F=t.map((I,G)=>te.has(String(I.id))?G:null).filter(I=>I!==null);F.length>0?s.restyle(O,{selectedpoints:[F]},[0]):s.restyle(O,{selectedpoints:[null]},[0])}),()=>{e=!0}},[te,t]);const Re=W?`scatter-plot-interactive relative ${W}`:"scatter-plot-interactive relative";return de.jsxs("div",{className:Re,children:[de.jsx("div",{ref:S,className:"scatter-plot-interactive__plot",style:{width:w,height:L}}),ye]})};exports.ScatterPlotInteractive=ve;
|
|
2
2
|
//# sourceMappingURL=ScatterPlotInteractive.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ScatterPlotInteractive.cjs","sources":["../../../../src/components/charts/ScatterPlotInteractive/ScatterPlotInteractive.tsx"],"sourcesContent":["import React, { useEffect, useMemo, useRef, useState } from \"react\";\n\nimport \"./ScatterPlotInteractive.scss\";\nimport { useChartTooltip } from \"../ChartTooltip\";\nimport { getLoadedPlotly, loadPlotly } from \"../plotly-loader\";\n\nimport { COLORS, DEFAULT_COLOR_SCALE, PLOT_CONSTANTS } from \"./constants\";\nimport {\n applySelection,\n calculateAxisRange,\n calculateRange,\n downsampleData,\n generateTooltipContent,\n getPlotlyLayoutConfig,\n getSelectionMode,\n mapColors,\n mapShapes,\n mapSizes,\n} from \"./utils\";\n\nimport type { AxisConfig, ScatterPlotInteractiveProps, SelectionMode, TooltipConfig } from \"./types\";\nimport type Plotly from \"plotly.js-dist\";\n\nimport { usePlotlyTheme } from \"@/hooks/use-plotly-theme\";\n\n// Stable default prop objects — inline defaults would create a new identity\n// on every render, retriggering the plot effect (and tearing down the\n// tooltip) whenever internal state changes\nconst DEFAULT_AXIS_CONFIG: AxisConfig = {};\nconst DEFAULT_TOOLTIP_CONFIG: TooltipConfig = { enabled: true };\n\n/**\n * ScatterPlotInteractive component for visualizing scatter plot data with advanced interactions.\n *\n * **Features:**\n * - Data-driven and static styling (color, shape, size)\n * - Interactive selection (click, box, lasso)\n * - Keyboard modifiers for click-selection modes (Shift/Ctrl)\n * - Customizable tooltips with rich content support\n * - Axis customization (ranges, log/linear scales)\n * - Performance optimizations for large datasets\n * - Selection propagation via callbacks\n *\n * **Selection Modes (click selection only):**\n * - Default click: Replace selection\n * - Shift + click: Add to selection\n * - Ctrl/Cmd + click: Remove from selection\n * - Shift + Ctrl + click: Toggle selection\n *\n * Box/lasso selection always replaces the current selection because\n * Plotly does not expose the original keyboard event for drag operations.\n */\nconst ScatterPlotInteractive: React.FC<ScatterPlotInteractiveProps> = ({\n data,\n title,\n xAxis = DEFAULT_AXIS_CONFIG,\n yAxis = DEFAULT_AXIS_CONFIG,\n colorMapping,\n shapeMapping,\n sizeMapping,\n tooltip = DEFAULT_TOOLTIP_CONFIG,\n enableClickSelection = true,\n enableBoxSelection = true,\n enableLassoSelection = true,\n selectedIds: controlledSelectedIds,\n onSelectionChange,\n onPointClick,\n downsampling,\n width = 800,\n height = 600,\n showColorBar = true,\n className,\n}) => {\n const plotRef = useRef<HTMLDivElement>(null);\n const theme = usePlotlyTheme();\n const onSelectionChangeRef = useRef(onSelectionChange);\n const onPointClickRef = useRef(onPointClick);\n const selectedIdsRef = useRef<Set<string | number>>(new Set());\n const isControlledRef = useRef(false);\n\n // Keep refs updated\n onSelectionChangeRef.current = onSelectionChange;\n onPointClickRef.current = onPointClick;\n\n // Internal selection state (only used in uncontrolled mode)\n const [internalSelectedIds, setInternalSelectedIds] = useState<Set<string | number>>(new Set());\n\n // Use controlled or uncontrolled selection\n const isControlled = controlledSelectedIds !== undefined;\n const selectedIds = isControlled ? controlledSelectedIds : internalSelectedIds;\n selectedIdsRef.current = selectedIds;\n isControlledRef.current = isControlled;\n\n // Normalize to strings so numeric IDs passed by consumers always match the\n // string IDs that Plotly stores (we always do String(p.id) when building the trace).\n const normalizedSelectedIds = useMemo(() => new Set([...selectedIds].map(String)), [selectedIds]);\n\n // Reverse-lookup: Plotly string ID → original (possibly numeric) ScatterPoint ID.\n // Used to restore original ID types when echoing selections back to consumers.\n const originalIdLookup = useMemo(() => new Map(data.map((p) => [String(p.id), p.id])), [data]);\n\n // Apply downsampling if configured\n const processedData = useMemo(() => {\n if (!downsampling) {\n return data;\n }\n return downsampleData(data, downsampling);\n }, [data, downsampling]);\n\n // Map colors, shapes, and sizes based on configuration\n const colors = useMemo(() => mapColors(processedData, colorMapping), [processedData, colorMapping]);\n\n const shapes = useMemo(() => mapShapes(processedData, shapeMapping), [processedData, shapeMapping]);\n\n const sizes = useMemo(() => mapSizes(processedData, sizeMapping), [processedData, sizeMapping]);\n\n // Calculate axis ranges\n const xRange = useMemo(() => {\n if (xAxis.range) return xAxis.range;\n if (xAxis.autoRange === false) return;\n return calculateAxisRange(processedData, \"x\", xAxis.autoRangePadding ?? PLOT_CONSTANTS.AUTO_RANGE_PADDING, xAxis.scale);\n }, [processedData, xAxis]);\n\n const yRange = useMemo(() => {\n if (yAxis.range) return yAxis.range;\n if (yAxis.autoRange === false) return;\n return calculateAxisRange(processedData, \"y\", yAxis.autoRangePadding ?? PLOT_CONSTANTS.AUTO_RANGE_PADDING, yAxis.scale);\n }, [processedData, yAxis]);\n\n const tooltipEnabled = tooltip.enabled !== false;\n const nativeTooltip = tooltip.native === true;\n\n // Build tooltip text\n const tooltipText = useMemo(() => {\n if (!tooltipEnabled) return [];\n\n return processedData.map((point) =>\n tooltip.content ? tooltip.content(point) : generateTooltipContent(point, tooltip.fields),\n );\n }, [processedData, tooltip, tooltipEnabled]);\n\n // Design-system tooltip driven by Plotly hover events\n const { bindTooltip, tooltipElement } = useChartTooltip({\n getLines: (points) => {\n const index = points[0]?.pointIndex;\n if (index === undefined) return [];\n return (tooltipText[index] ?? \"\").split(\"<br>\").filter(Boolean);\n },\n });\n\n // Prepare Plotly-compatible color data\n const plotlyColors = useMemo(() => {\n if (colorMapping?.type === \"continuous\" && colorMapping.field && processedData.length > 0) {\n // For continuous mapping, extract the numeric values\n return processedData.map((point) => {\n const value = point.metadata?.[colorMapping.field!];\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n });\n }\n return colors;\n }, [processedData, colorMapping, colors]);\n\n // Build colorscale for continuous mapping\n const plotlyColorscale = useMemo(() => {\n if (colorMapping?.type === \"continuous\") {\n const scale = colorMapping.colorScale || DEFAULT_COLOR_SCALE;\n return typeof scale === \"string\" ? scale : scale;\n }\n }, [colorMapping]);\n\n // Build marker configuration for Plotly\n const markerConfig = useMemo((): Partial<Plotly.PlotMarker> => {\n const config: Partial<Plotly.PlotMarker> = {\n size: sizes,\n symbol: shapes,\n // Points carry no outline; depth comes from a CSS drop-shadow\n // (see ScatterPlotInteractive.scss). Selected points re-add a line below.\n line: {\n width: 0,\n },\n };\n\n // Configure color mapping\n if (colorMapping?.type === \"continuous\" && plotlyColorscale) {\n config.color = plotlyColors as number[];\n config.colorscale = plotlyColorscale;\n config.showscale = showColorBar;\n\n if (colorMapping.field) {\n const range =\n colorMapping.min !== undefined && colorMapping.max !== undefined\n ? { min: colorMapping.min, max: colorMapping.max }\n : calculateRange(processedData, colorMapping.field);\n config.cmin = range.min;\n config.cmax = range.max;\n config.colorbar = {\n title: { text: colorMapping.field, side: \"right\" },\n thickness: 20,\n len: 0.7,\n };\n }\n } else {\n config.color = colors;\n }\n\n return config;\n }, [sizes, shapes, colorMapping, plotlyColorscale, plotlyColors, showColorBar, processedData, colors]);\n\n // Create Plotly plot\n useEffect(() => {\n const currentRef = plotRef.current;\n if (!currentRef || processedData.length === 0) return;\n\n const xValues = processedData.map((p) => p.x);\n const yValues = processedData.map((p) => p.y);\n const ids = processedData.map((p) => String(p.id));\n\n // Create base trace\n const trace: Partial<Plotly.PlotData> & {\n unselected?: { marker?: { opacity?: number } };\n selected?: { marker?: { opacity?: number; line?: { color?: string; width?: number } } };\n } = {\n x: xValues,\n y: yValues,\n ids,\n mode: \"markers\",\n type: \"scatter\",\n marker: markerConfig,\n // \"none\" keeps hover events firing for the HTML tooltip without\n // showing Plotly's hover label; \"skip\" disables hover entirely\n hoverinfo: tooltipEnabled ? (nativeTooltip ? \"text\" : \"none\") : \"skip\",\n text: tooltipText,\n hovertemplate: tooltipEnabled && nativeTooltip ? \"%{text}<extra></extra>\" : undefined,\n showlegend: false,\n unselected: {\n marker: {\n opacity: 0.3,\n },\n },\n selected: {\n marker: {\n opacity: 1,\n line: {\n color: COLORS.selected,\n width: 2,\n },\n },\n },\n };\n\n const plotData: Plotly.Data[] = [trace as Plotly.Data];\n\n // Configure layout\n const layout: Partial<Plotly.Layout> = getPlotlyLayoutConfig({\n title,\n xAxis,\n yAxis,\n width,\n height,\n xRange,\n yRange,\n enableLassoSelection,\n enableBoxSelection,\n theme,\n });\n\n const config: Partial<Plotly.Config> = {\n responsive: true,\n displayModeBar: true,\n displaylogo: false,\n modeBarButtonsToAdd: [],\n modeBarButtonsToRemove: [\"toImage\"],\n };\n\n // Add selection mode buttons if enabled\n if (enableBoxSelection) {\n config.modeBarButtonsToAdd?.push(\"select2d\" as never);\n }\n if (enableLassoSelection) {\n config.modeBarButtonsToAdd?.push(\"lasso2d\" as never);\n }\n\n // Plotly is loaded lazily so it stays out of the consumer's main chunk\n // (SW-2007); the draw is skipped if the effect re-runs or unmounts first.\n let cancelled = false;\n let drawnElement: HTMLDivElement | null = null;\n void loadPlotly().then((plotly) => {\n if (cancelled || !plotRef.current) return;\n plotly.newPlot(currentRef, plotData, layout, config);\n\n // Attach event handlers\n const plotElement = currentRef as unknown as Plotly.PlotlyHTMLElement;\n\n // Handle point click\n if (enableClickSelection) {\n plotElement.on(\"plotly_click\", (eventData: Plotly.PlotMouseEvent) => {\n const point = eventData.points[0];\n if (point && point.data.ids) {\n const clickedId = point.data.ids[point.pointIndex];\n const clickedPoint = processedData.find((p) => String(p.id) === clickedId);\n\n if (clickedPoint) {\n // Call point click handler if provided\n onPointClickRef.current?.(clickedPoint, eventData.event as MouseEvent);\n\n // Handle selection. Use the original-typed ID from the matched point so\n // numeric IDs (e.g., 123) are preserved instead of being coerced to \"123\".\n const mode = getSelectionMode(eventData.event as MouseEvent);\n const newSelection = applySelection(selectedIdsRef.current, new Set([clickedPoint.id]), mode);\n\n if (!isControlledRef.current) {\n setInternalSelectedIds(newSelection);\n }\n onSelectionChangeRef.current?.(newSelection, mode);\n }\n }\n });\n }\n\n // Handle box/lasso selection\n if (enableBoxSelection || enableLassoSelection) {\n plotElement.on(\"plotly_selected\", (eventData: Plotly.PlotSelectionEvent) => {\n if (eventData && eventData.points) {\n const selectedPointIds = eventData.points\n .map((p): string | number | null => {\n if (p.data.ids && p.pointIndex !== undefined) {\n const strId = p.data.ids[p.pointIndex] as string;\n // Restore the original ID type (string or number) via the lookup.\n return originalIdLookup.get(strId) ?? strId;\n }\n return null;\n })\n .filter((id: string | number | null): id is string | number => id !== null);\n\n // Get selection mode from keyboard state\n // Note: Plotly doesn't pass the original event, so we can't detect modifiers\n // For now, box/lasso selection always replaces\n const mode: SelectionMode = \"replace\";\n const newSelection = new Set<string | number>(selectedPointIds);\n\n if (!isControlledRef.current) {\n setInternalSelectedIds(newSelection);\n }\n onSelectionChangeRef.current?.(newSelection, mode);\n }\n });\n\n // Handle deselect (clicking on background)\n plotElement.on(\"plotly_deselect\", () => {\n const newSelection = new Set<string | number>();\n if (!isControlledRef.current) {\n setInternalSelectedIds(newSelection);\n }\n onSelectionChangeRef.current?.(newSelection, \"replace\");\n });\n }\n\n // Design-system tooltip driven by Plotly hover events\n if (tooltipEnabled && !nativeTooltip) {\n bindTooltip(currentRef);\n }\n\n // Capture ref value for cleanup\n drawnElement = currentRef;\n });\n\n return () => {\n cancelled = true;\n if (drawnElement) {\n getLoadedPlotly().purge(drawnElement);\n }\n };\n }, [\n processedData,\n markerConfig,\n xAxis,\n yAxis,\n xRange,\n yRange,\n title,\n width,\n height,\n tooltip,\n tooltipText,\n enableClickSelection,\n enableBoxSelection,\n enableLassoSelection,\n originalIdLookup,\n tooltipEnabled,\n nativeTooltip,\n bindTooltip,\n theme,\n ]);\n\n // Apply selection state to Plotly\n useEffect(() => {\n if (!plotRef.current || processedData.length === 0) return;\n\n // Wait for the lazily-loaded Plotly module: the draw effect registers its\n // loadPlotly().then first, so by the time this callback runs the plot has\n // been drawn — preserving the original \"restyle right after newPlot\"\n // ordering on initial mount.\n let cancelled = false;\n void loadPlotly().then((plotly) => {\n const currentRef = plotRef.current;\n if (cancelled || !currentRef) return;\n // Guard: skip if the chart hasn't been drawn (e.g. the draw was cancelled).\n if (!(currentRef as { _fullLayout?: unknown })._fullLayout) return;\n\n const plotElement = currentRef as unknown as Plotly.PlotlyHTMLElement;\n\n // Find indices of selected points. Use the string-normalized set to match the string IDs Plotly stores\n const selectedIndices = processedData\n .map((point, index) => (normalizedSelectedIds.has(String(point.id)) ? index : null))\n .filter((index): index is number => index !== null);\n\n // Update Plotly selection\n if (selectedIndices.length > 0) {\n plotly.restyle(\n plotElement,\n {\n selectedpoints: [selectedIndices],\n },\n [0],\n );\n } else {\n plotly.restyle(\n plotElement,\n {\n selectedpoints: [null],\n },\n [0],\n );\n }\n });\n\n return () => {\n cancelled = true;\n };\n }, [normalizedSelectedIds, processedData]);\n\n const containerClassName = className\n ? `scatter-plot-interactive relative ${className}`\n : \"scatter-plot-interactive relative\";\n\n return (\n <div className={containerClassName}>\n <div ref={plotRef} className=\"scatter-plot-interactive__plot\" style={{ width, height }} />\n {tooltipElement}\n </div>\n );\n};\n\nexport { ScatterPlotInteractive };\n"],"names":["DEFAULT_AXIS_CONFIG","DEFAULT_TOOLTIP_CONFIG","ScatterPlotInteractive","data","title","xAxis","yAxis","colorMapping","shapeMapping","sizeMapping","tooltip","enableClickSelection","enableBoxSelection","enableLassoSelection","controlledSelectedIds","onSelectionChange","onPointClick","downsampling","width","height","showColorBar","className","plotRef","useRef","theme","usePlotlyTheme","onSelectionChangeRef","onPointClickRef","selectedIdsRef","isControlledRef","internalSelectedIds","setInternalSelectedIds","useState","isControlled","selectedIds","normalizedSelectedIds","useMemo","originalIdLookup","p","processedData","downsampleData","colors","mapColors","shapes","mapShapes","sizes","mapSizes","xRange","calculateAxisRange","PLOT_CONSTANTS","yRange","tooltipEnabled","nativeTooltip","tooltipText","point","generateTooltipContent","bindTooltip","tooltipElement","useChartTooltip","points","index","plotlyColors","value","plotlyColorscale","scale","DEFAULT_COLOR_SCALE","markerConfig","config","range","calculateRange","useEffect","currentRef","xValues","yValues","ids","plotData","COLORS","layout","getPlotlyLayoutConfig","cancelled","drawnElement","loadPlotly","plotly","plotElement","eventData","clickedId","clickedPoint","mode","getSelectionMode","newSelection","applySelection","selectedPointIds","strId","id","getLoadedPlotly","selectedIndices","containerClassName","jsxs","jsx"],"mappings":"qXA4BMA,GAAkC,CAAA,EAClCC,GAAwC,CAAE,QAAS,EAAA,EAuBnDC,GAAgE,CAAC,CACrE,KAAAC,EACA,MAAAC,EACA,MAAAC,EAAQL,GACR,MAAAM,EAAQN,GACR,aAAAO,EACA,aAAAC,EACA,YAAAC,EACA,QAAAC,EAAUT,GACV,qBAAAU,EAAuB,GACvB,mBAAAC,EAAqB,GACrB,qBAAAC,EAAuB,GACvB,YAAaC,EACb,kBAAAC,EACA,aAAAC,EACA,aAAAC,EACA,MAAAC,EAAQ,IACR,OAAAC,EAAS,IACT,aAAAC,EAAe,GACf,UAAAC,CACF,IAAM,CACJ,MAAMC,EAAUC,EAAAA,OAAuB,IAAI,EACrCC,EAAQC,GAAAA,eAAA,EACRC,EAAuBH,EAAAA,OAAOR,CAAiB,EAC/CY,EAAkBJ,EAAAA,OAAOP,CAAY,EACrCY,EAAiBL,EAAAA,OAA6B,IAAI,GAAK,EACvDM,EA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QACLC,EACA,CACE,eAAgB,CAAC,IAAI,CAAA,EAEvB,CAAC,CAAC,CAAA,CAGR,CAAC,EAEM,IAAM,CACXJ,EAAY,EACd,CACF,EAAG,CAAC5C,GAAuBI,CAAa,CAAC,EAEzC,MAAMyD,GAAqB3E,EACvB,qCAAqCA,CAAS,GAC9C,oCAEJ,OACE4E,GAAAA,KAAC,MAAA,CAAI,UAAWD,GACd,SAAA,CAAAE,GAAAA,IAAC,MAAA,CAAI,IAAK5E,EAAS,UAAU,iCAAiC,MAAO,CAAE,MAAAJ,EAAO,OAAAC,CAAA,CAAO,CAAG,EACvFsC,EAAA,EACH,CAEJ"}
|
|
1
|
+
{"version":3,"file":"ScatterPlotInteractive.cjs","sources":["../../../../src/components/charts/ScatterPlotInteractive/ScatterPlotInteractive.tsx"],"sourcesContent":["import React, { useEffect, useMemo, useRef, useState } from \"react\";\n\nimport { useChartTooltip } from \"../ChartTooltip\";\nimport { getLoadedPlotly, loadPlotly } from \"../plotly-loader\";\n\nimport { COLORS, DEFAULT_COLOR_SCALE, PLOT_CONSTANTS } from \"./constants\";\nimport {\n applySelection,\n calculateAxisRange,\n calculateRange,\n downsampleData,\n generateTooltipContent,\n getPlotlyLayoutConfig,\n getSelectionMode,\n mapColors,\n mapShapes,\n mapSizes,\n} from \"./utils\";\n\nimport type { AxisConfig, ScatterPlotInteractiveProps, SelectionMode, TooltipConfig } from \"./types\";\nimport type Plotly from \"plotly.js-dist\";\n\nimport { usePlotlyTheme } from \"@/hooks/use-plotly-theme\";\n\n// Stable default prop objects — inline defaults would create a new identity\n// on every render, retriggering the plot effect (and tearing down the\n// tooltip) whenever internal state changes\nconst DEFAULT_AXIS_CONFIG: AxisConfig = {};\nconst DEFAULT_TOOLTIP_CONFIG: TooltipConfig = { enabled: true };\n\n/**\n * ScatterPlotInteractive component for visualizing scatter plot data with advanced interactions.\n *\n * **Features:**\n * - Data-driven and static styling (color, shape, size)\n * - Interactive selection (click, box, lasso)\n * - Keyboard modifiers for click-selection modes (Shift/Ctrl)\n * - Customizable tooltips with rich content support\n * - Axis customization (ranges, log/linear scales)\n * - Performance optimizations for large datasets\n * - Selection propagation via callbacks\n *\n * **Selection Modes (click selection only):**\n * - Default click: Replace selection\n * - Shift + click: Add to selection\n * - Ctrl/Cmd + click: Remove from selection\n * - Shift + Ctrl + click: Toggle selection\n *\n * Box/lasso selection always replaces the current selection because\n * Plotly does not expose the original keyboard event for drag operations.\n */\nconst ScatterPlotInteractive: React.FC<ScatterPlotInteractiveProps> = ({\n data,\n title,\n xAxis = DEFAULT_AXIS_CONFIG,\n yAxis = DEFAULT_AXIS_CONFIG,\n colorMapping,\n shapeMapping,\n sizeMapping,\n tooltip = DEFAULT_TOOLTIP_CONFIG,\n enableClickSelection = true,\n enableBoxSelection = true,\n enableLassoSelection = true,\n selectedIds: controlledSelectedIds,\n onSelectionChange,\n onPointClick,\n downsampling,\n width = 800,\n height = 600,\n showColorBar = true,\n className,\n}) => {\n const plotRef = useRef<HTMLDivElement>(null);\n const theme = usePlotlyTheme();\n const onSelectionChangeRef = useRef(onSelectionChange);\n const onPointClickRef = useRef(onPointClick);\n const selectedIdsRef = useRef<Set<string | number>>(new Set());\n const isControlledRef = useRef(false);\n\n // Keep refs updated\n onSelectionChangeRef.current = onSelectionChange;\n onPointClickRef.current = onPointClick;\n\n // Internal selection state (only used in uncontrolled mode)\n const [internalSelectedIds, setInternalSelectedIds] = useState<Set<string | number>>(new Set());\n\n // Use controlled or uncontrolled selection\n const isControlled = controlledSelectedIds !== undefined;\n const selectedIds = isControlled ? controlledSelectedIds : internalSelectedIds;\n selectedIdsRef.current = selectedIds;\n isControlledRef.current = isControlled;\n\n // Normalize to strings so numeric IDs passed by consumers always match the\n // string IDs that Plotly stores (we always do String(p.id) when building the trace).\n const normalizedSelectedIds = useMemo(() => new Set([...selectedIds].map(String)), [selectedIds]);\n\n // Reverse-lookup: Plotly string ID → original (possibly numeric) ScatterPoint ID.\n // Used to restore original ID types when echoing selections back to consumers.\n const originalIdLookup = useMemo(() => new Map(data.map((p) => [String(p.id), p.id])), [data]);\n\n // Apply downsampling if configured\n const processedData = useMemo(() => {\n if (!downsampling) {\n return data;\n }\n return downsampleData(data, downsampling);\n }, [data, downsampling]);\n\n // Map colors, shapes, and sizes based on configuration\n const colors = useMemo(() => mapColors(processedData, colorMapping), [processedData, colorMapping]);\n\n const shapes = useMemo(() => mapShapes(processedData, shapeMapping), [processedData, shapeMapping]);\n\n const sizes = useMemo(() => mapSizes(processedData, sizeMapping), [processedData, sizeMapping]);\n\n // Calculate axis ranges\n const xRange = useMemo(() => {\n if (xAxis.range) return xAxis.range;\n if (xAxis.autoRange === false) return;\n return calculateAxisRange(processedData, \"x\", xAxis.autoRangePadding ?? PLOT_CONSTANTS.AUTO_RANGE_PADDING, xAxis.scale);\n }, [processedData, xAxis]);\n\n const yRange = useMemo(() => {\n if (yAxis.range) return yAxis.range;\n if (yAxis.autoRange === false) return;\n return calculateAxisRange(processedData, \"y\", yAxis.autoRangePadding ?? PLOT_CONSTANTS.AUTO_RANGE_PADDING, yAxis.scale);\n }, [processedData, yAxis]);\n\n const tooltipEnabled = tooltip.enabled !== false;\n const nativeTooltip = tooltip.native === true;\n\n // Build tooltip text\n const tooltipText = useMemo(() => {\n if (!tooltipEnabled) return [];\n\n return processedData.map((point) =>\n tooltip.content ? tooltip.content(point) : generateTooltipContent(point, tooltip.fields),\n );\n }, [processedData, tooltip, tooltipEnabled]);\n\n // Design-system tooltip driven by Plotly hover events\n const { bindTooltip, tooltipElement } = useChartTooltip({\n getLines: (points) => {\n const index = points[0]?.pointIndex;\n if (index === undefined) return [];\n return (tooltipText[index] ?? \"\").split(\"<br>\").filter(Boolean);\n },\n });\n\n // Prepare Plotly-compatible color data\n const plotlyColors = useMemo(() => {\n if (colorMapping?.type === \"continuous\" && colorMapping.field && processedData.length > 0) {\n // For continuous mapping, extract the numeric values\n return processedData.map((point) => {\n const value = point.metadata?.[colorMapping.field!];\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n });\n }\n return colors;\n }, [processedData, colorMapping, colors]);\n\n // Build colorscale for continuous mapping\n const plotlyColorscale = useMemo(() => {\n if (colorMapping?.type === \"continuous\") {\n const scale = colorMapping.colorScale || DEFAULT_COLOR_SCALE;\n return typeof scale === \"string\" ? scale : scale;\n }\n }, [colorMapping]);\n\n // Build marker configuration for Plotly\n const markerConfig = useMemo((): Partial<Plotly.PlotMarker> => {\n const config: Partial<Plotly.PlotMarker> = {\n size: sizes,\n symbol: shapes,\n // Points carry no outline — a flat fill (SW-2298 dropped the earlier CSS\n // drop-shadow). Selected points re-add a line below.\n line: {\n width: 0,\n },\n };\n\n // Configure color mapping\n if (colorMapping?.type === \"continuous\" && plotlyColorscale) {\n config.color = plotlyColors as number[];\n config.colorscale = plotlyColorscale;\n config.showscale = showColorBar;\n\n if (colorMapping.field) {\n const range =\n colorMapping.min !== undefined && colorMapping.max !== undefined\n ? { min: colorMapping.min, max: colorMapping.max }\n : calculateRange(processedData, colorMapping.field);\n config.cmin = range.min;\n config.cmax = range.max;\n config.colorbar = {\n title: { text: colorMapping.field, side: \"right\" },\n thickness: 20,\n len: 0.7,\n };\n }\n } else {\n config.color = colors;\n }\n\n return config;\n }, [sizes, shapes, colorMapping, plotlyColorscale, plotlyColors, showColorBar, processedData, colors]);\n\n // Create Plotly plot\n useEffect(() => {\n const currentRef = plotRef.current;\n if (!currentRef || processedData.length === 0) return;\n\n const xValues = processedData.map((p) => p.x);\n const yValues = processedData.map((p) => p.y);\n const ids = processedData.map((p) => String(p.id));\n\n // Create base trace\n const trace: Partial<Plotly.PlotData> & {\n unselected?: { marker?: { opacity?: number } };\n selected?: { marker?: { opacity?: number; line?: { color?: string; width?: number } } };\n } = {\n x: xValues,\n y: yValues,\n ids,\n mode: \"markers\",\n type: \"scatter\",\n marker: markerConfig,\n // \"none\" keeps hover events firing for the HTML tooltip without\n // showing Plotly's hover label; \"skip\" disables hover entirely\n hoverinfo: tooltipEnabled ? (nativeTooltip ? \"text\" : \"none\") : \"skip\",\n text: tooltipText,\n hovertemplate: tooltipEnabled && nativeTooltip ? \"%{text}<extra></extra>\" : undefined,\n showlegend: false,\n unselected: {\n marker: {\n opacity: 0.3,\n },\n },\n selected: {\n marker: {\n opacity: 1,\n line: {\n color: COLORS.selected,\n width: 2,\n },\n },\n },\n };\n\n const plotData: Plotly.Data[] = [trace as Plotly.Data];\n\n // Configure layout\n const layout: Partial<Plotly.Layout> = getPlotlyLayoutConfig({\n title,\n xAxis,\n yAxis,\n width,\n height,\n xRange,\n yRange,\n enableLassoSelection,\n enableBoxSelection,\n theme,\n });\n\n const config: Partial<Plotly.Config> = {\n responsive: true,\n displayModeBar: true,\n displaylogo: false,\n modeBarButtonsToAdd: [],\n modeBarButtonsToRemove: [\"toImage\"],\n };\n\n // Add selection mode buttons if enabled\n if (enableBoxSelection) {\n config.modeBarButtonsToAdd?.push(\"select2d\" as never);\n }\n if (enableLassoSelection) {\n config.modeBarButtonsToAdd?.push(\"lasso2d\" as never);\n }\n\n // Plotly is loaded lazily so it stays out of the consumer's main chunk\n // (SW-2007); the draw is skipped if the effect re-runs or unmounts first.\n let cancelled = false;\n let drawnElement: HTMLDivElement | null = null;\n void loadPlotly().then((plotly) => {\n if (cancelled || !plotRef.current) return;\n plotly.newPlot(currentRef, plotData, layout, config);\n\n // Attach event handlers\n const plotElement = currentRef as unknown as Plotly.PlotlyHTMLElement;\n\n // Handle point click\n if (enableClickSelection) {\n plotElement.on(\"plotly_click\", (eventData: Plotly.PlotMouseEvent) => {\n const point = eventData.points[0];\n if (point && point.data.ids) {\n const clickedId = point.data.ids[point.pointIndex];\n const clickedPoint = processedData.find((p) => String(p.id) === clickedId);\n\n if (clickedPoint) {\n // Call point click handler if provided\n onPointClickRef.current?.(clickedPoint, eventData.event as MouseEvent);\n\n // Handle selection. Use the original-typed ID from the matched point so\n // numeric IDs (e.g., 123) are preserved instead of being coerced to \"123\".\n const mode = getSelectionMode(eventData.event as MouseEvent);\n const newSelection = applySelection(selectedIdsRef.current, new Set([clickedPoint.id]), mode);\n\n if (!isControlledRef.current) {\n setInternalSelectedIds(newSelection);\n }\n onSelectionChangeRef.current?.(newSelection, mode);\n }\n }\n });\n }\n\n // Handle box/lasso selection\n if (enableBoxSelection || enableLassoSelection) {\n plotElement.on(\"plotly_selected\", (eventData: Plotly.PlotSelectionEvent) => {\n if (eventData && eventData.points) {\n const selectedPointIds = eventData.points\n .map((p): string | number | null => {\n if (p.data.ids && p.pointIndex !== undefined) {\n const strId = p.data.ids[p.pointIndex] as string;\n // Restore the original ID type (string or number) via the lookup.\n return originalIdLookup.get(strId) ?? strId;\n }\n return null;\n })\n .filter((id: string | number | null): id is string | number => id !== null);\n\n // Get selection mode from keyboard state\n // Note: Plotly doesn't pass the original event, so we can't detect modifiers\n // For now, box/lasso selection always replaces\n const mode: SelectionMode = \"replace\";\n const newSelection = new Set<string | number>(selectedPointIds);\n\n if (!isControlledRef.current) {\n setInternalSelectedIds(newSelection);\n }\n onSelectionChangeRef.current?.(newSelection, mode);\n }\n });\n\n // Handle deselect (clicking on background)\n plotElement.on(\"plotly_deselect\", () => {\n const newSelection = new Set<string | number>();\n if (!isControlledRef.current) {\n setInternalSelectedIds(newSelection);\n }\n onSelectionChangeRef.current?.(newSelection, \"replace\");\n });\n }\n\n // Design-system tooltip driven by Plotly hover events\n if (tooltipEnabled && !nativeTooltip) {\n bindTooltip(currentRef);\n }\n\n // Capture ref value for cleanup\n drawnElement = currentRef;\n });\n\n return () => {\n cancelled = true;\n if (drawnElement) {\n getLoadedPlotly().purge(drawnElement);\n }\n };\n }, [\n processedData,\n markerConfig,\n xAxis,\n yAxis,\n xRange,\n yRange,\n title,\n width,\n height,\n tooltip,\n tooltipText,\n enableClickSelection,\n enableBoxSelection,\n enableLassoSelection,\n originalIdLookup,\n tooltipEnabled,\n nativeTooltip,\n bindTooltip,\n theme,\n ]);\n\n // Apply selection state to Plotly\n useEffect(() => {\n if (!plotRef.current || processedData.length === 0) return;\n\n // Wait for the lazily-loaded Plotly module: the draw effect registers its\n // loadPlotly().then first, so by the time this callback runs the plot has\n // been drawn — preserving the original \"restyle right after newPlot\"\n // ordering on initial mount.\n let cancelled = false;\n void loadPlotly().then((plotly) => {\n const currentRef = plotRef.current;\n if (cancelled || !currentRef) return;\n // Guard: skip if the chart hasn't been drawn (e.g. the draw was cancelled).\n if (!(currentRef as { _fullLayout?: unknown })._fullLayout) return;\n\n const plotElement = currentRef as unknown as Plotly.PlotlyHTMLElement;\n\n // Find indices of selected points. Use the string-normalized set to match the string IDs Plotly stores\n const selectedIndices = processedData\n .map((point, index) => (normalizedSelectedIds.has(String(point.id)) ? index : null))\n .filter((index): index is number => index !== null);\n\n // Update Plotly selection\n if (selectedIndices.length > 0) {\n plotly.restyle(\n plotElement,\n {\n selectedpoints: [selectedIndices],\n },\n [0],\n );\n } else {\n plotly.restyle(\n plotElement,\n {\n selectedpoints: [null],\n },\n [0],\n );\n }\n });\n\n return () => {\n cancelled = true;\n };\n }, [normalizedSelectedIds, processedData]);\n\n const containerClassName = className\n ? `scatter-plot-interactive relative ${className}`\n : \"scatter-plot-interactive relative\";\n\n return (\n <div className={containerClassName}>\n <div ref={plotRef} className=\"scatter-plot-interactive__plot\" style={{ width, height }} />\n {tooltipElement}\n </div>\n );\n};\n\nexport { ScatterPlotInteractive };\n"],"names":["DEFAULT_AXIS_CONFIG","DEFAULT_TOOLTIP_CONFIG","ScatterPlotInteractive","data","title","xAxis","yAxis","colorMapping","shapeMapping","sizeMapping","tooltip","enableClickSelection","enableBoxSelection","enableLassoSelection","controlledSelectedIds","onSelectionChange","onPointClick","downsampling","width","height","showColorBar","className","plotRef","useRef","theme","usePlotlyTheme","onSelectionChangeRef","onPointClickRef","selectedIdsRef","isControlledRef","internalSelectedIds","setInternalSelectedIds","useState","isControlled","selectedIds","normalizedSelectedIds","useMemo","originalIdLookup","p","processedData","downsampleData","colors","mapColors","shapes","mapShapes","sizes","mapSizes","xRange","calculateAxisRange","PLOT_CONSTANTS","yRange","tooltipEnabled","nativeTooltip","tooltipText","point","generateTooltipContent","bindTooltip","tooltipElement","useChartTooltip","points","index","plotlyColors","value","plotlyColorscale","scale","DEFAULT_COLOR_SCALE","markerConfig","config","range","calculateRange","useEffect","currentRef","xValues","yValues","ids","plotData","COLORS","layout","getPlotlyLayoutConfig","cancelled","drawnElement","loadPlotly","plotly","plotElement","eventData","clickedId","clickedPoint","mode","getSelectionMode","newSelection","applySelection","selectedPointIds","strId","id","getLoadedPlotly","selectedIndices","containerClassName","jsxs","jsx"],"mappings":"kUA2BMA,GAAkC,CAAA,EAClCC,GAAwC,CAAE,QAAS,EAAA,EAuBnDC,GAAgE,CAAC,CACrE,KAAAC,EACA,MAAAC,EACA,MAAAC,EAAQL,GACR,MAAAM,EAAQN,GACR,aAAAO,EACA,aAAAC,EACA,YAAAC,EACA,QAAAC,EAAUT,GACV,qBAAAU,EAAuB,GACvB,mBAAAC,EAAqB,GACrB,qBAAAC,EAAuB,GACvB,YAAaC,EACb,kBAAAC,EACA,aAAAC,EACA,aAAAC,EACA,MAAAC,EAAQ,IACR,OAAAC,EAAS,IACT,aAAAC,EAAe,GACf,UAAAC,CACF,IAAM,CACJ,MAAMC,EAAUC,EAAAA,OAAuB,IAAI,EACrCC,EAAQC,GAAAA,eAAA,EACRC,EAAuBH,EAAAA,OAAOR,CAAiB,EAC/CY,EAAkBJ,EAAAA,OAAOP,CAAY,EACrCY,EAAiBL,EAAAA,OAA6B,IAAI,GAAK,EACvDM,EAAkBN,EAAAA,OAAO,EAAK,EAGpCG,EAAqB,QAAUX,EAC/BY,EAAgB,QAAUX,EAG1B,KAAM,CAACc,GAAqBC,CAAsB,EAAIC,EAAAA,SAA+B,IAAI,GAAK,EAGxFC,GAAenB,IAA0B,OACzCoB,EAAcD,GAAenB,EAAwBgB,GAC3DF,EAAe,QAAUM,EACzBL,EAAgB,QAAUI,GAI1B,MAAME,GAAwBC,EAAAA,QAAQ,IAAM,IAAI,IAAI,CAAC,G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E,EAAS,UAAU,iCAAiC,MAAO,CAAE,MAAAJ,EAAO,OAAAC,CAAA,CAAO,CAAG,EACvFsC,EAAA,EACH,CAEJ"}
|
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
import { jsxs as ve, jsx as Re } from "react/jsx-runtime";
|
|
2
2
|
import { useRef as S, useState as Se, useMemo as o, useEffect as de } from "react";
|
|
3
|
-
/* empty css */
|
|
4
3
|
import { useChartTooltip as Te } from "../ChartTooltip/ChartTooltip.js";
|
|
5
4
|
import { loadPlotly as ue, getLoadedPlotly as ge } from "../plotly-loader.js";
|
|
6
5
|
import { PLOT_CONSTANTS as ae, DEFAULT_COLOR_SCALE as _e, COLORS as he } from "./constants.js";
|
|
7
6
|
import { downsampleData as Ce, mapColors as Pe, mapShapes as we, mapSizes as Ee, calculateAxisRange as fe, generateTooltipContent as Oe, calculateRange as Ne, getPlotlyLayoutConfig as ke, getSelectionMode as Le, applySelection as Be } from "./utils.js";
|
|
8
7
|
import { usePlotlyTheme as De } from "../../../hooks/use-plotly-theme.js";
|
|
9
|
-
const me = {}, Fe = { enabled: !0 },
|
|
8
|
+
const me = {}, Fe = { enabled: !0 }, Ve = ({
|
|
10
9
|
data: p,
|
|
11
10
|
title: x,
|
|
12
11
|
xAxis: l = me,
|
|
@@ -58,8 +57,8 @@ const me = {}, Fe = { enabled: !0 }, Xe = ({
|
|
|
58
57
|
const e = {
|
|
59
58
|
size: ne,
|
|
60
59
|
symbol: te,
|
|
61
|
-
// Points carry no outline
|
|
62
|
-
//
|
|
60
|
+
// Points carry no outline — a flat fill (SW-2298 dropped the earlier CSS
|
|
61
|
+
// drop-shadow). Selected points re-add a line below.
|
|
63
62
|
line: {
|
|
64
63
|
width: 0
|
|
65
64
|
}
|
|
@@ -210,6 +209,6 @@ const me = {}, Fe = { enabled: !0 }, Xe = ({
|
|
|
210
209
|
] });
|
|
211
210
|
};
|
|
212
211
|
export {
|
|
213
|
-
|
|
212
|
+
Ve as ScatterPlotInteractive
|
|
214
213
|
};
|
|
215
214
|
//# sourceMappingURL=ScatterPlotInteractive.js.map
|