@tetrascience-npm/tetrascience-react-ui 1.0.0-beta.146.1 → 1.0.0-beta.148.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/Electropherogram/Electropherogram.cjs +1 -1
- package/dist/components/charts/Electropherogram/Electropherogram.cjs.map +1 -1
- package/dist/components/charts/Electropherogram/Electropherogram.js +30 -30
- 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/ui/tree.d.ts +1 -1
- 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/dist/ui/tree.cjs +1 -1
- package/dist/ui/tree.cjs.map +1 -1
- package/dist/ui/tree.js +350 -205
- package/dist/ui/tree.js.map +1 -1
- package/package.json +8 -2
package/README.md
CHANGED
|
@@ -135,16 +135,35 @@ This library uses **Tailwind CSS 4** with design tokens defined as CSS custom pr
|
|
|
135
135
|
|
|
136
136
|
### CSS Import Options
|
|
137
137
|
|
|
138
|
-
| Import path | Use case
|
|
139
|
-
| ------------------------------------------------------------ |
|
|
140
|
-
| `@tetrascience-npm/tetrascience-react-ui/index.css` | **Pre-built CSS** —
|
|
141
|
-
| `@tetrascience-npm/tetrascience-react-ui/index.tailwind.css` | **Tailwind source** — for apps that run their own Tailwind build and want to extend/override tokens.
|
|
142
|
-
|
|
143
|
-
|
|
138
|
+
| Import path | Use case |
|
|
139
|
+
| ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
140
|
+
| `@tetrascience-npm/tetrascience-react-ui/index.css` | **Pre-built CSS** — for an app that owns its document. Import once at your app root. |
|
|
141
|
+
| `@tetrascience-npm/tetrascience-react-ui/index.tailwind.css` | **Tailwind source** — for apps that run their own Tailwind build and want to extend/override tokens. |
|
|
142
|
+
| `@tetrascience-npm/tetrascience-react-ui/index.scoped.css` | **Scoped CSS** — for code that renders inside a document it does _not_ own (a microfrontend remote, an embedded widget). See [Embedding in a host page](#embedding-in-a-host-page). |
|
|
143
|
+
|
|
144
|
+
Most consumers only need `index.css`.
|
|
145
|
+
|
|
146
|
+
#### What the stylesheet does — and does not — claim
|
|
147
|
+
|
|
148
|
+
Every selector rule the kit writes itself — its design tokens and its component CSS — ships
|
|
149
|
+
inside a `ts-ui-kit` cascade layer, and no published stylesheet contains an unlayered rule.
|
|
150
|
+
(Tailwind utilities land in Tailwind's `utilities` layer; `@font-face`, `@keyframes` and
|
|
151
|
+
`@property` are not selector-matched and stay top-level, with kit keyframes `ts-`-prefixed.)
|
|
152
|
+
That has two consequences worth knowing:
|
|
153
|
+
|
|
154
|
+
- **Your CSS always wins.** An unlayered rule outranks a layered one regardless of specificity or
|
|
155
|
+
load order, so a plain `:root { --primary: … }` in your app overrides the kit's token whether it
|
|
156
|
+
is written before or after the import. There is no ordering dance.
|
|
157
|
+
- **The kit never restyles your page by accident.** Its component class names are namespaced
|
|
158
|
+
(`.histogram-legend-divider`, `.platemap-legend__item`, …), and its tokens and Tailwind's
|
|
159
|
+
preflight reset are layered beneath anything you write. A CI gate
|
|
160
|
+
(`yarn check:css-leaks`) fails the build if any published stylesheet regains an unlayered rule.
|
|
144
161
|
|
|
145
162
|
### Theming
|
|
146
163
|
|
|
147
|
-
The design system is controlled via CSS custom properties
|
|
164
|
+
The design system is controlled via CSS custom properties. Override them anywhere in your own CSS
|
|
165
|
+
to customise colours, spacing, and radii — because the kit's tokens are layered, your unlayered
|
|
166
|
+
declaration wins in any order:
|
|
148
167
|
|
|
149
168
|
```css
|
|
150
169
|
:root {
|
|
@@ -156,6 +175,45 @@ The design system is controlled via CSS custom properties in `index.css`. Overri
|
|
|
156
175
|
|
|
157
176
|
Dark mode is supported via the `.dark` class on a parent element. See [THEMING.md](./THEMING.md) for details.
|
|
158
177
|
|
|
178
|
+
### Embedding in a host page
|
|
179
|
+
|
|
180
|
+
`index.css` is written for an app that owns its document: tokens on `:root` / `.dark`, Tailwind's
|
|
181
|
+
preflight on `html` / `body` / `*`. Inside someone else's document — a Module Federation remote
|
|
182
|
+
mounted into the TetraScience platform shell, a widget dropped into a legacy page — those are not
|
|
183
|
+
the kit's claims to make, even layered: a host that never declared `--surface-bright` would still
|
|
184
|
+
pick the kit's value up document-wide.
|
|
185
|
+
|
|
186
|
+
`index.scoped.css` is the same stylesheet with every rule in the `ts-ui-kit` and `base` layers
|
|
187
|
+
— tokens, component CSS, preflight — confined to an element carrying `data-ts-ui-root`. Import
|
|
188
|
+
it instead of `index.css` and mark your shell:
|
|
189
|
+
|
|
190
|
+
```tsx
|
|
191
|
+
import "@tetrascience-npm/tetrascience-react-ui/index.scoped.css";
|
|
192
|
+
|
|
193
|
+
export function App() {
|
|
194
|
+
return (
|
|
195
|
+
<div data-ts-ui-root className="dark">
|
|
196
|
+
{/* kit components render with their own tokens and reset in here… */}
|
|
197
|
+
</div>
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
Two things to know when you use it:
|
|
203
|
+
|
|
204
|
+
- **Portaled surfaces need the marker too.** `Dialog`, `Popover`, `Select`, `Tooltip` and the
|
|
205
|
+
other overlay components render their content into `document.body`, outside your shell. Put
|
|
206
|
+
`data-ts-ui-root` on their `*Content` element as well (a thin wrapper component around each one
|
|
207
|
+
you use is the usual pattern), or they render with the host's tokens instead of the kit's.
|
|
208
|
+
- **Dark mode still keys off `.dark`.** `.dark` on `<html>` (or anything above the marker), on the
|
|
209
|
+
marked element itself, or on a dark panel nested inside a light shell all work — the scoped
|
|
210
|
+
rules are emitted as `.dark [data-ts-ui-root]`, `[data-ts-ui-root].dark` and
|
|
211
|
+
`[data-ts-ui-root] .dark`.
|
|
212
|
+
|
|
213
|
+
Tailwind's own `theme`, `properties`, `components` and `utilities` layers are left global in the
|
|
214
|
+
scoped build: they are keyed on Tailwind class names, your unlayered CSS already outranks them,
|
|
215
|
+
and confining `theme` would strip `--spacing` / `--radius-*` from portaled content.
|
|
216
|
+
|
|
159
217
|
## Components
|
|
160
218
|
|
|
161
219
|
### UI Primitives (`ui/`)
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l=require("react/jsx-runtime"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l=require("react/jsx-runtime"),o=require("react"),$=require("../ChartTooltip/ChartTooltip.cjs"),E=require("../plotly-loader.cjs"),w=require("../../../hooks/use-plotly-theme.cjs"),b=require("../../../utils/colors.cjs");;/* empty css */const D=75,I=1.05,V=e=>{if(e.base!==void 0)return e.base;const a={A:e.peakA,T:e.peakT,G:e.peakG,C:e.peakC},m=Object.values(a);if(m.every(c=>c===m[0]))return"";let h="",f=0;return Object.entries(a).forEach(([c,g])=>{g>f&&(h=c,f=g)}),h},z=({data:e=[],width:a=900,height:m=600,positionInterval:y=10,colorA:h=b.CHART_COLORS[0],colorT:f=b.CHART_COLORS[2],colorG:c=b.CHART_COLORS[3],colorC:g=b.CHART_COLORS[1]})=>{const d=o.useRef(null),T=w.usePlotlyTheme(),{bindTooltip:O,tooltipElement:H}=$.useChartTooltip({xLabel:"Position",yLabel:"Intensity"}),s=o.useMemo(()=>e.map(t=>t.position),[e]),F=o.useMemo(()=>e.map(t=>V(t)),[e]),M=o.useMemo(()=>e.map(t=>t.peakA),[e]),P=o.useMemo(()=>e.map(t=>t.peakT),[e]),v=o.useMemo(()=>e.map(t=>t.peakG),[e]),C=o.useMemo(()=>e.map(t=>t.peakC),[e]),R=o.useMemo(()=>({x:s,y:M,type:"scatter",mode:"lines",hoverinfo:"none",name:"A",line:{color:h,width:2,shape:"spline"}}),[s,M,h]),_=o.useMemo(()=>({x:s,y:P,type:"scatter",mode:"lines",hoverinfo:"none",name:"T",line:{color:f,width:2,shape:"spline"}}),[s,P,f]),j=o.useMemo(()=>({x:s,y:v,type:"scatter",mode:"lines",hoverinfo:"none",name:"G",line:{color:c,width:2,shape:"spline"}}),[s,v,c]),A=o.useMemo(()=>({x:s,y:C,type:"scatter",mode:"lines",hoverinfo:"none",name:"C",line:{color:g,width:2,shape:"spline"}}),[s,C,g]),L=o.useMemo(()=>Math.max(...M,...P,...v,...C),[M,P,v,C]);if(o.useEffect(()=>{if(!d.current||e.length===0)return;const t=[R,_,j,A],k={width:a,height:m-D,margin:{l:0,r:0,b:20,t:10,pad:0},paper_bgcolor:T.paperBg,plot_bgcolor:T.plotBg,font:{family:w.CHART_FONT_FAMILY},showlegend:!1,xaxis:{showgrid:!1,zeroline:!1,showticklabels:!1,showline:!1,range:[Math.min(...s),Math.max(...s)],fixedrange:!0},yaxis:{showgrid:!1,zeroline:!1,showticklabels:!1,showline:!1,range:[0,L*I],fixedrange:!0}},i={responsive:!0,displayModeBar:!1,displaylogo:!1,fillFrame:!0};let p=!1,u=null;return E.loadPlotly().then(r=>{p||!d.current||(r.newPlot(d.current,t,k,i),O(d.current),u=d.current)}),()=>{p=!0,u&&E.getLoadedPlotly().purge(u)}},[e,a,m,R,_,j,A,L,s,T,O]),e.length===0)return l.jsx("div",{className:"electropherogram-empty",children:"No data available"});const G=()=>{const t=()=>{const i=Math.min(...s),p=Math.max(...s),u=a;return l.jsx("div",{className:"electropherogram-sequence-letters",children:F.map((r,x)=>{const n=s[x],q=r==="A"?h:r==="T"?f:r==="G"?c:r==="C"?g:T.textColor,N=p-i||1,B=(n-i)/N*u;return l.jsx("span",{className:"electropherogram-sequence-letter",style:{left:`${B}px`,color:q},children:r},`base-${x}`)})})},k=()=>{const i=Math.min(...s),p=Math.max(...s),u=a,r=Math.ceil(i/y)*y,x=[];for(let n=r;n<=p;n+=y)x.push({position:n,label:n.toString()});return l.jsx("div",{className:"electropherogram-position-numbers",children:x.map(n=>{const q=p-i||1,S=(n.position-i)/q*u;return l.jsx("span",{className:"electropherogram-position-number",style:{left:`${S}px`},children:n.label},`pos-${n.position}`)})})};return l.jsxs("div",{className:"electropherogram-sequence-header",children:[t(),k()]})};return l.jsxs("div",{className:"electropherogram-container relative",style:{width:a,height:m},children:[G(),l.jsx("div",{className:"electropherogram-chart",children:l.jsx("div",{ref:d,style:{width:"100%",height:"100%"}})}),H]})};exports.Electropherogram=z;
|
|
2
2
|
//# sourceMappingURL=Electropherogram.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Electropherogram.cjs","sources":["../../../../src/components/charts/Electropherogram/Electropherogram.tsx"],"sourcesContent":["import React, { useEffect, useRef, useMemo } from \"react\";\n\nimport { useChartTooltip } from \"../ChartTooltip\";\nimport { getLoadedPlotly, loadPlotly } from \"../plotly-loader\";\n\nimport type Plotly from \"plotly.js-dist\";\n\nimport { CHART_FONT_FAMILY, usePlotlyTheme } from \"@/hooks/use-plotly-theme\";\nimport { CHART_COLORS } from \"@/utils/colors\";\nimport \"./Electropherogram.scss\";\n\n/** Height offset for the plot area in pixels */\nconst PLOT_HEIGHT_OFFSET = 75;\n/** Scale factor for y-axis range to add padding above max value */\nconst Y_AXIS_PADDING_FACTOR = 1.05;\n\ninterface PeakData {\n position: number;\n base?: string;\n peakA: number;\n peakT: number;\n peakG: number;\n peakC: number;\n}\n\ninterface ElectropherogramProps {\n data?: PeakData[];\n width?: number;\n height?: number;\n positionInterval?: number;\n colorA?: string;\n colorT?: string;\n colorG?: string;\n colorC?: string;\n}\n\nconst determineBase = (item: PeakData): string => {\n if (item.base !== undefined) return item.base;\n const peakValues = {\n A: item.peakA,\n T: item.peakT,\n G: item.peakG,\n C: item.peakC,\n };\n\n const values = Object.values(peakValues);\n const allEqual = values.every((val) => val === values[0]);\n\n if (allEqual) {\n return \"\";\n }\n\n let highestBase = \"\";\n let highestValue = 0;\n\n Object.entries(peakValues).forEach(([base, value]) => {\n if (value > highestValue) {\n highestBase = base;\n highestValue = value;\n }\n });\n\n return highestBase;\n};\n\nconst Electropherogram: React.FC<ElectropherogramProps> = ({\n data = [],\n width = 900,\n height = 600,\n positionInterval = 10,\n colorA = CHART_COLORS[0], // blue\n colorT = CHART_COLORS[2], // teal/green\n colorG = CHART_COLORS[3], // red\n colorC = CHART_COLORS[1], // orange\n}) => {\n const plotRef = useRef<HTMLDivElement>(null);\n const theme = usePlotlyTheme();\n const { bindTooltip, tooltipElement } = useChartTooltip({\n xLabel: \"Position\",\n yLabel: \"Intensity\",\n });\n\n const positions = useMemo(() => data.map((item) => item.position), [data]);\n const sequence = useMemo(() => data.map((item) => determineBase(item)), [data]);\n const peakA = useMemo(() => data.map((item) => item.peakA), [data]);\n const peakT = useMemo(() => data.map((item) => item.peakT), [data]);\n const peakG = useMemo(() => data.map((item) => item.peakG), [data]);\n const peakC = useMemo(() => data.map((item) => item.peakC), [data]);\n\n const aTrace = useMemo(\n () => ({\n x: positions,\n y: peakA,\n type: \"scatter\" as const,\n mode: \"lines\" as const,\n hoverinfo: \"none\" as const,\n name: \"A\",\n line: { color: colorA, width: 2, shape: \"spline\" as const },\n }),\n [positions, peakA, colorA],\n );\n\n const tTrace = useMemo(\n () => ({\n x: positions,\n y: peakT,\n type: \"scatter\" as const,\n mode: \"lines\" as const,\n hoverinfo: \"none\" as const,\n name: \"T\",\n line: { color: colorT, width: 2, shape: \"spline\" as const },\n }),\n [positions, peakT, colorT],\n );\n\n const gTrace = useMemo(\n () => ({\n x: positions,\n y: peakG,\n type: \"scatter\" as const,\n mode: \"lines\" as const,\n hoverinfo: \"none\" as const,\n name: \"G\",\n line: { color: colorG, width: 2, shape: \"spline\" as const },\n }),\n [positions, peakG, colorG],\n );\n\n const cTrace = useMemo(\n () => ({\n x: positions,\n y: peakC,\n type: \"scatter\" as const,\n mode: \"lines\" as const,\n hoverinfo: \"none\" as const,\n name: \"C\",\n line: { color: colorC, width: 2, shape: \"spline\" as const },\n }),\n [positions, peakC, colorC],\n );\n\n const maxValue = useMemo(\n () => Math.max(...peakA, ...peakT, ...peakG, ...peakC),\n [peakA, peakT, peakG, peakC],\n );\n\n useEffect(() => {\n if (!plotRef.current || data.length === 0) return;\n\n const plotData = [aTrace, tTrace, gTrace, cTrace];\n\n const layout: Partial<Plotly.Layout> = {\n width: width,\n height: height - PLOT_HEIGHT_OFFSET,\n margin: { l: 0, r: 0, b: 20, t: 10, pad: 0 },\n paper_bgcolor: theme.paperBg,\n plot_bgcolor: theme.plotBg,\n font: {\n family: CHART_FONT_FAMILY,\n },\n showlegend: false,\n xaxis: {\n showgrid: false,\n zeroline: false,\n showticklabels: false,\n showline: false,\n range: [Math.min(...positions), Math.max(...positions)],\n fixedrange: true,\n },\n yaxis: {\n showgrid: false,\n zeroline: false,\n showticklabels: false,\n showline: false,\n range: [0, maxValue * Y_AXIS_PADDING_FACTOR],\n fixedrange: true,\n },\n };\n\n const config = {\n responsive: true,\n displayModeBar: false,\n displaylogo: false,\n fillFrame: true,\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 });\n\n return () => {\n cancelled = true;\n if (plotElement) {\n getLoadedPlotly().purge(plotElement);\n }\n };\n }, [data, width, height, aTrace, tTrace, gTrace, cTrace, maxValue, positions, theme, bindTooltip]);\n\n if (data.length === 0) {\n return <div className=\"chart-container\">No data available</div>;\n }\n\n const renderSequence = () => {\n const renderSequenceLetters = () => {\n const minPosition = Math.min(...positions);\n const maxPosition = Math.max(...positions);\n const chartWidth = width;\n\n return (\n <div className=\"sequence-letters-container\">\n {sequence.map((base, index) => {\n const position = positions[index];\n const color =\n base === \"A\"\n ? colorA\n : base === \"T\"\n ? colorT\n : base === \"G\"\n ? colorG\n : base === \"C\"\n ? colorC\n : theme.textColor;\n\n const span = maxPosition - minPosition || 1;\n const percentage = (position - minPosition) / span;\n const leftPosition = percentage * chartWidth;\n\n return (\n <span\n key={`base-${index}`}\n className=\"sequence-letter\"\n style={{\n left: `${leftPosition}px`,\n color,\n }}\n >\n {base}\n </span>\n );\n })}\n </div>\n );\n };\n\n const renderPositionNumbers = () => {\n const minPosition = Math.min(...positions);\n const maxPosition = Math.max(...positions);\n const chartWidth = width;\n\n const startPos =\n Math.ceil(minPosition / positionInterval) * positionInterval;\n\n const regularPositionLabels: Array<{ position: number; label: string }> =\n [];\n\n for (let pos = startPos; pos <= maxPosition; pos += positionInterval) {\n regularPositionLabels.push({\n position: pos,\n label: pos.toString(),\n });\n }\n\n return (\n <div className=\"position-numbers-container\">\n {regularPositionLabels.map((label) => {\n const span = maxPosition - minPosition || 1;\n const percentage = (label.position - minPosition) / span;\n const leftPosition = percentage * chartWidth;\n\n return (\n <span\n key={`pos-${label.position}`}\n className=\"position-number\"\n style={{\n left: `${leftPosition}px`,\n }}\n >\n {label.label}\n </span>\n );\n })}\n </div>\n );\n };\n\n return (\n <div className=\"sequence-header\">\n {renderSequenceLetters()}\n {renderPositionNumbers()}\n </div>\n );\n };\n\n return (\n <div className=\"electropherogram-container relative\" style={{ width, height }}>\n {renderSequence()}\n <div className=\"electropherogram-chart\">\n <div ref={plotRef} style={{ width: \"100%\", height: \"100%\" }} />\n </div>\n {tooltipElement}\n </div>\n );\n};\n\nexport { Electropherogram };\nexport type { PeakData, ElectropherogramProps };\n"],"names":["PLOT_HEIGHT_OFFSET","Y_AXIS_PADDING_FACTOR","determineBase","item","peakValues","values","val","highestBase","highestValue","base","value","Electropherogram","data","width","height","positionInterval","colorA","CHART_COLORS","colorT","colorG","colorC","plotRef","useRef","theme","usePlotlyTheme","bindTooltip","tooltipElement","useChartTooltip","positions","useMemo","sequence","peakA","peakT","peakG","peakC","aTrace","tTrace","gTrace","cTrace","maxValue","useEffect","plotData","layout","CHART_FONT_FAMILY","config","cancelled","plotElement","loadPlotly","plotly","getLoadedPlotly","jsx","renderSequence","renderSequenceLetters","minPosition","maxPosition","chartWidth","index","position","color","span","leftPosition","renderPositionNumbers","startPos","regularPositionLabels","pos","label","jsxs"],"mappings":"uVAYA,MAAMA,EAAqB,GAErBC,EAAwB,KAsBxBC,EAAiBC,GAA2B,CAChD,GAAIA,EAAK,OAAS,OAAW,OAAOA,EAAK,KACzC,MAAMC,EAAa,CACjB,EAAGD,EAAK,MACR,EAAGA,EAAK,MACR,EAAGA,EAAK,MACR,EAAGA,EAAK,KAAA,EAGJE,EAAS,OAAO,OAAOD,CAAU,EAGvC,GAFiBC,EAAO,MAAOC,GAAQA,IAAQD,EAAO,CAAC,CAAC,EAGtD,MAAO,GAGT,IAAIE,EAAc,GACdC,EAAe,EAEnB,cAAO,QAAQJ,CAAU,EAAE,QAAQ,CAAC,CAACK,EAAMC,CAAK,IAAM,CAChDA,EAAQF,IACVD,EAAcE,EACdD,EAAeE,EAEnB,CAAC,EAEMH,CACT,EAEMI,EAAoD,CAAC,CACzD,KAAAC,EAAO,CAAA,EACP,MAAAC,EAAQ,IACR,OAAAC,EAAS,IACT,iBAAAC,EAAmB,GACnB,OAAAC,EAASC,EAAAA,aAAa,CAAC,EACvB,OAAAC,EAASD,EAAAA,aAAa,CAAC,EACvB,OAAAE,EAASF,EAAAA,aAAa,CAAC,EACvB,OAAAG,EAASH,EAAAA,aAAa,CAAC,CACzB,IAAM,CACJ,MAAMI,EAAUC,EAAAA,OAAuB,IAAI,EACrCC,EAAQC,EAAAA,eAAA,EACR,CAAE,YAAAC,EAAa,eAAAC,CAAA,EAAmBC,kBAAgB,CACtD,OAAQ,WACR,OAAQ,WAAA,CACT,EAEKC,EAAYC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,GAAU,CACpC,MAAMN,EAAOL,EAAcD,GAAe,EAEpCO,GADcK,EAAM,SAAWZ,GAAeM,EAClBJ,EAElC,OACEL,EAAAA,IAAC,OAAA,CAEC,UAAU,kBACV,MAAO,CACL,KAAM,GAAGU,CAAY,IAAA,EAGtB,SAAAK,EAAM,KAAA,EANF,OAAOA,EAAM,QAAQ,EAAA,CAShC,CAAC,CAAA,CACH,CAEJ,EAEA,OACEC,EAAAA,KAAC,MAAA,CAAI,UAAU,kBACZ,SAAA,CAAAd,EAAA,EACAS,EAAA,CAAsB,EACzB,CAEJ,EAEA,OACEK,EAAAA,KAAC,OAAI,UAAU,sCAAsC,MAAO,CAAE,MAAArD,EAAO,OAAAC,GAClE,SAAA,CAAAqC,EAAA,EACDD,EAAAA,IAAC,MAAA,CAAI,UAAU,yBACb,eAAC,MAAA,CAAI,IAAK7B,EAAS,MAAO,CAAE,MAAO,OAAQ,OAAQ,MAAA,EAAU,EAC/D,EACCK,CAAA,EACH,CAEJ"}
|
|
1
|
+
{"version":3,"file":"Electropherogram.cjs","sources":["../../../../src/components/charts/Electropherogram/Electropherogram.tsx"],"sourcesContent":["import React, { useEffect, useRef, useMemo } from \"react\";\n\nimport { useChartTooltip } from \"../ChartTooltip\";\nimport { getLoadedPlotly, loadPlotly } from \"../plotly-loader\";\n\nimport type Plotly from \"plotly.js-dist\";\n\nimport { CHART_FONT_FAMILY, usePlotlyTheme } from \"@/hooks/use-plotly-theme\";\nimport { CHART_COLORS } from \"@/utils/colors\";\nimport \"./Electropherogram.scss\";\n\n/** Height offset for the plot area in pixels */\nconst PLOT_HEIGHT_OFFSET = 75;\n/** Scale factor for y-axis range to add padding above max value */\nconst Y_AXIS_PADDING_FACTOR = 1.05;\n\ninterface PeakData {\n position: number;\n base?: string;\n peakA: number;\n peakT: number;\n peakG: number;\n peakC: number;\n}\n\ninterface ElectropherogramProps {\n data?: PeakData[];\n width?: number;\n height?: number;\n positionInterval?: number;\n colorA?: string;\n colorT?: string;\n colorG?: string;\n colorC?: string;\n}\n\nconst determineBase = (item: PeakData): string => {\n if (item.base !== undefined) return item.base;\n const peakValues = {\n A: item.peakA,\n T: item.peakT,\n G: item.peakG,\n C: item.peakC,\n };\n\n const values = Object.values(peakValues);\n const allEqual = values.every((val) => val === values[0]);\n\n if (allEqual) {\n return \"\";\n }\n\n let highestBase = \"\";\n let highestValue = 0;\n\n Object.entries(peakValues).forEach(([base, value]) => {\n if (value > highestValue) {\n highestBase = base;\n highestValue = value;\n }\n });\n\n return highestBase;\n};\n\nconst Electropherogram: React.FC<ElectropherogramProps> = ({\n data = [],\n width = 900,\n height = 600,\n positionInterval = 10,\n colorA = CHART_COLORS[0], // blue\n colorT = CHART_COLORS[2], // teal/green\n colorG = CHART_COLORS[3], // red\n colorC = CHART_COLORS[1], // orange\n}) => {\n const plotRef = useRef<HTMLDivElement>(null);\n const theme = usePlotlyTheme();\n const { bindTooltip, tooltipElement } = useChartTooltip({\n xLabel: \"Position\",\n yLabel: \"Intensity\",\n });\n\n const positions = useMemo(() => data.map((item) => item.position), [data]);\n const sequence = useMemo(() => data.map((item) => determineBase(item)), [data]);\n const peakA = useMemo(() => data.map((item) => item.peakA), [data]);\n const peakT = useMemo(() => data.map((item) => item.peakT), [data]);\n const peakG = useMemo(() => data.map((item) => item.peakG), [data]);\n const peakC = useMemo(() => data.map((item) => item.peakC), [data]);\n\n const aTrace = useMemo(\n () => ({\n x: positions,\n y: peakA,\n type: \"scatter\" as const,\n mode: \"lines\" as const,\n hoverinfo: \"none\" as const,\n name: \"A\",\n line: { color: colorA, width: 2, shape: \"spline\" as const },\n }),\n [positions, peakA, colorA],\n );\n\n const tTrace = useMemo(\n () => ({\n x: positions,\n y: peakT,\n type: \"scatter\" as const,\n mode: \"lines\" as const,\n hoverinfo: \"none\" as const,\n name: \"T\",\n line: { color: colorT, width: 2, shape: \"spline\" as const },\n }),\n [positions, peakT, colorT],\n );\n\n const gTrace = useMemo(\n () => ({\n x: positions,\n y: peakG,\n type: \"scatter\" as const,\n mode: \"lines\" as const,\n hoverinfo: \"none\" as const,\n name: \"G\",\n line: { color: colorG, width: 2, shape: \"spline\" as const },\n }),\n [positions, peakG, colorG],\n );\n\n const cTrace = useMemo(\n () => ({\n x: positions,\n y: peakC,\n type: \"scatter\" as const,\n mode: \"lines\" as const,\n hoverinfo: \"none\" as const,\n name: \"C\",\n line: { color: colorC, width: 2, shape: \"spline\" as const },\n }),\n [positions, peakC, colorC],\n );\n\n const maxValue = useMemo(\n () => Math.max(...peakA, ...peakT, ...peakG, ...peakC),\n [peakA, peakT, peakG, peakC],\n );\n\n useEffect(() => {\n if (!plotRef.current || data.length === 0) return;\n\n const plotData = [aTrace, tTrace, gTrace, cTrace];\n\n const layout: Partial<Plotly.Layout> = {\n width: width,\n height: height - PLOT_HEIGHT_OFFSET,\n margin: { l: 0, r: 0, b: 20, t: 10, pad: 0 },\n paper_bgcolor: theme.paperBg,\n plot_bgcolor: theme.plotBg,\n font: {\n family: CHART_FONT_FAMILY,\n },\n showlegend: false,\n xaxis: {\n showgrid: false,\n zeroline: false,\n showticklabels: false,\n showline: false,\n range: [Math.min(...positions), Math.max(...positions)],\n fixedrange: true,\n },\n yaxis: {\n showgrid: false,\n zeroline: false,\n showticklabels: false,\n showline: false,\n range: [0, maxValue * Y_AXIS_PADDING_FACTOR],\n fixedrange: true,\n },\n };\n\n const config = {\n responsive: true,\n displayModeBar: false,\n displaylogo: false,\n fillFrame: true,\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 });\n\n return () => {\n cancelled = true;\n if (plotElement) {\n getLoadedPlotly().purge(plotElement);\n }\n };\n }, [data, width, height, aTrace, tTrace, gTrace, cTrace, maxValue, positions, theme, bindTooltip]);\n\n if (data.length === 0) {\n return <div className=\"electropherogram-empty\">No data available</div>;\n }\n\n const renderSequence = () => {\n const renderSequenceLetters = () => {\n const minPosition = Math.min(...positions);\n const maxPosition = Math.max(...positions);\n const chartWidth = width;\n\n return (\n <div className=\"electropherogram-sequence-letters\">\n {sequence.map((base, index) => {\n const position = positions[index];\n const color =\n base === \"A\"\n ? colorA\n : base === \"T\"\n ? colorT\n : base === \"G\"\n ? colorG\n : base === \"C\"\n ? colorC\n : theme.textColor;\n\n const span = maxPosition - minPosition || 1;\n const percentage = (position - minPosition) / span;\n const leftPosition = percentage * chartWidth;\n\n return (\n <span\n key={`base-${index}`}\n className=\"electropherogram-sequence-letter\"\n style={{\n left: `${leftPosition}px`,\n color,\n }}\n >\n {base}\n </span>\n );\n })}\n </div>\n );\n };\n\n const renderPositionNumbers = () => {\n const minPosition = Math.min(...positions);\n const maxPosition = Math.max(...positions);\n const chartWidth = width;\n\n const startPos =\n Math.ceil(minPosition / positionInterval) * positionInterval;\n\n const regularPositionLabels: Array<{ position: number; label: string }> =\n [];\n\n for (let pos = startPos; pos <= maxPosition; pos += positionInterval) {\n regularPositionLabels.push({\n position: pos,\n label: pos.toString(),\n });\n }\n\n return (\n <div className=\"electropherogram-position-numbers\">\n {regularPositionLabels.map((label) => {\n const span = maxPosition - minPosition || 1;\n const percentage = (label.position - minPosition) / span;\n const leftPosition = percentage * chartWidth;\n\n return (\n <span\n key={`pos-${label.position}`}\n className=\"electropherogram-position-number\"\n style={{\n left: `${leftPosition}px`,\n }}\n >\n {label.label}\n </span>\n );\n })}\n </div>\n );\n };\n\n return (\n <div className=\"electropherogram-sequence-header\">\n {renderSequenceLetters()}\n {renderPositionNumbers()}\n </div>\n );\n };\n\n return (\n <div className=\"electropherogram-container relative\" style={{ width, height }}>\n {renderSequence()}\n <div className=\"electropherogram-chart\">\n <div ref={plotRef} style={{ width: \"100%\", height: \"100%\" }} />\n </div>\n {tooltipElement}\n </div>\n );\n};\n\nexport { Electropherogram };\nexport type { PeakData, ElectropherogramProps };\n"],"names":["PLOT_HEIGHT_OFFSET","Y_AXIS_PADDING_FACTOR","determineBase","item","peakValues","values","val","highestBase","highestValue","base","value","Electropherogram","data","width","height","positionInterval","colorA","CHART_COLORS","colorT","colorG","colorC","plotRef","useRef","theme","usePlotlyTheme","bindTooltip","tooltipElement","useChartTooltip","positions","useMemo","sequence","peakA","peakT","peakG","peakC","aTrace","tTrace","gTrace","cTrace","maxValue","useEffect","plotData","layout","CHART_FONT_FAMILY","config","cancelled","plotElement","loadPlotly","plotly","getLoadedPlotly","jsx","renderSequence","renderSequenceLetters","minPosition","maxPosition","chartWidth","index","position","color","span","leftPosition","renderPositionNumbers","startPos","regularPositionLabels","pos","label","jsxs"],"mappings":"uVAYA,MAAMA,EAAqB,GAErBC,EAAwB,KAsBxBC,EAAiBC,GAA2B,CAChD,GAAIA,EAAK,OAAS,OAAW,OAAOA,EAAK,KACzC,MAAMC,EAAa,CACjB,EAAGD,EAAK,MACR,EAAGA,EAAK,MACR,EAAGA,EAAK,MACR,EAAGA,EAAK,KAAA,EAGJE,EAAS,OAAO,OAAOD,CAAU,EAGvC,GAFiBC,EAAO,MAAOC,GAAQA,IAAQD,EAAO,CAAC,CAAC,EAGtD,MAAO,GAGT,IAAIE,EAAc,GACdC,EAAe,EAEnB,cAAO,QAAQJ,CAAU,EAAE,QAAQ,CAAC,CAACK,EAAMC,CAAK,IAAM,CAChDA,EAAQF,IACVD,EAAcE,EACdD,EAAeE,EAEnB,CAAC,EAEMH,CACT,EAEMI,EAAoD,CAAC,CACzD,KAAAC,EAAO,CAAA,EACP,MAAAC,EAAQ,IACR,OAAAC,EAAS,IACT,iBAAAC,EAAmB,GACnB,OAAAC,EAASC,EAAAA,aAAa,CAAC,EACvB,OAAAC,EAASD,EAAAA,aAAa,CAAC,EACvB,OAAAE,EAASF,EAAAA,aAAa,CAAC,EACvB,OAAAG,EAASH,EAAAA,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AExCgD,EACJ,CAAA,EAEF,QAASC,EAAMF,EAAUE,GAAOV,EAAaU,GAAOjD,EAClDgD,EAAsB,KAAK,CACzB,SAAUC,EACV,MAAOA,EAAI,SAAA,CAAS,CACrB,EAGH,aACG,MAAA,CAAI,UAAU,oCACZ,SAAAD,EAAsB,IAAKE,GAAU,CACpC,MAAMN,EAAOL,EAAcD,GAAe,EAEpCO,GADcK,EAAM,SAAWZ,GAAeM,EAClBJ,EAElC,OACEL,EAAAA,IAAC,OAAA,CAEC,UAAU,mCACV,MAAO,CACL,KAAM,GAAGU,CAAY,IAAA,EAGtB,SAAAK,EAAM,KAAA,EANF,OAAOA,EAAM,QAAQ,EAAA,CAShC,CAAC,CAAA,CACH,CAEJ,EAEA,OACEC,EAAAA,KAAC,MAAA,CAAI,UAAU,mCACZ,SAAA,CAAAd,EAAA,EACAS,EAAA,CAAsB,EACzB,CAEJ,EAEA,OACEK,EAAAA,KAAC,OAAI,UAAU,sCAAsC,MAAO,CAAE,MAAArD,EAAO,OAAAC,GAClE,SAAA,CAAAqC,EAAA,EACDD,EAAAA,IAAC,MAAA,CAAI,UAAU,yBACb,eAAC,MAAA,CAAI,IAAK7B,EAAS,MAAO,CAAE,MAAO,OAAQ,OAAQ,MAAA,EAAU,EAC/D,EACCK,CAAA,EACH,CAEJ"}
|
|
@@ -16,8 +16,8 @@ const W = 75, Y = 1.05, X = (e) => {
|
|
|
16
16
|
if (h.every((i) => i === h[0]))
|
|
17
17
|
return "";
|
|
18
18
|
let u = "", f = 0;
|
|
19
|
-
return Object.entries(l).forEach(([i,
|
|
20
|
-
|
|
19
|
+
return Object.entries(l).forEach(([i, g]) => {
|
|
20
|
+
g > f && (u = i, f = g);
|
|
21
21
|
}), u;
|
|
22
22
|
}, oe = ({
|
|
23
23
|
data: e = [],
|
|
@@ -30,15 +30,15 @@ const W = 75, Y = 1.05, X = (e) => {
|
|
|
30
30
|
// teal/green
|
|
31
31
|
colorG: i = N[3],
|
|
32
32
|
// red
|
|
33
|
-
colorC:
|
|
33
|
+
colorC: g = N[1]
|
|
34
34
|
// orange
|
|
35
35
|
}) => {
|
|
36
|
-
const
|
|
36
|
+
const d = j(null), T = V(), { bindTooltip: C, tooltipElement: G } = $({
|
|
37
37
|
xLabel: "Position",
|
|
38
38
|
yLabel: "Intensity"
|
|
39
|
-
}),
|
|
39
|
+
}), t = o(() => e.map((n) => n.position), [e]), R = o(() => e.map((n) => X(n)), [e]), v = o(() => e.map((n) => n.peakA), [e]), P = o(() => e.map((n) => n.peakT), [e]), k = o(() => e.map((n) => n.peakG), [e]), b = o(() => e.map((n) => n.peakC), [e]), _ = o(
|
|
40
40
|
() => ({
|
|
41
|
-
x:
|
|
41
|
+
x: t,
|
|
42
42
|
y: v,
|
|
43
43
|
type: "scatter",
|
|
44
44
|
mode: "lines",
|
|
@@ -46,10 +46,10 @@ const W = 75, Y = 1.05, X = (e) => {
|
|
|
46
46
|
name: "A",
|
|
47
47
|
line: { color: u, width: 2, shape: "spline" }
|
|
48
48
|
}),
|
|
49
|
-
[
|
|
49
|
+
[t, v, u]
|
|
50
50
|
), q = o(
|
|
51
51
|
() => ({
|
|
52
|
-
x:
|
|
52
|
+
x: t,
|
|
53
53
|
y: P,
|
|
54
54
|
type: "scatter",
|
|
55
55
|
mode: "lines",
|
|
@@ -57,10 +57,10 @@ const W = 75, Y = 1.05, X = (e) => {
|
|
|
57
57
|
name: "T",
|
|
58
58
|
line: { color: f, width: 2, shape: "spline" }
|
|
59
59
|
}),
|
|
60
|
-
[
|
|
60
|
+
[t, P, f]
|
|
61
61
|
), w = o(
|
|
62
62
|
() => ({
|
|
63
|
-
x:
|
|
63
|
+
x: t,
|
|
64
64
|
y: k,
|
|
65
65
|
type: "scatter",
|
|
66
66
|
mode: "lines",
|
|
@@ -68,25 +68,25 @@ const W = 75, Y = 1.05, X = (e) => {
|
|
|
68
68
|
name: "G",
|
|
69
69
|
line: { color: i, width: 2, shape: "spline" }
|
|
70
70
|
}),
|
|
71
|
-
[
|
|
71
|
+
[t, k, i]
|
|
72
72
|
), E = o(
|
|
73
73
|
() => ({
|
|
74
|
-
x:
|
|
74
|
+
x: t,
|
|
75
75
|
y: b,
|
|
76
76
|
type: "scatter",
|
|
77
77
|
mode: "lines",
|
|
78
78
|
hoverinfo: "none",
|
|
79
79
|
name: "C",
|
|
80
|
-
line: { color:
|
|
80
|
+
line: { color: g, width: 2, shape: "spline" }
|
|
81
81
|
}),
|
|
82
|
-
[
|
|
82
|
+
[t, b, g]
|
|
83
83
|
), L = o(
|
|
84
84
|
() => Math.max(...v, ...P, ...k, ...b),
|
|
85
85
|
[v, P, k, b]
|
|
86
86
|
);
|
|
87
87
|
return H(() => {
|
|
88
|
-
if (!
|
|
89
|
-
const
|
|
88
|
+
if (!d.current || e.length === 0) return;
|
|
89
|
+
const n = [_, q, w, E], M = {
|
|
90
90
|
width: l,
|
|
91
91
|
height: h - W,
|
|
92
92
|
margin: { l: 0, r: 0, b: 20, t: 10, pad: 0 },
|
|
@@ -101,7 +101,7 @@ const W = 75, Y = 1.05, X = (e) => {
|
|
|
101
101
|
zeroline: !1,
|
|
102
102
|
showticklabels: !1,
|
|
103
103
|
showline: !1,
|
|
104
|
-
range: [Math.min(...
|
|
104
|
+
range: [Math.min(...t), Math.max(...t)],
|
|
105
105
|
fixedrange: !0
|
|
106
106
|
},
|
|
107
107
|
yaxis: {
|
|
@@ -120,20 +120,20 @@ const W = 75, Y = 1.05, X = (e) => {
|
|
|
120
120
|
};
|
|
121
121
|
let c = !1, p = null;
|
|
122
122
|
return D().then((r) => {
|
|
123
|
-
c || !
|
|
123
|
+
c || !d.current || (r.newPlot(d.current, n, M, a), C(d.current), p = d.current);
|
|
124
124
|
}), () => {
|
|
125
125
|
c = !0, p && I().purge(p);
|
|
126
126
|
};
|
|
127
|
-
}, [e, l, h, _, q, w, E, L,
|
|
127
|
+
}, [e, l, h, _, q, w, E, L, t, T, C]), e.length === 0 ? /* @__PURE__ */ m("div", { className: "electropherogram-empty", children: "No data available" }) : /* @__PURE__ */ F("div", { className: "electropherogram-container relative", style: { width: l, height: h }, children: [
|
|
128
128
|
(() => {
|
|
129
|
-
const
|
|
130
|
-
const a = Math.min(...
|
|
131
|
-
return /* @__PURE__ */ m("div", { className: "sequence-letters
|
|
132
|
-
const s =
|
|
129
|
+
const n = () => {
|
|
130
|
+
const a = Math.min(...t), c = Math.max(...t), p = l;
|
|
131
|
+
return /* @__PURE__ */ m("div", { className: "electropherogram-sequence-letters", children: R.map((r, y) => {
|
|
132
|
+
const s = t[y], A = r === "A" ? u : r === "T" ? f : r === "G" ? i : r === "C" ? g : T.textColor, O = c - a || 1, B = (s - a) / O * p;
|
|
133
133
|
return /* @__PURE__ */ m(
|
|
134
134
|
"span",
|
|
135
135
|
{
|
|
136
|
-
className: "sequence-letter",
|
|
136
|
+
className: "electropherogram-sequence-letter",
|
|
137
137
|
style: {
|
|
138
138
|
left: `${B}px`,
|
|
139
139
|
color: A
|
|
@@ -144,18 +144,18 @@ const W = 75, Y = 1.05, X = (e) => {
|
|
|
144
144
|
);
|
|
145
145
|
}) });
|
|
146
146
|
}, M = () => {
|
|
147
|
-
const a = Math.min(...
|
|
147
|
+
const a = Math.min(...t), c = Math.max(...t), p = l, r = Math.ceil(a / x) * x, y = [];
|
|
148
148
|
for (let s = r; s <= c; s += x)
|
|
149
149
|
y.push({
|
|
150
150
|
position: s,
|
|
151
151
|
label: s.toString()
|
|
152
152
|
});
|
|
153
|
-
return /* @__PURE__ */ m("div", { className: "position-numbers
|
|
153
|
+
return /* @__PURE__ */ m("div", { className: "electropherogram-position-numbers", children: y.map((s) => {
|
|
154
154
|
const A = c - a || 1, S = (s.position - a) / A * p;
|
|
155
155
|
return /* @__PURE__ */ m(
|
|
156
156
|
"span",
|
|
157
157
|
{
|
|
158
|
-
className: "position-number",
|
|
158
|
+
className: "electropherogram-position-number",
|
|
159
159
|
style: {
|
|
160
160
|
left: `${S}px`
|
|
161
161
|
},
|
|
@@ -165,12 +165,12 @@ const W = 75, Y = 1.05, X = (e) => {
|
|
|
165
165
|
);
|
|
166
166
|
}) });
|
|
167
167
|
};
|
|
168
|
-
return /* @__PURE__ */ F("div", { className: "sequence-header", children: [
|
|
169
|
-
|
|
168
|
+
return /* @__PURE__ */ F("div", { className: "electropherogram-sequence-header", children: [
|
|
169
|
+
n(),
|
|
170
170
|
M()
|
|
171
171
|
] });
|
|
172
172
|
})(),
|
|
173
|
-
/* @__PURE__ */ m("div", { className: "electropherogram-chart", children: /* @__PURE__ */ m("div", { ref:
|
|
173
|
+
/* @__PURE__ */ m("div", { className: "electropherogram-chart", children: /* @__PURE__ */ m("div", { ref: d, style: { width: "100%", height: "100%" } }) }),
|
|
174
174
|
G
|
|
175
175
|
] });
|
|
176
176
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Electropherogram.js","sources":["../../../../src/components/charts/Electropherogram/Electropherogram.tsx"],"sourcesContent":["import React, { useEffect, useRef, useMemo } from \"react\";\n\nimport { useChartTooltip } from \"../ChartTooltip\";\nimport { getLoadedPlotly, loadPlotly } from \"../plotly-loader\";\n\nimport type Plotly from \"plotly.js-dist\";\n\nimport { CHART_FONT_FAMILY, usePlotlyTheme } from \"@/hooks/use-plotly-theme\";\nimport { CHART_COLORS } from \"@/utils/colors\";\nimport \"./Electropherogram.scss\";\n\n/** Height offset for the plot area in pixels */\nconst PLOT_HEIGHT_OFFSET = 75;\n/** Scale factor for y-axis range to add padding above max value */\nconst Y_AXIS_PADDING_FACTOR = 1.05;\n\ninterface PeakData {\n position: number;\n base?: string;\n peakA: number;\n peakT: number;\n peakG: number;\n peakC: number;\n}\n\ninterface ElectropherogramProps {\n data?: PeakData[];\n width?: number;\n height?: number;\n positionInterval?: number;\n colorA?: string;\n colorT?: string;\n colorG?: string;\n colorC?: string;\n}\n\nconst determineBase = (item: PeakData): string => {\n if (item.base !== undefined) return item.base;\n const peakValues = {\n A: item.peakA,\n T: item.peakT,\n G: item.peakG,\n C: item.peakC,\n };\n\n const values = Object.values(peakValues);\n const allEqual = values.every((val) => val === values[0]);\n\n if (allEqual) {\n return \"\";\n }\n\n let highestBase = \"\";\n let highestValue = 0;\n\n Object.entries(peakValues).forEach(([base, value]) => {\n if (value > highestValue) {\n highestBase = base;\n highestValue = value;\n }\n });\n\n return highestBase;\n};\n\nconst Electropherogram: React.FC<ElectropherogramProps> = ({\n data = [],\n width = 900,\n height = 600,\n positionInterval = 10,\n colorA = CHART_COLORS[0], // blue\n colorT = CHART_COLORS[2], // teal/green\n colorG = CHART_COLORS[3], // red\n colorC = CHART_COLORS[1], // orange\n}) => {\n const plotRef = useRef<HTMLDivElement>(null);\n const theme = usePlotlyTheme();\n const { bindTooltip, tooltipElement } = useChartTooltip({\n xLabel: \"Position\",\n yLabel: \"Intensity\",\n });\n\n const positions = useMemo(() => data.map((item) => item.position), [data]);\n const sequence = useMemo(() => data.map((item) => determineBase(item)), [data]);\n const peakA = useMemo(() => data.map((item) => item.peakA), [data]);\n const peakT = useMemo(() => data.map((item) => item.peakT), [data]);\n const peakG = useMemo(() => data.map((item) => item.peakG), [data]);\n const peakC = useMemo(() => data.map((item) => item.peakC), [data]);\n\n const aTrace = useMemo(\n () => ({\n x: positions,\n y: peakA,\n type: \"scatter\" as const,\n mode: \"lines\" as const,\n hoverinfo: \"none\" as const,\n name: \"A\",\n line: { color: colorA, width: 2, shape: \"spline\" as const },\n }),\n [positions, peakA, colorA],\n );\n\n const tTrace = useMemo(\n () => ({\n x: positions,\n y: peakT,\n type: \"scatter\" as const,\n mode: \"lines\" as const,\n hoverinfo: \"none\" as const,\n name: \"T\",\n line: { color: colorT, width: 2, shape: \"spline\" as const },\n }),\n [positions, peakT, colorT],\n );\n\n const gTrace = useMemo(\n () => ({\n x: positions,\n y: peakG,\n type: \"scatter\" as const,\n mode: \"lines\" as const,\n hoverinfo: \"none\" as const,\n name: \"G\",\n line: { color: colorG, width: 2, shape: \"spline\" as const },\n }),\n [positions, peakG, colorG],\n );\n\n const cTrace = useMemo(\n () => ({\n x: positions,\n y: peakC,\n type: \"scatter\" as const,\n mode: \"lines\" as const,\n hoverinfo: \"none\" as const,\n name: \"C\",\n line: { color: colorC, width: 2, shape: \"spline\" as const },\n }),\n [positions, peakC, colorC],\n );\n\n const maxValue = useMemo(\n () => Math.max(...peakA, ...peakT, ...peakG, ...peakC),\n [peakA, peakT, peakG, peakC],\n );\n\n useEffect(() => {\n if (!plotRef.current || data.length === 0) return;\n\n const plotData = [aTrace, tTrace, gTrace, cTrace];\n\n const layout: Partial<Plotly.Layout> = {\n width: width,\n height: height - PLOT_HEIGHT_OFFSET,\n margin: { l: 0, r: 0, b: 20, t: 10, pad: 0 },\n paper_bgcolor: theme.paperBg,\n plot_bgcolor: theme.plotBg,\n font: {\n family: CHART_FONT_FAMILY,\n },\n showlegend: false,\n xaxis: {\n showgrid: false,\n zeroline: false,\n showticklabels: false,\n showline: false,\n range: [Math.min(...positions), Math.max(...positions)],\n fixedrange: true,\n },\n yaxis: {\n showgrid: false,\n zeroline: false,\n showticklabels: false,\n showline: false,\n range: [0, maxValue * Y_AXIS_PADDING_FACTOR],\n fixedrange: true,\n },\n };\n\n const config = {\n responsive: true,\n displayModeBar: false,\n displaylogo: false,\n fillFrame: true,\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 });\n\n return () => {\n cancelled = true;\n if (plotElement) {\n getLoadedPlotly().purge(plotElement);\n }\n };\n }, [data, width, height, aTrace, tTrace, gTrace, cTrace, maxValue, positions, theme, bindTooltip]);\n\n if (data.length === 0) {\n return <div className=\"chart-container\">No data available</div>;\n }\n\n const renderSequence = () => {\n const renderSequenceLetters = () => {\n const minPosition = Math.min(...positions);\n const maxPosition = Math.max(...positions);\n const chartWidth = width;\n\n return (\n <div className=\"sequence-letters-container\">\n {sequence.map((base, index) => {\n const position = positions[index];\n const color =\n base === \"A\"\n ? colorA\n : base === \"T\"\n ? colorT\n : base === \"G\"\n ? colorG\n : base === \"C\"\n ? colorC\n : theme.textColor;\n\n const span = maxPosition - minPosition || 1;\n const percentage = (position - minPosition) / span;\n const leftPosition = percentage * chartWidth;\n\n return (\n <span\n key={`base-${index}`}\n className=\"sequence-letter\"\n style={{\n left: `${leftPosition}px`,\n color,\n }}\n >\n {base}\n </span>\n );\n })}\n </div>\n );\n };\n\n const renderPositionNumbers = () => {\n const minPosition = Math.min(...positions);\n const maxPosition = Math.max(...positions);\n const chartWidth = width;\n\n const startPos =\n Math.ceil(minPosition / positionInterval) * positionInterval;\n\n const regularPositionLabels: Array<{ position: number; label: string }> =\n [];\n\n for (let pos = startPos; pos <= maxPosition; pos += positionInterval) {\n regularPositionLabels.push({\n position: pos,\n label: pos.toString(),\n });\n }\n\n return (\n <div className=\"position-numbers-container\">\n {regularPositionLabels.map((label) => {\n const span = maxPosition - minPosition || 1;\n const percentage = (label.position - minPosition) / span;\n const leftPosition = percentage * chartWidth;\n\n return (\n <span\n key={`pos-${label.position}`}\n className=\"position-number\"\n style={{\n left: `${leftPosition}px`,\n }}\n >\n {label.label}\n </span>\n );\n })}\n </div>\n );\n };\n\n return (\n <div className=\"sequence-header\">\n {renderSequenceLetters()}\n {renderPositionNumbers()}\n </div>\n );\n };\n\n return (\n <div className=\"electropherogram-container relative\" style={{ width, height }}>\n {renderSequence()}\n <div className=\"electropherogram-chart\">\n <div ref={plotRef} style={{ width: \"100%\", height: \"100%\" }} />\n </div>\n {tooltipElement}\n </div>\n );\n};\n\nexport { Electropherogram };\nexport type { PeakData, ElectropherogramProps };\n"],"names":["PLOT_HEIGHT_OFFSET","Y_AXIS_PADDING_FACTOR","determineBase","item","peakValues","values","val","highestBase","highestValue","base","value","Electropherogram","data","width","height","positionInterval","colorA","CHART_COLORS","colorT","colorG","colorC","plotRef","useRef","theme","usePlotlyTheme","bindTooltip","tooltipElement","useChartTooltip","positions","useMemo","sequence","peakA","peakT","peakG","peakC","aTrace","tTrace","gTrace","cTrace","maxValue","useEffect","plotData","layout","CHART_FONT_FAMILY","config","cancelled","plotElement","loadPlotly","plotly","getLoadedPlotly","jsx","jsxs","renderSequenceLetters","minPosition","maxPosition","chartWidth","index","position","color","span","leftPosition","renderPositionNumbers","startPos","regularPositionLabels","pos","label"],"mappings":";;;;;;;AAYA,MAAMA,IAAqB,IAErBC,IAAwB,MAsBxBC,IAAgB,CAACC,MAA2B;AAChD,MAAIA,EAAK,SAAS,OAAW,QAAOA,EAAK;AACzC,QAAMC,IAAa;AAAA,IACjB,GAAGD,EAAK;AAAA,IACR,GAAGA,EAAK;AAAA,IACR,GAAGA,EAAK;AAAA,IACR,GAAGA,EAAK;AAAA,EAAA,GAGJE,IAAS,OAAO,OAAOD,CAAU;AAGvC,MAFiBC,EAAO,MAAM,CAACC,MAAQA,MAAQD,EAAO,CAAC,CAAC;AAGtD,WAAO;AAGT,MAAIE,IAAc,IACdC,IAAe;AAEnB,gBAAO,QAAQJ,CAAU,EAAE,QAAQ,CAAC,CAACK,GAAMC,CAAK,MAAM;AACpD,IAAIA,IAAQF,MACVD,IAAcE,GACdD,IAAeE;AAAA,EAEnB,CAAC,GAEMH;AACT,GAEMI,KAAoD,CAAC;AAAA,EACzD,MAAAC,IAAO,CAAA;AAAA,EACP,OAAAC,IAAQ;AAAA,EACR,QAAAC,IAAS;AAAA,EACT,kBAAAC,IAAmB;AAAA,EACnB,QAAAC,IAASC,EAAa,CAAC;AAAA;AAAA,EACvB,QAAAC,IAASD,EAAa,CAAC;AAAA;AAAA,EACvB,QAAAE,IAASF,EAAa,CAAC;AAAA;AAAA,EACvB,QAAAG,IAASH,EAAa,CAAC;AAAA;AACzB,MAAM;AACJ,QAAMI,IAAUC,EAAuB,IAAI,GACrCC,IAAQC,E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,IACD,gBAAAX,EAAC,OAAA,EAAI,WAAU,0BACb,4BAAC,OAAA,EAAI,KAAK7B,GAAS,OAAO,EAAE,OAAO,QAAQ,QAAQ,OAAA,GAAU,GAC/D;AAAA,IACCK;AAAA,EAAA,GACH;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"Electropherogram.js","sources":["../../../../src/components/charts/Electropherogram/Electropherogram.tsx"],"sourcesContent":["import React, { useEffect, useRef, useMemo } from \"react\";\n\nimport { useChartTooltip } from \"../ChartTooltip\";\nimport { getLoadedPlotly, loadPlotly } from \"../plotly-loader\";\n\nimport type Plotly from \"plotly.js-dist\";\n\nimport { CHART_FONT_FAMILY, usePlotlyTheme } from \"@/hooks/use-plotly-theme\";\nimport { CHART_COLORS } from \"@/utils/colors\";\nimport \"./Electropherogram.scss\";\n\n/** Height offset for the plot area in pixels */\nconst PLOT_HEIGHT_OFFSET = 75;\n/** Scale factor for y-axis range to add padding above max value */\nconst Y_AXIS_PADDING_FACTOR = 1.05;\n\ninterface PeakData {\n position: number;\n base?: string;\n peakA: number;\n peakT: number;\n peakG: number;\n peakC: number;\n}\n\ninterface ElectropherogramProps {\n data?: PeakData[];\n width?: number;\n height?: number;\n positionInterval?: number;\n colorA?: string;\n colorT?: string;\n colorG?: string;\n colorC?: string;\n}\n\nconst determineBase = (item: PeakData): string => {\n if (item.base !== undefined) return item.base;\n const peakValues = {\n A: item.peakA,\n T: item.peakT,\n G: item.peakG,\n C: item.peakC,\n };\n\n const values = Object.values(peakValues);\n const allEqual = values.every((val) => val === values[0]);\n\n if (allEqual) {\n return \"\";\n }\n\n let highestBase = \"\";\n let highestValue = 0;\n\n Object.entries(peakValues).forEach(([base, value]) => {\n if (value > highestValue) {\n highestBase = base;\n highestValue = value;\n }\n });\n\n return highestBase;\n};\n\nconst Electropherogram: React.FC<ElectropherogramProps> = ({\n data = [],\n width = 900,\n height = 600,\n positionInterval = 10,\n colorA = CHART_COLORS[0], // blue\n colorT = CHART_COLORS[2], // teal/green\n colorG = CHART_COLORS[3], // red\n colorC = CHART_COLORS[1], // orange\n}) => {\n const plotRef = useRef<HTMLDivElement>(null);\n const theme = usePlotlyTheme();\n const { bindTooltip, tooltipElement } = useChartTooltip({\n xLabel: \"Position\",\n yLabel: \"Intensity\",\n });\n\n const positions = useMemo(() => data.map((item) => item.position), [data]);\n const sequence = useMemo(() => data.map((item) => determineBase(item)), [data]);\n const peakA = useMemo(() => data.map((item) => item.peakA), [data]);\n const peakT = useMemo(() => data.map((item) => item.peakT), [data]);\n const peakG = useMemo(() => data.map((item) => item.peakG), [data]);\n const peakC = useMemo(() => data.map((item) => item.peakC), [data]);\n\n const aTrace = useMemo(\n () => ({\n x: positions,\n y: peakA,\n type: \"scatter\" as const,\n mode: \"lines\" as const,\n hoverinfo: \"none\" as const,\n name: \"A\",\n line: { color: colorA, width: 2, shape: \"spline\" as const },\n }),\n [positions, peakA, colorA],\n );\n\n const tTrace = useMemo(\n () => ({\n x: positions,\n y: peakT,\n type: \"scatter\" as const,\n mode: \"lines\" as const,\n hoverinfo: \"none\" as const,\n name: \"T\",\n line: { color: colorT, width: 2, shape: \"spline\" as const },\n }),\n [positions, peakT, colorT],\n );\n\n const gTrace = useMemo(\n () => ({\n x: positions,\n y: peakG,\n type: \"scatter\" as const,\n mode: \"lines\" as const,\n hoverinfo: \"none\" as const,\n name: \"G\",\n line: { color: colorG, width: 2, shape: \"spline\" as const },\n }),\n [positions, peakG, colorG],\n );\n\n const cTrace = useMemo(\n () => ({\n x: positions,\n y: peakC,\n type: \"scatter\" as const,\n mode: \"lines\" as const,\n hoverinfo: \"none\" as const,\n name: \"C\",\n line: { color: colorC, width: 2, shape: \"spline\" as const },\n }),\n [positions, peakC, colorC],\n );\n\n const maxValue = useMemo(\n () => Math.max(...peakA, ...peakT, ...peakG, ...peakC),\n [peakA, peakT, peakG, peakC],\n );\n\n useEffect(() => {\n if (!plotRef.current || data.length === 0) return;\n\n const plotData = [aTrace, tTrace, gTrace, cTrace];\n\n const layout: Partial<Plotly.Layout> = {\n width: width,\n height: height - PLOT_HEIGHT_OFFSET,\n margin: { l: 0, r: 0, b: 20, t: 10, pad: 0 },\n paper_bgcolor: theme.paperBg,\n plot_bgcolor: theme.plotBg,\n font: {\n family: CHART_FONT_FAMILY,\n },\n showlegend: false,\n xaxis: {\n showgrid: false,\n zeroline: false,\n showticklabels: false,\n showline: false,\n range: [Math.min(...positions), Math.max(...positions)],\n fixedrange: true,\n },\n yaxis: {\n showgrid: false,\n zeroline: false,\n showticklabels: false,\n showline: false,\n range: [0, maxValue * Y_AXIS_PADDING_FACTOR],\n fixedrange: true,\n },\n };\n\n const config = {\n responsive: true,\n displayModeBar: false,\n displaylogo: false,\n fillFrame: true,\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 });\n\n return () => {\n cancelled = true;\n if (plotElement) {\n getLoadedPlotly().purge(plotElement);\n }\n };\n }, [data, width, height, aTrace, tTrace, gTrace, cTrace, maxValue, positions, theme, bindTooltip]);\n\n if (data.length === 0) {\n return <div className=\"electropherogram-empty\">No data available</div>;\n }\n\n const renderSequence = () => {\n const renderSequenceLetters = () => {\n const minPosition = Math.min(...positions);\n const maxPosition = Math.max(...positions);\n const chartWidth = width;\n\n return (\n <div className=\"electropherogram-sequence-letters\">\n {sequence.map((base, index) => {\n const position = positions[index];\n const color =\n base === \"A\"\n ? colorA\n : base === \"T\"\n ? colorT\n : base === \"G\"\n ? colorG\n : base === \"C\"\n ? colorC\n : theme.textColor;\n\n const span = maxPosition - minPosition || 1;\n const percentage = (position - minPosition) / span;\n const leftPosition = percentage * chartWidth;\n\n return (\n <span\n key={`base-${index}`}\n className=\"electropherogram-sequence-letter\"\n style={{\n left: `${leftPosition}px`,\n color,\n }}\n >\n {base}\n </span>\n );\n })}\n </div>\n );\n };\n\n const renderPositionNumbers = () => {\n const minPosition = Math.min(...positions);\n const maxPosition = Math.max(...positions);\n const chartWidth = width;\n\n const startPos =\n Math.ceil(minPosition / positionInterval) * positionInterval;\n\n const regularPositionLabels: Array<{ position: number; label: string }> =\n [];\n\n for (let pos = startPos; pos <= maxPosition; pos += positionInterval) {\n regularPositionLabels.push({\n position: pos,\n label: pos.toString(),\n });\n }\n\n return (\n <div className=\"electropherogram-position-numbers\">\n {regularPositionLabels.map((label) => {\n const span = maxPosition - minPosition || 1;\n const percentage = (label.position - minPosition) / span;\n const leftPosition = percentage * chartWidth;\n\n return (\n <span\n key={`pos-${label.position}`}\n className=\"electropherogram-position-number\"\n style={{\n left: `${leftPosition}px`,\n }}\n >\n {label.label}\n </span>\n );\n })}\n </div>\n );\n };\n\n return (\n <div className=\"electropherogram-sequence-header\">\n {renderSequenceLetters()}\n {renderPositionNumbers()}\n </div>\n );\n };\n\n return (\n <div className=\"electropherogram-container relative\" style={{ width, height }}>\n {renderSequence()}\n <div className=\"electropherogram-chart\">\n <div ref={plotRef} style={{ width: \"100%\", height: \"100%\" }} />\n </div>\n {tooltipElement}\n </div>\n );\n};\n\nexport { Electropherogram };\nexport type { PeakData, ElectropherogramProps };\n"],"names":["PLOT_HEIGHT_OFFSET","Y_AXIS_PADDING_FACTOR","determineBase","item","peakValues","values","val","highestBase","highestValue","base","value","Electropherogram","data","width","height","positionInterval","colorA","CHART_COLORS","colorT","colorG","colorC","plotRef","useRef","theme","usePlotlyTheme","bindTooltip","tooltipElement","useChartTooltip","positions","useMemo","sequence","peakA","peakT","peakG","peakC","aTrace","tTrace","gTrace","cTrace","maxValue","useEffect","plotData","layout","CHART_FONT_FAMILY","config","cancelled","plotElement","loadPlotly","plotly","getLoadedPlotly","jsx","jsxs","renderSequenceLetters","minPosition","maxPosition","chartWidth","index","position","color","span","leftP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ports,Symbol.toStringTag,{value:"Module"});const c=require("react/jsx-runtime"),l=require("react"),U=require("../ChartTooltip/ChartTooltip.cjs"),k=require("../plotly-loader.cjs"),$=require("../../../hooks/use-element-size.cjs"),R=require("../../../hooks/use-plotly-theme.cjs"),D=require("../../../lib/utils.cjs"),G=require("../../../utils/colors.cjs");;/* empty css */const J=-.5,K=r=>r.reduce((n,u)=>n+u,0)/r.length,Q=(r,a)=>{const u=r.map(s=>Math.pow(s-a,2)).reduce((s,h)=>s+h,0)/r.length;return Math.sqrt(u)},Z=(r,a,n,u,s=100)=>{const h=[],p=[],y=(u-n)/(s-1);for(let e=0;e<s;e++){const o=n+e*y;h.push(o);const M=J*Math.pow((o-r)/a,2),q=1/(a*Math.sqrt(2*Math.PI))*Math.exp(M);p.push(q)}return{x:h,y:p}},tt=(r,a,n)=>{const u=Math.ceil((n.end-n.start)/n.size),s=Array(u).fill(0);a.forEach(e=>{if(e>=n.start&&e<=n.end){const o=Math.floor((e-n.start)/n.size);s[o]++}});const h=Math.max(...s),p=Math.max(...r),y=h/p;return r.map(e=>e*y)},et=({dataSeries:r,width:a,height:n,title:u="Histogram",xTitle:s="X Axis",yTitle:h="Frequency",bargap:p=.2,showDistributionLine:y=!1})=>{const e=l.useRef(null),o=R.usePlotlyTheme(),{bindTooltip:M,tooltipElement:q}=U.useChartTooltip({xLabel:s,yLabel:h}),[B,F]=$.useElementSize(),g=a??F.width,x=n??F.height,_=g>0&&x>0,W=a===void 0,L=n===void 0,b=l.useRef({width:g,height:x});b.current={width:g,height:x};const j=l.useRef(!1),C=l.useRef({width:0,height:0}),N=l.useMemo(()=>Array.isArray(r)?r:[r],[r]),T=l.useMemo(()=>N.length>1?"stack":void 0,[N.length]),z=G.CHART_COLORS,v=l.useMemo(()=>N.map((t,m)=>{const d=typeof t.showDistributionLine>"u"?y:t.showDistributionLine;return{...t,color:t.color||z[m%z.length],opacity:d?.5:t.opacity||1,showDistributionLine:d,lineWidth:t.lineWidth||3}}),[N,y,z]),A=o.gridColor,E=l.useMemo(()=>v.map(t=>({type:"histogram",x:t.x,name:t.name,marker:{color:t.color,line:{color:o.paperBg,width:1},opacity:t.opacity},autobinx:t.autobinx,xbins:t.xbins,hoverinfo:"none"})),[v,o]),P=l.useMemo(()=>v.filter(t=>t.showDistributionLine).map(t=>{const m=K(t.x),d=Q(t.x,m),f=Math.min(...t.x),i=Math.max(...t.x),w=i-f,H=f-w*.1,I=i+w*.1,V=t.xbins||{start:H,end:I,size:w/10},S=Z(m,d,H,I,100),X=tt(S.y,t.x,V);return{type:"scatter",x:S.x,y:X,mode:"lines",name:`${t.name} Distribution`,line:{color:t.color,width:t.lineWidth},hoverinfo:"none"}}),[v]),O=l.useMemo(()=>[...E,...P],[E,P]);l.useEffect(()=>{if(!e.current||!_)return;const t={width:b.current.width,height:b.current.height,font:{family:R.CHART_FONT_FAMILY},showlegend:!1,margin:{l:90,r:40,b:80,t:40},xaxis:{title:{text:s,font:{size:16,color:o.textSecondary,family:R.CHART_FONT_FAMILY,weight:400},standoff:20},gridcolor:A,tickcolor:o.tickColor,ticklen:8,tickwidth:1,ticks:"outside",linecolor:o.lineColor,linewidth:1,zeroline:!1,automargin:!0},yaxis:{title:{text:h,font:{size:16,color:o.textSecondary,family:R.CHART_FONT_FAMILY,weight:400},standoff:20},gridcolor:A,tickcolor:o.tickColor,ticklen:8,tickwidth:1,ticks:"outside",linecolor:o.lineColor,linewidth:1,zeroline:!1,rangemode:"tozero",automargin:!0},barmode:T,bargap:p,paper_bgcolor:o.paperBg,plot_bgcolor:o.plotBg},m={responsive:!1,displayModeBar:!1,displaylogo:!1};let d=!1,f=null;return k.loadPlotly().then(i=>{d||!e.current||(i.newPlot(e.current,O,t,m),M(e.current),f=e.current,j.current=!0,C.current={...b.current})}),()=>{d=!0,f&&(k.getLoadedPlotly().purge(f),j.current=!1)}},[_,s,h,p,O,T,A,o,M]),l.useEffect(()=>{const t=e.current;!t||!j.current||g<=0||x<=0||C.current.width===g&&C.current.height===x||(C.current={width:g,height:x},k.getLoadedPlotly().relayout(t,{width:g,height:x}).catch(()=>{}))},[g,x]);const Y=({series:t})=>{const m=t.map((i,w)=>c.jsx(l.Fragment,{children:c.jsxs("div",{className:"histogram-legend-item",children:[c.jsx("span",{className:"histogram-legend-swatch",style:{background:i.color}}),i.name,w<t.length-1&&c.jsx("span",{className:"histogram-legend-divider"})]})},i.name)),d=[],f=6;for(let i=0;i<m.length;i+=f)d.push(c.jsx("div",{className:"histogram-legend-row",children:m.slice(i,i+f)},i));return c.jsx("div",{className:"histogram-legend",children:d})};return c.jsxs("div",{className:D.cn("histogram-container relative",W&&"w-full",L&&"h-full"),style:a===void 0?void 0:{width:a},children:[c.jsxs("div",{className:D.cn("histogram-chart",L&&"flex h-full flex-col"),children:[u&&c.jsx("div",{className:"histogram-title-container",children:c.jsx("h2",{className:"histogram-title",children:u})}),c.jsx("div",{ref:B,className:D.cn(L&&"min-h-0 flex-1"),children:c.jsx("div",{ref:e,style:{width:"100%",height:"100%",margin:"0"}})}),c.jsx(Y,{series:v})]}),q]})};exports.Histogram=et;
|
|
2
2
|
//# sourceMappingURL=Histogram.cjs.map
|
|
@@ -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,EAAIJ,EAAQI,IAAK,CAC/B,MAAMC,EAAIP,EAAQM,EAAID,EACtBF,EAAQ,KAAKI,CAAC,EAEd,MAAMC,EAAWnB,EAAqC,KAAK,KAAKkB,EAAIZ,GAAQI,EAAQ,CAAC,EAC/EU,EAAK,GAAKV,EAAS,KAAK,KAAK,EAAI,KAAK,EAAE,GAAM,KAAK,IAAIS,CAAQ,EACrEJ,EAAQ,KAAKK,CAAC,CAChB,CAEA,MAAO,CAAE,EAAGN,EAAS,EAAGC,CAAA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ACb,SAAA,CAAAF,MAAC,OAAA,CAAK,UAAU,YAAY,MAAO,CAAE,WAAYD,EAAK,OAAS,EAC9DA,EAAK,KACLpE,EAAI8C,EAAO,OAAS,GAAKuB,EAAAA,IAAC,OAAA,CAAK,UAAU,SAAA,CAAU,CAAA,CAAA,CACtD,CAAA,EALmBD,EAAK,IAM1B,CACD,EAEKI,EAAO,CAAA,EACPC,EAAU,EAChB,QAAS,EAAI,EAAG,EAAIN,EAAM,OAAQ,GAAKM,EACrCD,EAAK,KACHH,EAAAA,IAAC,MAAA,CAAI,UAAU,aACZ,SAAAF,EAAM,MAAM,EAAG,EAAIM,CAAO,CAAA,EADI,CAEjC,CAAA,EAIJ,OAAOJ,EAAAA,IAAC,MAAA,CAAI,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,kBACb,eAAC,KAAA,CAAG,UAAU,QAAS,SAAApD,CAAA,CAAM,CAAA,CAC/B,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"}
|
|
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,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,EACA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