@cornerstonejs/core 5.15.1 → 5.16.0

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.
Files changed (44) hide show
  1. package/dist/esm/RenderingEngine/ECGViewport.d.ts +4 -2
  2. package/dist/esm/RenderingEngine/ECGViewport.js +43 -37
  3. package/dist/esm/RenderingEngine/GenericViewport/ECG/CanvasECGRenderPath.d.ts +1 -5
  4. package/dist/esm/RenderingEngine/GenericViewport/ECG/CanvasECGRenderPath.js +30 -87
  5. package/dist/esm/RenderingEngine/GenericViewport/ECG/DefaultECGDataProvider.d.ts +3 -1
  6. package/dist/esm/RenderingEngine/GenericViewport/ECG/DefaultECGDataProvider.js +5 -3
  7. package/dist/esm/RenderingEngine/GenericViewport/ECG/ECGResolvedView.d.ts +39 -3
  8. package/dist/esm/RenderingEngine/GenericViewport/ECG/ECGResolvedView.js +156 -30
  9. package/dist/esm/RenderingEngine/GenericViewport/ECG/ECGViewport.d.ts +21 -8
  10. package/dist/esm/RenderingEngine/GenericViewport/ECG/ECGViewport.js +147 -54
  11. package/dist/esm/RenderingEngine/GenericViewport/ECG/ECGViewportLegacyAdapter.d.ts +9 -3
  12. package/dist/esm/RenderingEngine/GenericViewport/ECG/ECGViewportLegacyAdapter.js +105 -16
  13. package/dist/esm/RenderingEngine/GenericViewport/ECG/ECGViewportTypes.d.ts +47 -22
  14. package/dist/esm/RenderingEngine/GenericViewport/ECG/ecgDrawing.d.ts +29 -0
  15. package/dist/esm/RenderingEngine/GenericViewport/ECG/ecgDrawing.js +167 -0
  16. package/dist/esm/RenderingEngine/GenericViewport/ECG/ecgGeometry.d.ts +53 -0
  17. package/dist/esm/RenderingEngine/GenericViewport/ECG/ecgGeometry.js +127 -0
  18. package/dist/esm/RenderingEngine/GenericViewport/ECG/ecgProjectionSnapshot.js +13 -7
  19. package/dist/esm/RenderingEngine/GenericViewport/ECG/ecgTraceLayouts.d.ts +40 -0
  20. package/dist/esm/RenderingEngine/GenericViewport/ECG/ecgTraceLayouts.js +175 -0
  21. package/dist/esm/RenderingEngine/GenericViewport/ECG/ecgViewportCamera.d.ts +6 -3
  22. package/dist/esm/RenderingEngine/GenericViewport/ECG/ecgViewportCamera.js +21 -0
  23. package/dist/esm/RenderingEngine/GenericViewport/ECG/ecgWaveform.d.ts +54 -0
  24. package/dist/esm/RenderingEngine/GenericViewport/ECG/ecgWaveform.js +95 -0
  25. package/dist/esm/RenderingEngine/GenericViewport/ECG/index.d.ts +3 -1
  26. package/dist/esm/RenderingEngine/GenericViewport/ECG/index.js +2 -0
  27. package/dist/esm/RenderingEngine/GenericViewport/GenericViewport.js +2 -0
  28. package/dist/esm/RenderingEngine/GenericViewport/Planar/PlanarViewport.js +0 -2
  29. package/dist/esm/RenderingEngine/GenericViewport/genericViewportDisplaySetAccess.d.ts +5 -1
  30. package/dist/esm/RenderingEngine/GenericViewport/genericViewportDisplaySetAccess.js +41 -2
  31. package/dist/esm/RenderingEngine/GenericViewport/index.d.ts +2 -2
  32. package/dist/esm/RenderingEngine/GenericViewport/index.js +1 -1
  33. package/dist/esm/index.d.ts +10 -4
  34. package/dist/esm/index.js +8 -2
  35. package/dist/esm/types/ECGViewportProperties.d.ts +6 -0
  36. package/dist/esm/types/ViewportInputOptions.d.ts +2 -0
  37. package/dist/esm/utilities/index.d.ts +2 -1
  38. package/dist/esm/utilities/index.js +2 -1
  39. package/dist/esm/utilities/scroll.js +5 -0
  40. package/dist/esm/utilities/viewportCapabilities.d.ts +5 -0
  41. package/dist/esm/utilities/viewportCapabilities.js +4 -0
  42. package/dist/esm/version.d.ts +1 -1
  43. package/dist/esm/version.js +1 -1
  44. package/package.json +5 -5
@@ -1,52 +1,88 @@
1
1
  import { viewportProjection } from '../viewportProjection.js';
2
2
  import ECGViewport from './ECGViewport.js';
3
+ const LEGACY_VIEW_STATE_PROPERTIES = [
4
+ 'visibleChannels',
5
+ 'sweepSpeed',
6
+ 'sensitivityMmMv',
7
+ 'traceLayout',
8
+ ];
3
9
  class ECGViewportLegacyAdapter extends ECGViewport {
4
10
  async setEcg(imageId) {
5
11
  await this.setDisplaySets({ displaySetId: imageId });
6
12
  }
13
+ getNumberOfSlices() {
14
+ return 1;
15
+ }
16
+ getCanvas() {
17
+ return this.canvas;
18
+ }
7
19
  setChannelVisibility(index, visible) {
8
20
  const waveform = this.getWaveformData();
9
- const dataId = this.getFirstBinding()?.data.id;
10
- if (!waveform || !dataId) {
21
+ if (!waveform) {
11
22
  return;
12
23
  }
13
- const current = this.getDisplaySetPresentation(dataId) || {};
14
- const nextVisibleChannels = new Set(current.visibleChannels || waveform.channels.map((_channel, i) => i));
24
+ const nextVisibleChannels = new Set(this.getViewState().visibleChannels ||
25
+ waveform.channels.map((_channel, i) => i));
15
26
  if (visible) {
16
27
  nextVisibleChannels.add(index);
17
28
  }
18
29
  else {
19
30
  nextVisibleChannels.delete(index);
20
31
  }
21
- this.setDisplaySetPresentation(dataId, {
32
+ this.setViewState({
22
33
  visibleChannels: Array.from(nextVisibleChannels).sort((a, b) => a - b),
23
34
  });
24
35
  }
25
- setProperties(props) {
36
+ setProperties(props = {}) {
26
37
  const dataId = this.getFirstBinding()?.data.id;
27
38
  if (!dataId) {
28
39
  return;
29
40
  }
30
- this.setDisplaySetPresentation(dataId, {
31
- visibleChannels: props.visibleChannels,
41
+ const viewStatePatch = {};
42
+ LEGACY_VIEW_STATE_PROPERTIES.forEach((key) => {
43
+ if (props[key] !== undefined) {
44
+ viewStatePatch[key] = props[key];
45
+ }
32
46
  });
47
+ if (props.traceLayout === undefined && props.layoutType !== undefined) {
48
+ viewStatePatch.traceLayout = props.layoutType;
49
+ }
50
+ if (Object.keys(viewStatePatch).length) {
51
+ this.setViewState(viewStatePatch);
52
+ }
53
+ if (props.showAmplitudeLabels !== undefined) {
54
+ this.setDisplaySetPresentation(dataId, {
55
+ showAmplitudeLabels: props.showAmplitudeLabels,
56
+ });
57
+ }
33
58
  }
34
59
  getProperties() {
35
60
  const dataId = this.getFirstBinding()?.data.id;
61
+ const presentation = dataId
62
+ ? this.getDisplaySetPresentation(dataId)
63
+ : undefined;
64
+ const viewState = this.getViewState();
36
65
  return {
37
- visibleChannels: dataId
38
- ? this.getDisplaySetPresentation(dataId)?.visibleChannels
39
- : undefined,
66
+ visibleChannels: viewState.visibleChannels,
67
+ sweepSpeed: viewState.sweepSpeed,
68
+ sensitivityMmMv: viewState.sensitivityMmMv,
69
+ showAmplitudeLabels: presentation?.showAmplitudeLabels,
70
+ traceLayout: viewState.traceLayout,
40
71
  };
41
72
  }
42
73
  resetProperties() {
43
- const waveform = this.getWaveformData();
44
74
  const dataId = this.getFirstBinding()?.data.id;
45
- if (!waveform || !dataId) {
75
+ if (!dataId) {
46
76
  return;
47
77
  }
78
+ this.setViewState({
79
+ visibleChannels: undefined,
80
+ sweepSpeed: undefined,
81
+ sensitivityMmMv: undefined,
82
+ traceLayout: undefined,
83
+ });
48
84
  this.setDisplaySetPresentation(dataId, {
49
- visibleChannels: waveform.channels.map((_channel, index) => index),
85
+ showAmplitudeLabels: undefined,
50
86
  });
51
87
  }
52
88
  getViewPresentation(selector) {
@@ -63,8 +99,61 @@ class ECGViewportLegacyAdapter extends ECGViewport {
63
99
  this.setViewState(nextViewState);
64
100
  }
65
101
  }
66
- resetCamera() {
67
- return this.resetViewState();
102
+ resetCamera(options) {
103
+ return this.resetViewState(options);
104
+ }
105
+ getCamera() {
106
+ return {
107
+ ...this.getViewState(),
108
+ ...this.getCameraForEvent(),
109
+ };
110
+ }
111
+ setCamera(cameraPatch) {
112
+ if (cameraPatch.timeRange || cameraPatch.valueRange) {
113
+ const nextViewState = {};
114
+ if (cameraPatch.timeRange) {
115
+ nextViewState.timeRange = cameraPatch.timeRange;
116
+ }
117
+ if (cameraPatch.valueRange) {
118
+ nextViewState.valueRange = cameraPatch.valueRange;
119
+ }
120
+ this.setViewState(nextViewState);
121
+ }
122
+ if (cameraPatch.parallelScale !== undefined &&
123
+ cameraPatch.parallelScale > 0) {
124
+ const currentCamera = this.getCamera();
125
+ if (currentCamera.parallelScale) {
126
+ const ratio = currentCamera.parallelScale / cameraPatch.parallelScale;
127
+ const currentZoom = this.getZoom();
128
+ this.setZoom(currentZoom * ratio);
129
+ }
130
+ }
131
+ else if (cameraPatch.scale !== undefined && cameraPatch.scale > 0) {
132
+ this.setZoom(cameraPatch.scale);
133
+ }
134
+ if (cameraPatch.focalPoint) {
135
+ this.setFocalPoint(cameraPatch.focalPoint);
136
+ }
137
+ }
138
+ setFocalPoint(focalPoint) {
139
+ const resolvedView = this.getResolvedView();
140
+ if (!resolvedView) {
141
+ return;
142
+ }
143
+ const z = Math.round(focalPoint[2]);
144
+ if (!resolvedView.findLayoutForZ(z)) {
145
+ return;
146
+ }
147
+ const targetCanvas = resolvedView.worldToCanvas(focalPoint);
148
+ const canvasCenter = [
149
+ this.canvas.clientWidth / 2,
150
+ this.canvas.clientHeight / 2,
151
+ ];
152
+ const currentPan = this.getPan();
153
+ this.setPan([
154
+ currentPan[0] + (canvasCenter[0] - targetCanvas[0]),
155
+ currentPan[1] + (canvasCenter[1] - targetCanvas[1]),
156
+ ]);
68
157
  }
69
158
  }
70
159
  export default ECGViewportLegacyAdapter;
@@ -1,11 +1,42 @@
1
+ import type { AABB2, ViewportInputOptions } from '../../../types/index.js';
1
2
  import type { BaseViewportRenderContext, BasePresentationProps, DataProvider, MountedRendering, RenderPathResolver } from '../ViewportArchitectureTypes.js';
2
3
  import type { ViewportCameraBase } from '../ViewportCameraTypes.js';
4
+ import type ECGResolvedView from './ECGResolvedView.js';
3
5
  export interface ECGChannelData {
4
6
  name: string;
7
+ code?: string;
5
8
  data: Int16Array;
6
9
  min: number;
7
10
  max: number;
11
+ mvPerUnit?: number;
8
12
  }
13
+ export interface ECGTraceLayoutRegistry {
14
+ '12x1': true;
15
+ '6x2': true;
16
+ '3x4': true;
17
+ '3x4+1': true;
18
+ }
19
+ export type ECGTraceLayoutName = keyof ECGTraceLayoutRegistry | (string & {});
20
+ export interface ECGTraceRegion {
21
+ id?: string;
22
+ label?: string;
23
+ bounds: AABB2;
24
+ lead: number | string;
25
+ time?: 'view' | [number, number];
26
+ }
27
+ export interface ECGTraceLayoutDefinition {
28
+ regions: ECGTraceRegion[];
29
+ }
30
+ export type ECGTraceLayout = ECGTraceLayoutName | ECGTraceLayoutDefinition;
31
+ export interface ECGTraceLayoutContext {
32
+ channels: {
33
+ name: string;
34
+ code?: string;
35
+ }[];
36
+ numberOfSamples?: number;
37
+ samplingFrequency?: number;
38
+ }
39
+ export type ECGTraceLayoutFactory = (context: ECGTraceLayoutContext) => ECGTraceLayoutDefinition;
9
40
  export interface ECGWaveformPayload {
10
41
  channels: ECGChannelData[];
11
42
  numberOfChannels: number;
@@ -14,21 +45,25 @@ export interface ECGWaveformPayload {
14
45
  bitsAllocated: number;
15
46
  sampleInterpretation: string;
16
47
  multiplexGroupLabel?: string;
48
+ multiplexGroupIndex?: number;
49
+ numberOfMultiplexGroups?: number;
17
50
  calibration?: unknown;
18
51
  }
19
- export interface ECGPresentationProps extends BasePresentationProps {
20
- visibleChannels?: number[];
21
- }
52
+ export type ECGPresentationProps = BasePresentationProps;
22
53
  export interface ECGViewState extends ViewportCameraBase<[number, number]> {
23
54
  timeRange: [number, number];
24
55
  valueRange: [number, number];
25
56
  scrollOffset?: number;
57
+ sweepSpeed?: number;
58
+ sensitivityMmMv?: number;
59
+ amplitudeScale?: number;
60
+ visibleChannels?: number[];
61
+ traceLayout?: ECGTraceLayout;
26
62
  }
27
63
  export interface ECGProperties {
28
64
  lineWidth?: number;
29
- sweepSpeed?: number;
30
- amplitudeScale?: number;
31
65
  showGrid?: boolean;
66
+ showAmplitudeLabels?: boolean;
32
67
  }
33
68
  export type ECGDataPresentation = ECGPresentationProps & ECGProperties;
34
69
  export interface ECGViewportInput {
@@ -37,33 +72,23 @@ export interface ECGViewportInput {
37
72
  renderingEngineId: string;
38
73
  dataProvider?: DataProvider;
39
74
  renderPathResolver?: RenderPathResolver;
75
+ defaultOptions?: Pick<ViewportInputOptions, 'traceLayout'>;
40
76
  }
41
77
  export type ECGGenericViewportInput = ECGViewportInput;
42
- export interface ChannelLayout {
43
- channel: ECGChannelData;
44
- itemHeight: number;
45
- yOffset: number;
46
- baseline: number;
47
- }
48
- export interface RenderWindowMetrics {
49
- ecgWidth: number;
50
- ecgHeight: number;
51
- channelScale: number;
52
- worldToCanvasRatio: number;
53
- xOffsetCanvas: number;
54
- yOffsetCanvas: number;
55
- }
56
78
  export interface ECGCanvasRenderContext extends BaseViewportRenderContext {
57
79
  type: 'ecg';
58
80
  element: HTMLDivElement;
59
81
  canvas: HTMLCanvasElement;
60
82
  canvasContext: CanvasRenderingContext2D;
83
+ getResolvedView(): ECGResolvedView | undefined;
61
84
  }
62
85
  export type ECGCanvasRendering = MountedRendering<{
63
86
  renderMode: 'signal2d';
64
87
  canvas: HTMLCanvasElement;
65
88
  canvasContext: CanvasRenderingContext2D;
66
- metrics: RenderWindowMetrics;
67
- currentCamera?: ECGViewState;
68
- currentDataPresentation?: ECGDataPresentation;
69
89
  }>;
90
+ export interface ECGResetViewStateOptions {
91
+ resetPan?: boolean;
92
+ resetZoom?: boolean;
93
+ resetTimeRange?: boolean;
94
+ }
@@ -0,0 +1,29 @@
1
+ import type { ECGChannelLayout, ECGRenderMetrics } from './ecgGeometry.js';
2
+ import type { ECGCanvasTransform } from './ECGResolvedView.js';
3
+ import { type ECGChannelLike } from './ecgWaveform.js';
4
+ export declare function drawECGGrid<TChannel extends ECGChannelLike = ECGChannelLike>(ctx: CanvasRenderingContext2D, metrics: Partial<ECGRenderMetrics> & {
5
+ ecgWidth: number;
6
+ ecgHeight: number;
7
+ channelScale: number;
8
+ sweepSpeed?: number;
9
+ sensitivityMmMv?: number;
10
+ showAmplitudeLabels?: boolean;
11
+ pxPerSecond?: number;
12
+ }, options?: {
13
+ showGrid?: boolean;
14
+ bounds?: {
15
+ minX: number;
16
+ minY: number;
17
+ maxX: number;
18
+ maxY: number;
19
+ };
20
+ }, layouts?: Pick<ECGChannelLayout<TChannel>, 'baseline' | 'itemHeight' | 'xOffset'>[]): void;
21
+ export declare function drawECGTraces<TChannel extends ECGChannelLike>(args: {
22
+ ctx: CanvasRenderingContext2D;
23
+ layouts: ECGChannelLayout<TChannel>[];
24
+ lineWidth?: number;
25
+ amplitudeScale?: number;
26
+ }): void;
27
+ export declare function drawECGLabels<TChannel extends ECGChannelLike>(ctx: CanvasRenderingContext2D, layouts: ECGChannelLayout<TChannel>[], worldToCanvasRatio: number): void;
28
+ export declare function drawECGCanvasLabels<TChannel extends ECGChannelLike>(ctx: CanvasRenderingContext2D, layouts: ECGChannelLayout<TChannel>[], transform: ECGCanvasTransform, dpr?: number): void;
29
+ export declare function ensureECGCanvasSize(canvas: HTMLCanvasElement): void;
@@ -0,0 +1,167 @@
1
+ import { ECG_DEFAULT_SWEEP_SPEED_MM_S, ECG_PX_PER_MM, ECG_RENDERING_COLORS, ECG_SECONDS_WIDTH, } from './ecgWaveform.js';
2
+ export function drawECGGrid(ctx, metrics, options, layouts) {
3
+ if (options?.showGrid === false || metrics.channelScale <= 0) {
4
+ return;
5
+ }
6
+ const { ecgWidth, ecgHeight, channelScale, sweepSpeed, sensitivityMmMv, showAmplitudeLabels = false, worldToCanvasRatio = 1, pxPerSecond, } = metrics;
7
+ let minorH;
8
+ let majorH;
9
+ if (sensitivityMmMv != null && sensitivityMmMv > 0) {
10
+ minorH = ECG_PX_PER_MM;
11
+ majorH = ECG_PX_PER_MM * 5;
12
+ }
13
+ else {
14
+ const minLineSpacing = 8;
15
+ let horizontalGridUnit = 100;
16
+ while (horizontalGridUnit * channelScale < minLineSpacing) {
17
+ horizontalGridUnit *= 2;
18
+ }
19
+ minorH = horizontalGridUnit * channelScale;
20
+ majorH = minorH * 5;
21
+ }
22
+ const resolvedSweepSpeed = sweepSpeed != null && sweepSpeed > 0
23
+ ? sweepSpeed
24
+ : ECG_DEFAULT_SWEEP_SPEED_MM_S;
25
+ const resolvedPxPerSecond = pxPerSecond != null && pxPerSecond > 0 ? pxPerSecond : ECG_SECONDS_WIDTH;
26
+ const minorV = resolvedPxPerSecond / resolvedSweepSpeed;
27
+ const majorV = minorV * 5;
28
+ const { minX = 0, minY = 0, maxX = ecgWidth, maxY = ecgHeight, } = options?.bounds ?? {};
29
+ const effectiveMinorH = minorH * worldToCanvasRatio;
30
+ const effectiveMinorV = minorV * worldToCanvasRatio;
31
+ if (effectiveMinorH >= 4 && effectiveMinorV >= 4) {
32
+ ctx.strokeStyle = ECG_RENDERING_COLORS.gridMinor;
33
+ ctx.lineWidth = 0.5;
34
+ ctx.beginPath();
35
+ forEachGridLine(minY, maxY, minorH, (y, k) => {
36
+ if (k % 5 !== 0) {
37
+ ctx.moveTo(minX, y);
38
+ ctx.lineTo(maxX, y);
39
+ }
40
+ });
41
+ forEachGridLine(minX, maxX, minorV, (x, k) => {
42
+ if (k % 5 !== 0) {
43
+ ctx.moveTo(x, minY);
44
+ ctx.lineTo(x, maxY);
45
+ }
46
+ });
47
+ ctx.stroke();
48
+ }
49
+ ctx.strokeStyle = ECG_RENDERING_COLORS.gridMajor;
50
+ ctx.lineWidth = 1;
51
+ ctx.beginPath();
52
+ forEachGridLine(minY, maxY, majorH, (y) => {
53
+ ctx.moveTo(minX, y);
54
+ ctx.lineTo(maxX, y);
55
+ });
56
+ forEachGridLine(minX, maxX, majorV, (x) => {
57
+ ctx.moveTo(x, minY);
58
+ ctx.lineTo(x, maxY);
59
+ });
60
+ ctx.stroke();
61
+ if (showAmplitudeLabels &&
62
+ sensitivityMmMv != null &&
63
+ sensitivityMmMv > 0 &&
64
+ layouts) {
65
+ ctx.fillStyle = ECG_RENDERING_COLORS.label;
66
+ const mvPerMajor = 5 / sensitivityMmMv;
67
+ const fontSize = 10;
68
+ ctx.font = `${fontSize}px monospace`;
69
+ const firstColumnLayouts = layouts.filter((layout) => !layout.xOffset || layout.xOffset === 0);
70
+ if (majorH >= fontSize + 4) {
71
+ firstColumnLayouts.forEach((layout) => {
72
+ const { baseline, itemHeight } = layout;
73
+ const yPlus = baseline - majorH;
74
+ const yMinus = baseline + majorH;
75
+ if (yPlus >= baseline - itemHeight) {
76
+ ctx.fillText(`+${mvPerMajor.toFixed(1)} mV`, 5, yPlus - 2);
77
+ }
78
+ if (yMinus <= baseline + itemHeight) {
79
+ ctx.fillText(`-${mvPerMajor.toFixed(1)} mV`, 5, yMinus - 2);
80
+ }
81
+ });
82
+ }
83
+ }
84
+ }
85
+ export function drawECGTraces(args) {
86
+ const { ctx, layouts, lineWidth = 1, amplitudeScale = 1 } = args;
87
+ layouts.forEach(({ channel, baseline, channelScale, xOffset, width, itemHeight, yOffset, startSample, endSample, }) => {
88
+ const sampleCount = Math.max(1, endSample - startSample);
89
+ const lastSample = Math.min(endSample, channel.data.length);
90
+ ctx.strokeStyle = ECG_RENDERING_COLORS.baseline;
91
+ ctx.lineWidth = 2;
92
+ ctx.beginPath();
93
+ ctx.moveTo(xOffset, baseline);
94
+ ctx.lineTo(xOffset + width, baseline);
95
+ ctx.stroke();
96
+ if (lastSample <= startSample) {
97
+ return;
98
+ }
99
+ ctx.save?.();
100
+ ctx.beginPath?.();
101
+ ctx.rect?.(xOffset, yOffset - itemHeight * 2, width, itemHeight * 3);
102
+ ctx.clip?.();
103
+ ctx.strokeStyle = ECG_RENDERING_COLORS.trace;
104
+ ctx.lineWidth = lineWidth;
105
+ ctx.beginPath();
106
+ const step = width / sampleCount;
107
+ for (let index = startSample; index < lastSample; index++) {
108
+ const x = xOffset + (index - startSample) * step;
109
+ const y = baseline - channel.data[index] * channelScale * amplitudeScale;
110
+ if (index === startSample) {
111
+ ctx.moveTo(x, y);
112
+ }
113
+ else {
114
+ ctx.lineTo(x, y);
115
+ }
116
+ }
117
+ ctx.stroke();
118
+ ctx.restore?.();
119
+ });
120
+ }
121
+ export function drawECGLabels(ctx, layouts, worldToCanvasRatio) {
122
+ const fontSize = 14 / (worldToCanvasRatio || 1);
123
+ layouts.forEach(({ label, itemHeight, yOffset, xOffset }) => {
124
+ const labelY = yOffset - itemHeight + fontSize;
125
+ ctx.font = `${fontSize}px monospace`;
126
+ const textWidth = ctx.measureText(label).width;
127
+ ctx.fillStyle = ECG_RENDERING_COLORS.background;
128
+ ctx.fillRect(xOffset + 5, labelY - fontSize, textWidth + 4, fontSize + 4);
129
+ ctx.fillStyle = ECG_RENDERING_COLORS.label;
130
+ ctx.fillText(label, xOffset + 5, labelY);
131
+ });
132
+ }
133
+ export function drawECGCanvasLabels(ctx, layouts, transform, dpr = 1) {
134
+ const fontSize = 12 * dpr;
135
+ const { effectiveRatio, xOffset, yOffset } = transform;
136
+ ctx.font = `${fontSize}px monospace`;
137
+ layouts.forEach((layout) => {
138
+ const x = (layout.xOffset * effectiveRatio + xOffset + 5) * dpr;
139
+ const y = ((layout.yOffset - layout.itemHeight) * effectiveRatio + yOffset + 2) *
140
+ dpr +
141
+ fontSize;
142
+ const textWidth = ctx.measureText(layout.label).width;
143
+ ctx.fillStyle = ECG_RENDERING_COLORS.background;
144
+ ctx.fillRect(x, y - fontSize, textWidth + 4 * dpr, fontSize + 4 * dpr);
145
+ ctx.fillStyle = ECG_RENDERING_COLORS.label;
146
+ ctx.fillText(layout.label, x, y);
147
+ });
148
+ }
149
+ function forEachGridLine(min, max, step, draw) {
150
+ if (!(step > 0)) {
151
+ return;
152
+ }
153
+ for (let k = Math.ceil(min / step); k * step <= max; k++) {
154
+ draw(k * step, Math.abs(k));
155
+ }
156
+ }
157
+ export function ensureECGCanvasSize(canvas) {
158
+ const dpr = window.devicePixelRatio || 1;
159
+ const width = Math.max(1, canvas.clientWidth || canvas.width || 1);
160
+ const height = Math.max(1, canvas.clientHeight || canvas.height || 1);
161
+ const nextWidth = Math.floor(width * dpr);
162
+ const nextHeight = Math.floor(height * dpr);
163
+ if (canvas.width !== nextWidth || canvas.height !== nextHeight) {
164
+ canvas.width = nextWidth;
165
+ canvas.height = nextHeight;
166
+ }
167
+ }
@@ -0,0 +1,53 @@
1
+ import type { ECGTraceCell } from './ecgTraceLayouts.js';
2
+ import { type ECGChannelLike } from './ecgWaveform.js';
3
+ export interface ECGChannelLayout<TChannel extends ECGChannelLike = ECGChannelLike> {
4
+ channel: TChannel;
5
+ label: string;
6
+ itemHeight: number;
7
+ yOffset: number;
8
+ baseline: number;
9
+ channelScale: number;
10
+ xOffset: number;
11
+ width: number;
12
+ startSample: number;
13
+ endSample: number;
14
+ leadIndex: number;
15
+ regionIndex: number;
16
+ }
17
+ export interface ECGRenderMetrics {
18
+ ecgWidth: number;
19
+ ecgHeight: number;
20
+ channelScale: number;
21
+ worldToCanvasRatio: number;
22
+ xOffsetCanvas: number;
23
+ yOffsetCanvas: number;
24
+ pxPerSecond: number;
25
+ sweepSpeed: number;
26
+ }
27
+ export declare function getECGWorldWidth(args: {
28
+ cells: ECGTraceCell[];
29
+ numberOfSamples: number;
30
+ samplingFrequency: number;
31
+ pxPerSecond: number;
32
+ }): number;
33
+ export declare function computeECGTraceGeometry<TChannel extends ECGChannelLike>(args: {
34
+ cells: ECGTraceCell<TChannel>[];
35
+ ecgWidth: number;
36
+ targetHeight: number;
37
+ sensitivityMmMv?: number;
38
+ }): {
39
+ channelScale: number;
40
+ ecgHeight: number;
41
+ layouts: ECGChannelLayout<TChannel>[];
42
+ };
43
+ export declare function computeECGRenderMetrics<TChannel extends ECGChannelLike>(args: {
44
+ canvas: HTMLCanvasElement;
45
+ cells: ECGTraceCell<TChannel>[];
46
+ numberOfSamples: number;
47
+ samplingFrequency: number;
48
+ sweepSpeed?: number;
49
+ sensitivityMmMv?: number;
50
+ }): {
51
+ metrics: ECGRenderMetrics;
52
+ layouts: ECGChannelLayout<TChannel>[];
53
+ };
@@ -0,0 +1,127 @@
1
+ import { ECG_CHANNEL_SPACING, ECG_DEFAULT_SWEEP_SPEED_MM_S, ECG_PX_PER_MM, getECGChannelMvPerUnit, } from './ecgWaveform.js';
2
+ const AMPLITUDE_HEADROOM = 1.25;
3
+ export function getECGWorldWidth(args) {
4
+ const { cells, numberOfSamples, samplingFrequency, pxPerSecond } = args;
5
+ let recordPerWidth = 0;
6
+ cells.forEach(({ visible, region, startSample, endSample }) => {
7
+ const widthFraction = region.bounds.maxX - region.bounds.minX;
8
+ if (visible && widthFraction > 0) {
9
+ recordPerWidth = Math.max(recordPerWidth, (endSample - startSample) / numberOfSamples / widthFraction);
10
+ }
11
+ });
12
+ const durationSeconds = numberOfSamples / samplingFrequency;
13
+ return Math.max(1, Math.ceil(durationSeconds * (recordPerWidth || 1) * pxPerSecond));
14
+ }
15
+ export function computeECGTraceGeometry(args) {
16
+ const { cells, ecgWidth, targetHeight, sensitivityMmMv } = args;
17
+ const bands = getVisibleBands(cells);
18
+ if (!bands.length) {
19
+ return { channelScale: 1, ecgHeight: 1, layouts: [] };
20
+ }
21
+ const isCalibrated = sensitivityMmMv != null && sensitivityMmMv > 0;
22
+ const totalExtent = bands.reduce((total, band) => total + (band.maxY - band.minY), 0);
23
+ const fractions = bands.map((band) => totalExtent > 0 ? (band.maxY - band.minY) / totalExtent : 1 / bands.length);
24
+ const range = (cell) => Math.max(1, cell.channel.max - cell.channel.min);
25
+ const rangeMv = (cell) => range(cell) * getECGChannelMvPerUnit(cell.channel);
26
+ let autoFitScale = 0;
27
+ let ecgHeight;
28
+ if (isCalibrated) {
29
+ ecgHeight = Math.max(...bands.map((band, index) => (Math.max(...band.cells.map((cell) => range(cell) * scaleOf(cell) * AMPLITUDE_HEADROOM)) +
30
+ ECG_CHANNEL_SPACING) /
31
+ fractions[index]));
32
+ }
33
+ else {
34
+ autoFitScale = Math.max(Number.EPSILON, Math.min(...bands.map((band, index) => (targetHeight * fractions[index] - ECG_CHANNEL_SPACING) /
35
+ (Math.max(...band.cells.map(rangeMv)) * AMPLITUDE_HEADROOM))));
36
+ ecgHeight = targetHeight;
37
+ }
38
+ function scaleOf(cell) {
39
+ return isCalibrated
40
+ ? sensitivityMmMv * ECG_PX_PER_MM * getECGChannelMvPerUnit(cell.channel)
41
+ : autoFitScale * getECGChannelMvPerUnit(cell.channel);
42
+ }
43
+ const layouts = [];
44
+ let top = 0;
45
+ bands.forEach((band, index) => {
46
+ const bandHeight = fractions[index] * ecgHeight;
47
+ const yOffset = top + bandHeight;
48
+ const itemHeight = bandHeight - ECG_CHANNEL_SPACING;
49
+ const traceHeight = Math.max(...band.cells.map((cell) => range(cell) * scaleOf(cell) * AMPLITUDE_HEADROOM));
50
+ const lowest = Math.min(0, ...band.cells.map((cell) => cell.channel.min * scaleOf(cell)));
51
+ const baseline = yOffset - Math.max(0, itemHeight - traceHeight) / 2 + lowest;
52
+ band.cells.forEach((cell) => {
53
+ const { bounds } = cell.region;
54
+ layouts.push({
55
+ channel: cell.channel,
56
+ label: cell.label,
57
+ itemHeight,
58
+ yOffset,
59
+ baseline,
60
+ channelScale: scaleOf(cell),
61
+ xOffset: bounds.minX * ecgWidth,
62
+ width: (bounds.maxX - bounds.minX) * ecgWidth,
63
+ startSample: cell.startSample,
64
+ endSample: cell.endSample,
65
+ leadIndex: cell.leadIndex,
66
+ regionIndex: cell.regionIndex,
67
+ });
68
+ });
69
+ top = yOffset;
70
+ });
71
+ const firstVisible = bands[0].cells[0];
72
+ return {
73
+ channelScale: scaleOf(firstVisible),
74
+ ecgHeight,
75
+ layouts,
76
+ };
77
+ }
78
+ function getVisibleBands(cells) {
79
+ const bands = new Map();
80
+ cells.forEach((cell) => {
81
+ if (!cell.visible) {
82
+ return;
83
+ }
84
+ const { minY, maxY } = cell.region.bounds;
85
+ const key = `${minY.toFixed(6)}:${maxY.toFixed(6)}`;
86
+ const band = bands.get(key) ?? { minY, maxY, cells: [] };
87
+ band.cells.push(cell);
88
+ bands.set(key, band);
89
+ });
90
+ return Array.from(bands.values()).sort((a, b) => a.minY - b.minY);
91
+ }
92
+ export function computeECGRenderMetrics(args) {
93
+ const { canvas, cells, numberOfSamples, samplingFrequency, sweepSpeed, sensitivityMmMv, } = args;
94
+ const resolvedSweepSpeed = sweepSpeed ?? ECG_DEFAULT_SWEEP_SPEED_MM_S;
95
+ const pxPerSecond = resolvedSweepSpeed * ECG_PX_PER_MM;
96
+ const ecgWidth = getECGWorldWidth({
97
+ cells,
98
+ numberOfSamples,
99
+ samplingFrequency,
100
+ pxPerSecond,
101
+ });
102
+ const canvasAspect = canvas.clientHeight && canvas.clientWidth
103
+ ? canvas.clientHeight / canvas.clientWidth
104
+ : 2 / 3;
105
+ const { channelScale, ecgHeight, layouts } = computeECGTraceGeometry({
106
+ cells,
107
+ ecgWidth,
108
+ targetHeight: ecgWidth * canvasAspect,
109
+ sensitivityMmMv,
110
+ });
111
+ const clientWidth = canvas.clientWidth || canvas.width || ecgWidth;
112
+ const clientHeight = canvas.clientHeight || canvas.height || ecgHeight;
113
+ const worldToCanvasRatio = Math.min(clientWidth / Math.max(1, ecgWidth), clientHeight / Math.max(1, ecgHeight));
114
+ return {
115
+ metrics: {
116
+ ecgWidth,
117
+ ecgHeight,
118
+ channelScale,
119
+ worldToCanvasRatio,
120
+ xOffsetCanvas: (clientWidth - ecgWidth * worldToCanvasRatio) / 2,
121
+ yOffsetCanvas: (clientHeight - ecgHeight * worldToCanvasRatio) / 2,
122
+ pxPerSecond,
123
+ sweepSpeed: resolvedSweepSpeed,
124
+ },
125
+ layouts,
126
+ };
127
+ }